text:
Q: Free tool to send binary data to IP address and port? I'm using windows 7. There is application that is listening to an ip address and port. It waits for binary data to come and process it. Currently, I'm testing the application now.
Is there a free tool that I can use to send binary data to an ip address and port?
I had tried using telnet to connect to the ip address and port, but unfortunately I cannot enter binary data in the command prompt.
For example, I want to enter this binary data (I show it here in hex):
FFFAFEF0

A: If you don't mind installing it, Python makes interactive socket use pretty easy. Here's an example of an interactive sessions with a HTTP connection, for demonstration purposes:
>>> import socket
>>> sock = socket.socket()
>>> sock.connect(("www.google.com", 80))
>>> sock.send("GET / HTTP/1.1\r\nHost: www.google.com\r\n\r\n")
40
>>> sock.recv(64)
'HTTP/1.1 302 Found\r\nLocation: http://www.google.co.uk/\r\nCache-Co'

For binary data you could just do something like:
sock.send("\xff\xfa\xfe\xf0")

The sockets API uses strings in Python, but as you can see it's pretty easy to send arbitrary bytes.
I can understand if you didn't want to install Python just for that (although it's got a pretty simple installer), but personally I think it's a reasonable tool for the job in this case - you've got all the flexibility of a powerful language there but you don't have to use it.
Alternatively you can get netcat for windows, which should be able to accept input from a file with redirect (which I'm pretty sure DOS supports). So, if you put your binary data into a file binary_data.bin you could do:
nc hostname.org 1234 < binary_data.bin

A: I found a freeware tool named TCP/IP Builder.
But if you found a better free tool, please let me know.


text:
Q: C# printer prints just a quarter of the submitted picture Greetings,
i have a little application which should be able to print single jpeg files to a network printer. Now the printing itself works but the problem is that the printer prints just the upper left quarter of the picture, no matter which picture i use. Typically the picture is 1800x1200 px and in jpeg format.
The code im using to print is the following:
protected void Button5_Click(object sender, EventArgs e)
{
    PrintDocument doc = new PrintDocument();
    doc.PrinterSettings.PrinterName = "KONICA MINOLTA C250/C250P PCL";
    doc.PrintPage += this.Doc_PrintPage;
    if(doc.PrinterSettings.IsValid)
        doc.Print();
}

private void Doc_PrintPage(object sender, PrintPageEventArgs e)
{
    float x = e.MarginBounds.Left;
    float y = e.MarginBounds.Top;

    e.Graphics.DrawImage((System.Drawing.Image)ShowImg(bild.ToolTip),x, y);
}

The ShowImg() function just returns a Bitmap with the picture from a network drive.
Does anyone know why this strange behaviour happens?
Thanks in advance
xen

A: What are MarginBounds.Height/Width?
Take a look at image dimensions too...
private void Doc_PrintPage(object sender, PrintPageEventArgs e)
{
    float x = e.MarginBounds.Left;
    float y = e.MarginBounds.Top;
    var img = (System.Drawing.Image)ShowImg(bild.ToolTip);

    Debug.Print("img: {0}x{1}", img.Width, img.Height);
    Debug.Print("margins: {0}x{1}", e.MarginBounds.Width, e.MarginBounds.Height);

    e.Graphics.DrawImage(img,x, y);
}

I hope you'll see the difference between their dimensions.

A: Found out that i was using 300dpi for my jpeg where the printer just supported 90dpi. Silly me :)

redpajama_set_name: RedPajamaStackExchange


text: Q: COP and input work in a refrigerator Where can i find a COP and input work requierd in a standard modern refrigerator? I need a sample refrigerator, so that I can calculate the heat disposed to the surrounding and use that to design an heat exchanger.


text: Q: iOS + FMDatabase: DB opens, but can't be queried I'm using FMDatabase (subclassed to be a singleton) as a wrapper for an SQLite3 database. I am trying to write a feature in my app that updates the database over the air if necessary. After the update I set databaseSingleton = nil, and then call the accessor again to create a new singleton with the new DB. For some reason this results in some strange behavior. For example, if I call [FMDatabase open] it returns TRUE, but when I try querying it fails [FMDatabase databaseExists] and logs that the DB is not open. This essentially means that the database pointer is simultaneously satisfying if (db) and if (!db). I've tried logging the object to the console but it throws an access error, which leads me to believe it doesn't actually exist. Can anyone think of what could be doing this? Or more importantly, how it's even possible for those two conditions to be true?


text:
Q: c# choose printer only working in main form I want to print a DataGridView.
My code to print the view works finde but I've encountered a problem:
The code to choose the printer
PrintDocument _printDocument = new PrintDocument();
PrintDialog printDialog = new PrintDialog();
printDialog.Document = _printDocument;
printDialog.UseEXDialog = true;
if (DialogResult.OK == printDialog.ShowDialog())
{
     _printDocument.DocumentName = "Test";
}

PrintPreviewDialog objPPdialog = new PrintPreviewDialog();
objPPdialog.Document = _printDocument;
objPPdialog.ShowDialog();

only works in my main Form (Form1).
In other forms he doesen't find a printer.
Print dialog in other forms
What could be the reason for this?


text:
Q: ffmpeg - Overlay one video on to another I want to overlay one video on to another.I have two videos with same time duration.
Aim is to make upper video little transparent so that one can see whats happening in background video.
I've tried below command :
String command="ffmpeg -y -i /sdcard/videokit/two.mp4 -i /sdcard/videokit/inone.mp4 -filter_complex [0:v][1:v]overlay=100:100:eof_action=pass[v] -map [v] /sdcard/videokit/output.mp4";

In this command upper video isn't matching(In context of height and width) with video at back.
Confusion :  There may be a possibility that background video wont have same height width as upper video cause it comes dynamically in that case how should I manage..!!!
Any help or suggestions would be appreciated.

A: The command below resizes the upper video to match the base video and also gives it transparency.
ffmpeg -y -i /sdcard/videokit/two.mp4 -i /sdcard/videokit/inone.mp4 -filter_complex "[1:v][0:v]scale2ref[ua][b];[ua]setsar=1,format=yuva444p,colorchannelmixer=aa=0.5[u];[b][u]overlay=eof_action=pass[v]" -map [v] /sdcard/videokit/output.mp4

The scale2ref resizes the second video to match the dimensions of the first. Then the colorchannelmixer tweaks the alpha channel to give it 50% transparency.


text:
Q: Azure Kudu access for users with Lighthouse delegated permissions I have delegated access to Azure resources in a third-party tenant using Lighthouse, and this works fine via the portal; users receive the roles expected (typically Contributor).
However, they are unable to access Kudu (at webappname.scm.azurewebsites.net), receiving an error;

Selected user account does not exist in tenant 'Tenant Name' and
cannot access the application 'abfa0a7c-a6b6-4736-8310-5855508787cd'
in that tenant. The account needs to be added as an external user in
the tenant first. Please use a different account.

If the same user account is added as a guest to the third-party tenant and given the same role, they can access Kudu as expected.
It's clear that Kudu is expecting/demanding an account in the same tenant as the application, but Azure Lighthouse delegated permissions is all about not having to do that.
Is there something I'm missing, or another role that needs granting?

A: @PhilD, Thanks for the detailed description of the scenario. I have also posted this on your Q&A thread.
Currently, Kudu is not compatible with Lighthouse-delegated permissions.
Our product engineering team is working on it; however, we do not have an exact ETA to share.
We're expecting it to be available in a few months. Please note that this timeline is just an estimate and is subject to change, depending on a myriad of factors.
I have relayed the feedback internally to our product engineering team and it's being tracked.
-On a side note, as mentioned in this Kudu wiki :
"Only those with Contributor / Owner access (to be exact, with microsoft.web/sites/publish/action or, for slot, microsoft.web/sites/slots/publish/action) can access to Kudu (SCM)."
Much appreciate your valuable feedback on this. Thanks for your patience!


text:
Q: Why is the switch operator only reading default and not the other instructions I am working on an exercise:

You have a  matrix written in a file and given some commands you have to shift
(left or right) or (up or down) in a circular way a certain row or column and after given the instructions you print it out.

This is my code so far. The problem is that it is like the switch operator is not reading anything. It is just printing "Exiting" which is in the default block.
I know that it is far from done but I just need a bit of help with my problem.
To be clear, I only need help with why the switch statement isn't working. I want to try to solve the rest of the problem myself. I just need help with that specific part.
#include <stdio.h>
#include <stdlib.h>
#define N 30

int main()
{
    int v[N][N];
    int i=0,p,j=0;
    int command1;
    int command2;
    int times;
    int times2=0;
    FILE*file;
    file=fopen("file","r");
    if(file==NULL)
    {
        printf("ERROR in the file....");
        exit(1);
    }
    for(i=0; i<3; i++)
    {
        for(j=0; j<3; j++)
        {
            fscanf(file,"%d ",&v[i][j]);
        }
    }

    printf("Original Matrix: \n");
    for(i=0; i<3; i++)
    {
        for(j=0; j<3; j++)
        {
            printf("%d ",v[i][j]);
        }
        printf("\n");
    }

    printf("\n\n");
    printf("Choose:\n1:Rows\n2:Columns\n3:Exiting\n");
    {
        scanf("%d",&command1);
    }

    switch (command1)
    {
    case '1':
    {
        printf("Choose:\n1:Shift left\n2:Shift right\n");
        scanf("%d",&command2);
        if(command2==1)
        {
            printf("Which row:\n");
            scanf("%d",&p);
            printf("\n");
            printf("How many times:\n");
            scanf("%d",&times);
            while(times2<times && i<3)
            {
                v[p][i]= v[p][i+1];
                v[p][i+1]=v[p][i+2];
                v[p][i+2]=v[p][i];

                i++;
                times2++;
            }
            printf("\nNew Matrix:\n");
            for(i=0; i<3; i++)
            {
                for(j=0; j<3; j++)
                {
                    printf("%d ",&v[i][j]);
                }
                printf("\n");
            }

        }
    }
    break;
    case '2':
    {
        printf("Something Something");
    }
    default:
        printf("\nExiting");
    }

    return 0;
}

A: Make that case 1: and case 2: without any single quotes. When you use '1' and '2' it's checking for chars, but command1 is an int.
Make sure to add a break; statement to the second case as well so it doesn't fall through to the default: case.


text:
Q: ssrs error - The attempt to connect to the report server failed I'm running a windows network service on a clients server. It's job is to periodically check the database for any unprinted dockets, and print them to a network printer.
The issue is that whenever it attempts to print a report it gets the following error -
The attempt to connect to the report server failed.  Check your connection information and that the report server is a compatible version.
The ssrs web service can connect to the report server, and I have an instance of our main desktop application running on the server, and it can open reports.
Any help would be greatly appreciated.

A: I found the issue. The server report URI was defaulting to localhost\ReportServer. This was fine when I ran on my own machine, but was causing an issue on the server (even though reporting services is on the server)
I changed it to a named instance, and it's working.
(serverReport.ReportServerUrl = new Uri("ServerName\ReportServer");)
Thanks


text:
Q: Add a row number to result set of a SQL query I have a simple select statement. I want to add a temporary column that will represent number the of rows in my result set. I tried this -
declare @num int
set @num = 0;
select t.A, t.B, t.C, (@count + 1) as number
from tableZ as t

It assigns the 1 to all rows. I tried @count = @count + 1 and it did not work.
How do I do this thing in a simple manner?
thanks.

A: The typical pattern would be as follows, but you need to actually define how the ordering should be applied (since a table is, by definition, an unordered bag of rows). One way to do that if you don't care about a specific order otherwise is to use the leading key(s) of a covering index, the leading key(s) of the clustered index, or the columns in any group by / order by clauses. In this case I'll assume A is the single-column clustering key for t:
SELECT t.A, t.B, t.C, number = ROW_NUMBER() OVER (ORDER BY t.A)
  FROM dbo.tableZ AS t
  ORDER BY t.A;

If you truly don't care about order, you can generate arbitrary/nondeterministic row numbering using:
ROW_NUMBER() OVER (ORDER BY @@SPID)

-- or for serial plans

ROW_NUMBER() OVER (ORDER BY @@TRANCOUNT)

Little tricks I picked up from Paul White in this article (see "Paul's Solution").
Not sure what the variables in your question are supposed to represent (they don't match).

A: SELECT
    t.A,
    t.B,
    t.C,
    ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS number
FROM tableZ AS t

See working example at SQLFiddle
Of course, you may want to define the row-numbering order – if so, just swap OVER (ORDER BY (SELECT 1)) for, e.g., OVER (ORDER BY t.C), like in a normal ORDER BY clause.


text:
Q: How to use console.log for a custom function? Hi following is my code:
const tst = require("trucksim-telemetry")

const telemetry = tst()

function update(data) {
  console.log('Speed Limit:',data.navigation.speedLimit)
  console.log('Speed:',data.truck.speed)
  console.log('Controls:',data.controls.input)
  console.log('ADAS:',data.truck.cruiseControl.enabled)
}

telemetry.watch({interval: 12}, update)

I can log everything from the function update(data) successfully into a txt file but I want to also log
telemetry.watch({interval: 12}, update)

such as it shows me time (ms): 0 12 24 and so on till I close the script. I tried using setinterval function but it sometimes logs an interval multiple times. I'm sorry if my question is vague I'm new to javascript*.

A: You can try capturing the time from when you start running the script, and have the update() subtract from that value every time it is invoked:
const now = new Date() // capture start time
const telemetry = tst()

function update(data) {
  console.log('Time (ms):', new Date() - now) // time elapsed in ms
  console.log('Speed Limit:',data.navigation.speedLimit)
  console.log('Speed:',data.truck.speed)
  console.log('Controls:',data.controls.input)
  console.log('ADAS:',data.truck.cruiseControl.enabled)
}

telemetry.watch({interval: 12}, update)

Alternatively, if you are trying to plot with multiples of 12, you can add a counter and multiply that by 12ms
let counter = 0
const telemetry = tst()

function update(data) {
  counter++
  console.log('Time (ms):', counter*12) // difference is in ms
  console.log('Speed Limit:',data.navigation.speedLimit)
  console.log('Speed:',data.truck.speed)
  console.log('Controls:',data.controls.input)
  console.log('ADAS:',data.truck.cruiseControl.enabled)
}

telemetry.watch({interval: 12}, update)

A: The JavaScript Date class keeps time by milliseconds. So you can handle this by putting this line just before the .watch call.
const start = new Date();

then in the update function add
console.log ('Time:'.(Date.now - start));


text:
Q: Without access to argv[0], how do I get the program name? I know the program name is passed as the first argument, and next simple example will print it to the standard output :
#include <iostream>
int main ( int argc, char *argv[] )
{
  std::cout<<argv[0]<<std::endl;
}

Is there a function to get the program name?
EDIT
I am starting the program from the shell, and the above code will always print the program name (I am using fedora 9, but I am sure it works in other distros).
I have found that /proc/self/ directory might contain what I am looking for, but I couldn't find what exactly in that directory.

A: This is not guaranteed.
Usually, argv[0] holds the executable name but one can call your executable using execve and set it to something else.
In a word: don't rely on this.

A: No, it depends entirely on what the parent program puts in there.
The exec family of functions allow the executable name to be totally different to the argument passed in, and this is supported by the ISO C standard.

If the value of argc is greater than zero, the string pointed to by argv[0] represents the program name; argv[0][0] shall be the null character if the program name is not available from the host environment.

So no, it's only the program name if the name is available. And the section before that states:

If the value of argc is greater than zero, the array members argv[0] through argv[argc-1] inclusive shall contain pointers to strings, which are given implementation-defined values by the host environment prior to program startup.

(my italics).
So, even their values are not dictated by the standard, it's up to the implementation entirely. This means that the program name can be empty if the host environment doesn't provide it, and anything else if the host environment does provide it.
However, implementation-defined has a specific meaning in the ISO standards - the implementation must document how it works. So even UNIX, which can put anything it likes into argv[0] with the exec family of calls, has to (and does) document it.
Similarly (thanks to Chubsdad), C++03 states:

"If argc is nonzero these arguments shall be supplied in argv[0] through argv[argc-1] as pointers to the initial characters of null-terminated multibyte strings (NTMBSs) (17.3.2.1.3.2) and argv[0] shall be the pointer to the initial character of a NTMBS that represents the name used to invoke the program or "".

So, even there, argv[0] may not contain anything and, even if it does, "represents the name" is a very vague requirement. It doesn't have to be the full pathname of the executable or even contain the command used to invoke it

Another way to do it under Linux is with the proc filesystem. I think /proc/self/exe is a link to the executable file.
Wikipedia has an entry for the procfs filesystem with lots of goodies.

A: You can determine the pid of your process using getpid() and then inspect the contents of /proc/[pid number] using standard I/O tools.

A: No, there is no such function. Linux stores the program name in __progname, but that's not a public interface. In case you want to use this for warnings/error messages, use the err(3) functions.
If you want the full path of the running program, call readlink on /proc/self/exe:
char *program_path()
{
    char *path = malloc(PATH_MAX);
    if (path != NULL) {
        if (readlink("/proc/self/exe", path, PATH_MAX) == -1) {
            free(path);
            path = NULL;
        }
    }
    return path;
}

(I believe __progname is set to the basename of argv[0]. Check out the glibc sources to be sure.)

A: If you use GLib you can use the function g_get_prgname().  On Win32 it calls GetModuleFileNameW(), on everything else it appears to return NULL though.

A: GLIBC-specific solution:
#include <errno.h>
...
fprintf(stderr, "Program name is %s\n", program_invocation_name);

From man invocation_name:

program_invocation_name contains the name that was used to invoke the calling program.  This is the same as the value of argv[0] in main(), with the difference that the scope of program_invocation_name is global.
program_invocation_short_name contains the basename component of name that was used to invoke the calling program.  That is, it is the same  value  as  program_invocation_name, with all text up to and including the final slash (/), if any, removed.


text:
Q: Uncaught SyntaxError: Кавычки ломают title с БД У меня с БД приходят значение айтемов для таблицы.
В 'title' могут приходить названия внутри которых могут быть разные кавычки: ' " `

Использовать ' - невозможно по причине несовместимости с IE11.
' и " - все равно ломают несколько важных документов.
Как лучше добавить title в объект, что бы не было :" Uncaught SyntaxError: Unexpected identifier " и все тайтлы были валидными?
replace не очень помог, так как он воспринимает как строку только первую часть текста до кавычки...

A: Сделайте конкатенацию строк, сейчас у вас просто прерывается строка и вылетает эксепшн:
title: 'строка' + "с" + 'конкатенацией'

Либо надо делать экранирование символов, то есть если у вас встречается символ ' или " до последнего закрывающего символа, то экранируйте его:
title: 'строка\' \"с \" \"экранированием\'\"'

Ещё вы можете написать свой парсер для JSON.parse, читайте про reviver, там вы можете например задать обработчик (который принимает key, value), проверять ключ, если title, то делать кастомную обработку, иначе просто верните value.


text:
Q: Sending Email to multiple recipients in VB.NET I'd like to ask if sending email to multiple recipients in vb.net is possible?
What I mean here is I want to create a program that sends email to multiple recipients, unlike the usual program which the email address , the subject and other email attributes are hard coded, what I want is hopefully the email address, message body, is came from the database.
So basically if i will going to call a form to send the email, it will fetch the data from the database server providing me a list of recipients and their other details.
Can someone show me how to do that? I would be grateful if someone could show me how to do it. Thanks!

A: It's to simple :
Public Function Snd(ByVal frm As String, ByVal tooo As List(Of String), _
                        ByVal pass As String, ByVal hst As String, _
                        ByVal sbj As String, ByVal bdy As String, _
                        ByVal lAtt As List(Of String)) As String

        Dim ml As New MailMessage()

        ml.From = New MailAddress(frm)
        For Each sA As String In tooo
            ml.To.Add(sA)
        Next

        ml.Subject = sbj
        ml.Body = bdy
        For Each sA As String In lAtt
            ml.Attachments.Add(New Attachment(sA))
        Next
        '"smtp.gmail.com" for gmail
        '"smtp.live.com"   for hotmail
        Dim SMTPServer As New SmtpClient(hst)
        SMTPServer.Port = 587
        SMTPServer.Credentials = New System.Net.NetworkCredential(frm, pass)
        SMTPServer.EnableSsl = hst <> "smtp.mail.yahoo.com"

        Try
            SMTPServer.Send(ml)
            Return "Sent"
        Catch ex As SmtpException
            Return ex.Message
        End Try
        Return ""
    End Function

Check this : sending email using smtp


text:
Q: AVCaptureVideoPreviewLayer crash application on release I have problem with AVCaptureVideoPreviewLayer. I create it like that:
self.previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:session];

session is my AVCaptureSession object. Its is initialized already. When I pop from view controller my app gets crash. I dont even use this vatiable and I get crash anyway. I get EXC_BAD_ACCESS code = 1;. self.previewLayer is my class object. I declarate is in my class, then make it property with retain and nonatomic and @synthesize. I use code from RosyWritter and only difference is that I use AVCaptureVideoPreviewLayer. It seems like I heve problem with release this object. Can anybody tell me what I do wrong?
edit
I finally resolved it. It occurs that I dont unregister videoOut delegate :)
PS: I use automatic reference counting

A: Can you please provide some more details about, how you are accessing AVCaptureVideoPreviewLayer. Please paste crash log if you have.
please try your code simulation with below code of block.
if ([self captureManager] == nil) {
        captureManager = [[AVCamCaptureManager alloc] init];
        captureManager.delegate = self;

        if ([[self captureManager] setupSession] && _captureVideoPreviewLayer == nil) {
            // Create video preview layer and add it to the UI
            _captureVideoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:[[self captureManager] session]];

            if ([_captureVideoPreviewLayer isOrientationSupported]) {
                [_captureVideoPreviewLayer setOrientation:AVCaptureVideoOrientationPortrait];
            }

            [_captureVideoPreviewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];

            // Start the session. This is done asychronously since -startRunning doesn't return until the session is running.
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                [[[self captureManager] session] startRunning];
            });
        }
    }

Hope it helps. Please check and let me know if we have to go with another solution.


text:
Q: How to extract data from pyplot figure I already checked out this question, but it didn't solve my problem.
Hello! I have a pyplot figure:
def foo(data):
        fig, ax = plt. subplots(figsize=(20, 10), dpi=100)
    xaxis = (list with x values)
    yaxis = (numpy array with y values)
    ax.plot(xaxis, yaxis)

I would like foo() to return the x and y values. I understand that I could just do
return xvalues, yvalues

But I'd like to extract the data from the figure.
I've tried my best to read the pyplot documentation, but I'm still pretty new to it, so if I'm doing something stupid, please let me know!
EDIT: I wasn't really descriptive enough, sorry. I'm trying to write a unit test for a module where one of the methods is to generate and save a graph. foo() doesn't necessarily have to return the x and y data, I'd just like it to return something I can use to make sure it generated the plot properly. I'm aware that matplotlib has testing stuff built in, but I would have to restructure a lot of my code to make it work.

A: I think the following code does what you want for a simple line plot:
import numpy as np
import matplotlib.pyplot as plt

def foo(xaxis, yaxis):
    fig, ax = plt. subplots(figsize=(20, 10), dpi=100)
    curve = ax.plot(xaxis, yaxis)
    # curve = [Line2D object]
    return curve[0].get_xdata(), curve[0].get_ydata()

x,y = foo(range(10), range(0,20,2))
print(x,y)


text:
Q: Why is the "top" command showing a CPU usage of 799%? I am running a process in a 4 core Ubuntu server. However, the top command shows that the CPU usage is 799% all the time.
How can this be possible? I know for multi-core CPUs, more than 100% CPU usage is expected, but 799% is a really high value.
Can anybody explain to me why and when this could happen?
As per suggestion of Gregory MOUSSAT, using htop, I got the following output:

A: The scale used by top is 100% when a core is fully used. Or when one core is 20% and a second one is 80%. This leads to strange results on multicore computers because it easily can exceed 100%.
If you have 8 cores, then top can display CPU usage from 0% (idle system) to 800% (full power).
Your program is just using your 4 cores with hyper-threading (so 8 virtual cores) at maximum capacity. So top gives you nearly 8 x 100% = 800%.
To change this way of calculating CPU usage (it's called Irix mode), press uppercase 'i': Shift+i
You can't explicitly tell the JVM to use a single thread, it will use multiple threads to do its work, even if you only use a single thread in your application.
You can use the htop utility as a better top alternative. You'll see your program using all of the 8 cores.


text:
Q: Confused about Frustum Culling I'm new to OpenGL. I'm using it with JOGL.
I'm reading about frustum culling:
http://www.lighthouse3d.com/opengl/viewfrustum/
http://www.crownandcutlass.com/features/technicaldetails/frustum.html
I'm not sure exactly what it's supposed to do. Doesn't OpenGL cull off-screen objects automatically? (Is this culling significantly slower than just not sending the objects in the first place?)
From what I'm reading, it doesn't look like this will handle avoiding drawing objects that are obscured behind another but are within the viewing frustum. Does that mean that the only benefit is avoid sending off-screen objects to OpenGL?

A: Yes, you are basically right. Frustum culling cuts off objects that are outside the camera pyramid. OpenGL, when rendering a scene, of course does this as well but on a per vertex basis. Frustum culling works per object and its performance boost potential is therefore much higher.
One of the bottlenecks is transferring the data between CPU and GPU. If you need to transfer for example only 1/4 of all the objects/vertices in an outdoor scene, frustum culling can yield a nice performance boost.

A: The fastest object is the one you don't have to draw at all.
In general, for objects that are not dead simple already, you will provide a simplified, conservative bounding volume.  That way,  you can do frustum culling without dealing with every triangle in a complex object..
Avoiding drawing objects that are obscured behind each other is called occlusion culling.  Occlusion culling is generally more complex than frustum culling;  however, note that it can still use the same simplified bounding volume.

A: Yes -- frustum culling just removes objects that lie entirely outside the viewing frustum. Nothing more or less. Yes, you can potentially improve performance over OpenGL itself, especially if you can cull a larger number of items at once (e.g., a viewgraph library may be able to chop off entire branches of the graph fairly quickly).
There is also face culling that removes triangles (or whatever) that are facing away from the viewer, but that's separate from frustum culling.
There are a couple of ways of handling objects that are obscured by other objects. Occlusion culling is the simplest, but OpenGL does nothing to support it directly (though some hardware does as an extension). The other is the depth buffer -- which OpenGL does support directly. The difference is that occlusion culling looks at an entire object, and doesn't render it at all if it's completely obscured. The depth buffer works on a fragment-by-fragment basis, so it only takes place after you've (almost) fully rendered an object. Depending on how many objects you're dealing with (and such) doing your own occlusion culling can, therefore, be a pretty big win (since it can avoid doing a lot of rendering that's needed before the depth buffer can do its thing).

A: When you do you frustum checks in code, you do it using simple geometry that encases the object being draw.  This can be done much faster than the card trying to cull each triangle.


text:
Q: Is Functional Programming Similar to Self-Modifying Code? It seems that sometimes code in functional programs accepts other code (functions) as arguments and modifies it and returns it for execution. It seems similar to self-modifying code. Does this mean that the compactness of functional programs result from the same reason that allows extremely compact self-modifying programs?

A: Ernest Friedman-Hill may be correct that this question doesn't belong here, but here is an answer:
I would say: No.
There are various ways that a language can allow self-modifying code.  The most flexible way would be to be able flip arbitrary bits at arbitrary locations in memory.  (Here is a classic story: The Story of Mel.)  But self-modifying methods need not exhibit such dangerous freedom.  In Common Lisp, it's easy to write code that constructs Lisp code and the evaluates it, but this all stays within the constraints of Lisp, and it's not necessarily more compact.  In Java, you can do certain kinds of "self-modification" using reflection, but this is often more verbose than regular Java usage.
Also, keep in mind that there's actually a fine line between some kinds of object-oriented methods and functional programming methods.  Both allow you to pack up executable things and data together.  OO does it by attaching methods to objects, while functional languages do it by using closures to capture data.  Thus, if functional languages are self-modifying, Java is too.  But Java is not normally thought of as a self-modifying language (except for reflection), and Java code is often verbose.  (By the way, Guy Steele, one of the designers of Java, was also one of the people who designed the Lisp dialect Scheme--a more purely functional language than Common Lisp--in order to experiment with object-oriented programming!  I believe that the idea was to construct different object-oriented language constructs using closures.)
Caveat: I haven't done any hard-core Java programming in a while, and there are probably language features relevant to this issue of which I'm unaware.


text:
Q: How to make javascript function to fire consistently I have a HTML page with a simple form that calculates the product of two input fields and displays the result in a div . It calls a on click javascript funciton.
However , after I have submitted the first time , the form doesn't work from second time onwards , the page keeps refreshing.

<!DOCTYPE html>

DATAX Shipping Company

                        Sign up
                        Log in

    <form id="controls">

Calculation of Shipping charge

 Total Product Weight <input id="weight"/>

Shipping cost (Per Kg) <input id="cost"/>

         <button id="compute" onclick="return result()"/>Compute</button>

</form>

I'm testing with below scenarios
weight = 4 , distance =5
Weight = 10 , distance = 15
From second iteration onwards it seems to fail

A: You're overwriting the variable result inside the function, you need to change it to something else:

 var weight;
        var cost;
        var result;
        function result(){

            weight=document.getElementById("weight").value;
            cost=document.getElementById("cost").value;
            console.log(weight);
            console.log(cost);
            xresult=weight*cost;
            console.log(xresult);
            document.getElementById("result").innerHTML="The Total Shipment charge is "+xresult;
            return false;
        }
#header {
        border: 1px solid lightgrey;
        margin : -8px -8px 0;
        background-color: lightgrey;
     }

                 #controls{

                   margin-left: 475px;

                 }

                 #weight{

                    margin-bottom:25px;
                 }

                 #cost{
                     margin-bottom:25px;
                 }

                 #compute{

                     margin-bottom:25px;
                     margin-left: 300x
                 }

             #result{

                   margin-left: 50px
             }

DATAX Shipping Company

                        Sign up
                        Log in

    <form id="controls">

Calculation of Shipping charge

 Total Product Weight <input id="weight"/>

Shipping cost (Per Kg) <input id="cost"/>

         <button id="compute" onclick="return result()"/>Compute</button>

</form>

A: That because you using the same name (result) as a variable and again as a function name as the same scope. you need to change on of them. you can change the function name to (getResult).

A: I would do it this way:

document.getElementById("compute").addEventListener('click', result);
function result(e) {
    // Since its a form, you need to use preventDefault()
    e.preventDefault();
    // Define input variables
    var weight = document.getElementById("weight").value;
    var cost   = document.getElementById("cost").value;
    // Result variable
    var result = document.getElementById("result");
    // Check if the value is a number
    if( isNaN(weight) || isNaN(cost) ) {
        result.innerHTML = "Please enter a Valid Number!";
    }
    // Final result
    else {
        result.innerHTML = "The Total Shipment charge is " + (weight * cost);
    }
}

document.getElementById("resetForm").addEventListener('click', resultReset);
function resultReset(e) {
    // prevent submit
    e.preventDefault();
    // Reset form
    document.getElementById("controls").reset();
}
#header {
 border: 1px solid lightgrey;
 margin : -8px -8px 0;
 background-color: lightgrey;
}

#controls{
 margin-left: 475px;
}

#weight{
 margin-bottom:25px;
}

#cost{
 margin-bottom:25px;
}

#compute{
 margin-bottom:25px;
 margin-left: 300x
}

#result{
 margin-left: 50px
}

DATAX Shipping Company

          Sign up
          Log in

<form id="controls">

Calculation of Shipping charge

 Total Product Weight <input id="weight"/>

Shipping cost (Per Kg) <input id="cost"/>

    <button id="compute">Compute</button>
    <button id="resetForm">Reset</button>

</form>


text:
Q: How to draw an arc between edges connecting child nodes? I have the following code to generate a couple of trees. How do I draw arcs between the edges (marked in red in the figure)?
\usetikzlibrary{intersections}
\begin{tikzpicture}

\node {Goto(P$_A$)} [grow'=up]
child {node { Say(A,P$_A$)}}
child {node {IsTrue(A)}
};
\begin{scope}[xshift=4.5cm]
\node {Goto(P$_B$)} [grow'=up]
child { node [left=0cm]{ Goto(P$_B$)}
    child {node (sayb) { Say(B,P$_B$)}}
    child {node (istrueb) {IsTrue(B)}}
}
child {node [right=0cm]{ Goto(P$_B$)}
    child {node { Say(C,P$_B$)}}
    child {node {IsTrue(C)}}
};
\end{scope}
\end{tikzpicture}

A: This is one possible solution. Since there were no sibling distance information, this solution assumes its own. Basically, internal names are given for each node and calc is used to determine the starting and ending points via ($(name1)!0.5!(name2)$), then draw the arc by, for example,
\draw ($(o)!0.5!(A)$) to[bend left=30]  ($(o)!0.5!(B)$);

Code
\documentclass[border=10pt]{standalone}
\usepackage{tikz}
\usetikzlibrary{trees,calc}
\usetikzlibrary{intersections}
\begin{document}

\begin{tikzpicture}[level distance=2cm,
                    level 1/.style={sibling distance=3cm},
                    level 2/.style={sibling distance=2cm},
]
\node (o) {Goto(P$_A$)} [grow'=up]
child {node (A) {Say(A,P$_A$)}}
child {node (B){IsTrue(A)}
};
\draw[red,very thick] ($(o)!0.5!(A)$) to[bend left=30]  ($(o)!0.5!(B)$);

\begin{scope}[xshift=6.5cm]
\node {Goto(P$_B$)} [grow'=up]
child { node (B) [left=0cm]{ Goto(P$_B$)}
    child {node (sayb) { Say(B,P$_B$)}}
    child {node (istrueb) {IsTrue(B)}}
}
child {node (C)[right=0cm]{ Goto(P$_B$)}
    child {node (sayc)  {Say(C,P$_B$)}}
    child {node (istruec){IsTrue(C)}}
};
\draw[red,very thick] ($(B)!0.5!(sayb)$) to[bend left=30]  ($(B)!0.5!(istrueb)$);
\draw[red,very thick] ($(C)!0.5!(sayc)$) to[bend left=30]  ($(C)!0.5!(istruec)$);
\end{scope}
\end{tikzpicture}

\end{document}

A: May be there are easier solutions but next one works. It draws a circle with center on parent anchor which is clipped inside a triangle with vertices in parent anchor and child centers.
\documentclass[tikz,border=3mm]{standalone}
\usetikzlibrary{intersections}

\newcommand\myarc[4]{\begin{scope}[very thick,red]
    \clip (#1)--(#2)--(#3)--cycle;
    \draw (#1) circle (#4);\end{scope}}

\begin{document}
\begin{tikzpicture}

\node (rootA) {Goto(P$_A$)} [grow'=up,parent anchor=north]
child {node { Say(A,P$_A$)}}
child {node {IsTrue(A)}
};

\begin{scope}[xshift=4.5cm]
\node (rootB) {Goto(P$_B$)} [grow'=up, parent anchor=north]
child { node [left=0cm]{ Goto(P$_B$)}
    child {node (sayb) { Say(B,P$_B$)}}
    child {node (istrueb) {IsTrue(B)}}
}
child {node [right=0cm]{ Goto(P$_B$)}
    child {node { Say(C,P$_B$)}}
    child {node {IsTrue(C)}}
};

\end{scope}

\myarc{rootA.north}{rootA-1.center}{rootA-2.center}{5mm}
\myarc{rootB.north}{rootB-1.center}{rootB-2.center}{6mm}
\myarc{rootB-1.north}{sayb.center}{istrueb.center}{5mm}
\myarc{rootB-2.north}{rootB-2-1.center}{rootB-2-2.center}{5mm}

\end{tikzpicture}
\end{document}

Update
If you uses TikZ 3.0 you can use angles library which defines a pic angle

Pic type angle=<A>--<B>--<C>
This pic adds a drawing of an angle to
  the current path. This "drawing of an angle" consist of a "sector" or
  "wedge" or "slice" whose pointed end is at point  and whose
  straight sides lie on the lines form  to  and from  to .
  [...]
  The three points <A>, <B>, and <C> must be the names of nodes or coordinates; you
  cannot use direct coordinates like "(1,1)" here.

Last sentence creates a little problem because is not possible to use rootA.north as one of three point, it's necessary to convert it into a coordinate. It accepts rootA which means rootA.center.
Code with angles is:
\documentclass[tikz,border=3mm]{standalone}
\usetikzlibrary{angles}

\begin{document}
\begin{tikzpicture}

\node (rootA) {Goto(P$_A$)} [grow'=up]
child {node { Say(A,P$_A$)}}
child {node {IsTrue(A)}
};

\draw pic[draw, red, thick, angle radius=8mm] {angle=rootA-2--rootA--rootA-1};

\begin{scope}[xshift=4.5cm]
\node (rootB) {Goto(P$_B$)} [grow'=up, parent anchor=north]
child { node [left=0cm]{ Goto(P$_B$)}
    child {node (sayb) { Say(B,P$_B$)}}
    child {node (istrueb) {IsTrue(B)}}
}
child {node [right=0cm]{ Goto(P$_B$)}
    child {node { Say(C,P$_B$)}}
    child {node {IsTrue(C)}}
};

\end{scope}

\draw (rootB.north) coordinate (A)
      pic[draw, red, thick, angle radius=3mm]
      {angle=rootB-2--A--rootB-1};

\draw (rootB-1.north) coordinate (A)
      pic[draw, red, thick, angle radius=3mm]
      {angle=istrueb--A--sayb};

\draw (rootB-2.north) coordinate (A)
      pic[draw, blue, very thick, angle radius=3mm]
      {angle=rootB-2-2--A--rootB-2-1};

\end{tikzpicture}
\end{document}


text:
Q: Simulating the Behavior of a Screening Test for a Disease A test for a certain rare disease is assumed to be correct 95% of the time: if a person has disease, the test results are positive with probability 0.95, and if the person does not have the disease, the test results are negative with probability 0.95. A random person drawn from a certain population has probability 0.001 of having the disease.
Given that the person just tested positive, what is the probability of having the disease?
Just pseudocode would be great

A: Try something like this:

*

*Starting with $1000000$ people, how many do you expect to have the disease and how many not?

*Of those with the disease, how many do you expect to test positive (true positive) and how many negative (false negative)?

*Of those not with the disease, how many do you expect to test positive (false positive) and how many negative (true negative)?

*Of those testing positive, what proportion do you expect to be true positives?

You can easily simulate the first three steps and then calculate the fourth, though like any simulation you should not expect the calculation to be particularly accurate, especially of a very rare disease.

A: If you want a simulation, try following procedure:

*

*Initialize TP - true positive people counter and FP - false positive people counter with zeros;

*Repeat the following N times (a total number of people simulated):
2.1. Roll random variable assuming $1$ with probability $0.001$ (observed sick person) and $0$ with probability $0.999$ (observed healthy person);
2.2. If in previous step you got $1$, with probability $0.95$ increase TP by one (sick person tested positive); otherwise with probability $0.05$ increase FP by one (healthy person tested positive);

*Probability to be sick if tested positive is ${TP}/(TP + FP)$.
Given that you have rather low probability of being sick in the first place, you would need big enough N to converge to mean values (probability of being sick given tested positive is $0.018664\ldots$).

A: Please read my Comment first:
Code in R. Using ten million iterations gives about three-place accuracy. Both of the vectors dis and pos are of length m. Brackets [ ] can be read 'such that'. Assignment is =; logical equality is ==; mean of a logical vector
is the proportion of its TRUEs. Structure avoids explicit loops and 'if...then' branching. Retain set.seed statement for exactly the same simulation, omit
for unpredictable seed and fresh simulation.
answ = (.001*.95)/(.001*.95 + .999*.05);  answ
[1] 0.01866405                                   # exact P(Dis|Pos)
set.seed(627)
m = 10^7;  pos = numeric(m)
dis = rbinom(m, 1, .001);  nr.dis = sum(dis==1)  # 1=disease, 0=none
  pos[dis==1] = rbinom(nr.dis, 1, .95)             # 1=pos test ...
  pos[dis==0] = rbinom(m-nr.dis, 1, .05)           #  ... 0 = neg test
mean(dis[pos==1]==1)                             # aprx P(Dis|Pos)
[1]  0.01879157

In the language of Bayesian inference and screening tests, the 'prevalence' 0.001 of the disease is a 'prior probability', and the 'predictive value of a positive test' $P(\text{Disease | Positive})$ is a 'posterior probability'. Here, although PVP  $\approx 2\%$ is small, it is relatively much larger than prevalence $0.1\%$.


text:
Q: Hide textbox when clicking off box (jQuery) I've got three icons. When I click one, I'm appending an overlay (like a light box), then popping up a textbox explaining the icon, then hiding the textbox when the overlay is clicked.
I've gotten everything down except when I click on the box again, the textbox doesn't appear again. Do I need to do some kind of refresh or something?
HTML:

     Technology Audits

HEADLINE 1

 Popup text 1

    Cloud Solutions

HEADLINE 2

 Popup text 2

    Email Solutions

HEADLINE 3

Popup text 3

and my JQuery:
/* ----------- SERVICES TOGGLE ON SERVICES PAGE--------------- */
// 1. Create overlay and append it to body
var overlay = $('

');
$('body').append(overlay);

$('.iconAnchor').click(function(){
  var serviceParagraph = $(this).closest('.serviceOption').next('.popupBox');
  overlay.show();
  overlay.append(serviceParagraph);
  serviceParagraph.slideDown();
}); // end ICON click

$(overlay).click(function(event){
  $('.popupBox').slideUp(200);
  overlay.hide();
}); // end OVERLAY click

A: If you are going to use jQuery, slideToggle() is perfect for this use case...
$(document).ready(function(){
  $('.popupBox').hide();
  $('.iconAnchor').click(function(){
    $(this).closest('.serviceOption').next('.popupBox').slideToggle();
  });
  $('.popupBox').click(function(){
    $(this).slideToggle();
  })
});

EDIT
So I think there are probably better ways to what you want but for the sake of preserving your overlay div, this will work:
$(document).ready(function(){
  var overlay = $('

');
  $('body').append(overlay);
  $('.popupBox').hide();
  $('.iconAnchor').click(function(){
    overlay.empty().html($(this).closest('.serviceOption').next('.popupBox').html());
    overlay.slideDown();
  });
  overlay.click(function(){
    $(this).slideUp();
  })
});

Also, the reason why your original code isn't working as you expect is because when you append the popupBox element to your overlay div it is actually being moved inside of the div and no longer exists where you expect it to be the next time that click handler for the iconAnchor is called. This means that your serviceParagraph.slideDown() is being called on an empty element.


text:
Q: Silverlight 4 Problem with Out of Browser sllauncher.exe - no paramaters in shortcut My OOB app was working fine. I stupidly renamed all my namespaces and my project names/filenames. (Eventually) I got it all working again but my OOB shortcut stopped working. I removed and reinstalled it but it will not load and throws an error (see below).
It creates the shortcut on my desktop, but if you look at the Target of the shortcut (right-click, properties) it is "C:\Program Files\Microsoft Silverlight\sllauncher.exe". I installed some other apps and they have the ApplicationID and the source website in the shortcut (e.g. "C:\Program Files\Microsoft Silverlight\sllauncher.exe" 3143398843.www.microsoft.com).
Hence, when I click on it, it gives me an error like "Usage: sllauncher.exe xyz".
After some googling, it seems as though the .xap and directory under local settings is being created correctly and the .xap and meta data look fine:
C:\Documents and Settings\Rod\Local Settings\Application Data\Microsoft\Silverlight\OutOfBrowser\1457003494.localhost
When it is creating the shortcut it is just not putting the ApplicationID into it - I have turned off and turned on OOB support, restarted my PC etc. but I cannot get it to work.
After one such attempt, it inserted a whole lot of gibberish:
"C:\Program Files\Microsoft Silverlight\sllauncher.exe" ⇴콅䢯㎣鱎㉝眾˚㯘䉘ᇟ薧∀녟፻粨⇴콅䢯㎣鱎㉝眾˚㯘䉘ᇟ薧∀녟፻
Which also failed...
Any ideas please?

A: Ok, it looks like I have possibly found a bug in the VS2010 editor: Basically my Application Description under the OOB settings was too long. If I make it shorter than the application link works again (it sounds weird but I tested it extensively and it is definitely that).
To confirm - open your OOB settings and paste a whole lot of text into Application Description. Then try and install it locally (I am keen to know if it is just me/my pc).


text:
Q: Error when i use layout tag in databinding in xml android project FAILURE: Build failed with an exception.

What went wrong:
Execution failed for task ':app:kaptDebugKotlin'.
> A failure occurred while executing org.jetbrains.kotlin.gradle.internal.KaptExecution
   > java.lang.reflect.InvocationTargetException (no error message)
Caused by: org.gradle.workers.internal.DefaultWorkerExecutor$WorkExecutionException: A failure occurred while executing org.jetbrains.kotlin.gradle.internal.KaptExecution
Caused by: java.lang.reflect.InvocationTargetException
Caused by: org.jetbrains.kotlin.kapt3.base.util.KaptBaseError: Exception while annotation processing
Caused by: java.lang.IllegalArgumentException: couldn't make a guess for databinding.ActivityStartPageBindingImpl

A: Had a similar issue after upgrading the Kotlin version to 1.4 in my project. Downgrading to ext.kotlin_version to '1.3.50' fixed the issue. Apparently the kapt plugin in gradle 4.1.1 doesn't fully support databinding yet in this kotlin version.

A: Had same error and error because of package name is capital latter, So after make is small its working

A: I had the same problem in Android Studio version 4.1.1. I fixed this problem by updating the Android Studio to version 2020.3.1. Just try to update Android Studio.


text:
Q: How to save wechat qr code for print purpose? I am registered my wechat account through phone number. I have the qr code and I tried to share it to facebook, then download it to my pc, but the image is small, not suitable for print purpose.
Anyone has any idea how can I generate a big QR code for print purpose?

A: *

*Log in https://mp.weixin.qq.com/

*click on 公众号设置 on the side menu

*click on the QR code in the 二维码 section

The downloading should proceed.
Edit: this is in case you have a wechat official account.
If it is a personal account :

*

*click "me" on the app menu

*click on your profile picture on the top

*click on "My QR Code"

*there is an option button on the top bar of the app. Click it and click on "save to phone"

The quality should be good enough


text:
Q: Bing maps How to set a pin on a map (url)? I have all the code, the only thing that missing for me is how to put a pushpin in that url:
http://www.bing.com/maps/default.aspx?v=2&cp=50.22599~50.81103&lvl=10
My pushpin link is:
http://s8.postimg.org/8uuikcaw1/pin.png
I want to make something like this:
http://www.bing.com/maps/default.aspx?v=2&cp=50.22599~50.81103&lvl=10&pushpin=http://s8.postimg.org/8uuikcaw1/pin.png
Or if bing maps has their pushpin, it's also good.
Just want to get a static image with a map and a pushpin on it, can someone help me?
Thanks :)

A: Here is an example of a map with a pushpin:
Pushpin in a map (with tooltip).

A: Replace the latitude and longitude with yours.
var pushpin= new Microsoft.Maps.Pushpin(new Microsoft.Maps.Location(47.6, -122.33));
map.entities.push(pushpin);


text:
Q: Change location of hibernation to HDD I have an SSD and an HDD in my laptop. I changed the size for the SSD to 0 MB (I disabled it completely) and put a 16 GB page size on my HDD. So the question is, is it safe to do hibernation now? So only my HDD will be used, is that right? I don't want to hurt my SSD at all. I've done hibernation a million times on an HDD and I know it's fine with it. But SSDs get wrecked pretty easily.
Sounds like I'm wrong about the relation of page and hibernation. So how do I change the hibernation mode? I've read it's not possible. But maybe there's a workaround?

A: The Windows paging file (pagefile.sys):

*

*Is used to store data that can't be held by your computer's RAM, which generally occurs when a program requests more memory than is currently available.

*Is likely to be used much more frequently than the Windows hibernation file.

*Can be moved to a different drive (as you've discovered).
The Windows hibernation file (hiberfil.sys):

*

*Is used to store the contents of RAM when hibernating (hiberfil.sys is effectively a dump of all your current working memory).

*Likely cannot be moved to a different drive (i.e. to the best of my knowledge, it typically needs to remain on the primary Windows drive).

Is it safe to do hibernation now?

With modern SSDs, it is unlikely that hibernation will adversely affect the drive (even if the PC goes into hibernation several times a day). As far as I am aware, with the total amount of data that can often be written to these drives, other kinds of mechanical failure are often more likely before a drive might even begin to develop errors.

How do I change the hibernation mode?

I am not sure what you mean by "hibernation mode". That said, you can turn hibernation on or off with:
Window 7

*

*Control Panel\System and Security\Power Options

*Select a power plan and choose Edit Plan Settings.

*Click Change advanced power settings.

*Look for the "Hybrid Sleep" option and toggle as desired.
Window 10

*

*Control Panel\Hardware and Sound\Power Options

*Click Change what the power buttons do

*Click Change Settings that are currently unavailable (as necessary).

*Check or uncheck Hibernate (Show in Power menu) as desired.
Note that you may also want/need to run powercfg -h off (Windows 7) or powercfg.exe /h off (Windows 10) from an administrative command prompt (Run → "cmd" → Ctrl + Shift + Enter).

Maybe there's a workaround?

I found this sketchy site claiming that you may be able to disable hibernation and edit the registry to change where hiberfil.sys is located but even those instructions state it may not work in all cases.


text:
Q: How can I fix "The markup in the document following the root element must be well-formed." error in eclipse Here is my schema. Eclipse shows "The markup in the document following the root element must be well-formed."
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>test</groupId>
    <artifactId>testing-projects</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>ProjectForTests</name>

</project>

Here is the error message:

A: The error indicates that there is content AFTER the end of the root element, which means after the root element end marker.  Your screenshot is obscuring that line, so we can't tell if you have anything unusual there.


text:
Q: Tomcat Webapp: Have a Settings Page Where Admin Can Set Default Font Size I have a tomcat web app that I am developing that makes heavy use of javascript/jquery.  There are times when the admin user of the application (we have users integrated with LDAP) would like to adjust some of the common display settings.  For example, today he came to me and asked if I could reduce the font size of one of the heading's.  This required me to modify the css for that heading class.
My question is, would there be a way to integrate a "Settings" page to my webapp, where the admin can modify things like font styles, sizes, and faces and have it update the CSS on the server?  Something tells me that is a big security no-no, but I figured I would ask as I couldn't find anything from a web search.


text:
Q: Upgrade magento version from 1.9.2.4 to 2.0 I want to upgrade magento version from 1.9.2.4 to 2.0.
How to achieve this ?
Anyone can explain the steps to achieve this.

A: You can't really upgrade from 1.9 to 2.0.
What you can do is migrate the installation from 1.9 to 2.0
You can find every detail you need in the official documentation here: http://devdocs.magento.com/guides/v2.0/migration/bk-migration-guide.html
Here's a workflow diagram that will give you a good idea of what to do:


text:
Q: Oracle systimestamp result differs in db server and client I am getting some strange output while executing the below command on db server and on client machine connected to same db server.
On DB server
SQL> select systimestamp from dual;

systimestamp

25-JUN-15 06.16.13.424135 PM +08:00

On Client Machine
SQL> select systimestamp from dual;

SYSTIMESTAMP

25-JUN-15 02.16.57.936662 AM -08:00

Below output for Reference
SQL>  select dbtimezone, sessiontimezone from dual;

DBTIMEZONE                     SESSIONTIMEZONE

+00:00                            +08:00

A: It is normal, because your NLS settings differ on the server and on the client.
The NLS conversion always happens on the client side no matter what your server settings are.  Compare the output of these:
select * from nls_database_parameters;
select * from nls_session_parameters;

A: Timezone of SYSTIMESTAMP is taken from operating system. However, on operating system this can be user-specific.
Do you get different results when you do this on DB Server?
$ su oracle

$ setenv TZ America/Winnipeg
$ sqlplus / as sysdba

SQL> select systimestamp from dual;
...
SQL> exit

$ setenv TZ Europe/Zurich
$ sqlplus / as sysdba

SQL> select systimestamp from dual;
...
SQL> exit


text: Q: Jetbrains Rider slow debug startup compared to Visual Studio 2017 Im currently working on a monolothic ASP NET MVC 5, .Net 4.6.1 web app and i have problem with the debug startup time in JetBrains Rider. When using Visual studio 2017  it takes around 60 seconds for the entire web app to start but with Rider it takes atleast 3 minutes. I havent changed the default debug settings.


text:
Q: How to construct a differential equation of this problem? A tank containing water is in the form of a cone with vertex C. The axis is vertical and the semi-vertical angle is 60°.
At time t= 0, the tank is full and the depth of water is H. At this instant, a tap at C is opened and water begins to flow out.
The volume of water in the tank decreases at a rate proportional to $\sqrt h$, where h is the depth of water at time t.
The tank becomes empty when t=$60$. Find h at time t in terms of H and t.

A: Hint.
$$
\frac{dV}{dt} = k\sqrt{h}
$$
$$
r = h\tan\theta
$$
$$
dV = \pi r^2 dh = \pi(h\tan\theta)^2dh \therefore \frac{dV}{dt}= \pi(h\tan\theta)^2\frac{dh}{dt} = k\sqrt{h}
$$


text:
Q: Best practices for testing settings file with many parameters in simulation code I'm conflicted as to what is the best way to approach this problem.
I am writing a simulation in Python, which is parametrized by ~ 50 parameters. I have a JSON file where these parameters are set, so that it is simple to modify them and perform different simulations iteratively.
Snippet of settings.json (not actual parameter names):
{
  "global_settings": {
    "param1": 10,
    "param2": true,
    "param3": 0.5
  },
  "simulation_settings": {
    "param4": true,
    "param5": false,
    "param6": true
  },
  "output_settings": {
    "file_settings": {
      "param7": "string"
      "param8": false
      "param9": null
    },
  "param10": true
  }
}

I've written a SettingsManager class whose job is to:

*

*parse the JSON into a Python dictionary;

*expose some parameters as attributes (so that objects using the SettingsManager instance won't need to access a 3-level deep dictionary entry);

*validate these settings, making sure that every mandatory parameter is present (by raising exceptions if they aren't).

Snippet of managers.py (where SettingsManager is located):
import sys

class SettingsManager:
    def __init__(self, settings_path: str) -> None
        self._data = self.parse_settings(settings_path)
        if self._data is None:
            sys.exit()
        self.validate_settings()  # calls all other validation methods

Snippet of main.py (responsible for creating a SettingsManager instance and running the simulation with the parsed settings):
from src.managers import SettingsManager
from src.simulation import Simulation

def main(path: str) -> None:
    settings = SettingsManager(settings_path=path)
    simulation = Simulation(settings=settings)
    simulation.run()

if __name__ == '__main__':
    main(path='settings.json')

The SettingManagers's validate_settings method calls downstream methods that go through each subditcionary of the parsed settings and make sure that the relevant keys exist (one method for one dictionary).
As you can imagine, writing code to validate all parameters was tedious. Still, I can't think of a better way other than checking each individual key in each individual dictionay/subdictionary, since each key has a different name, each subdict has a different structure and many different data types are used for values.
Now the real issue is testing: How do I test for the validation of the settings file?
Should I create test cases for every single key that could be missing? That sounds like a lot of work! Not to mention a lot of refactoring, since requirements are not fixed and parameters may be added/modified/removed down the road. I thought about making a mock dictionary in place of the resulting dictionary from the parsed JSON file, but I'm not sure that's beneficial. Am I not simply testing my mocked dictionary, then?
I'm struggling to find some resources about best practices when writing simulation code with many parameters. At the same time, I can't shake off the feeling that I'm missing something obvious here.
How do people deal with this many settings? Are simulations always painful to code? Should I just accept my fate and write tests for every single parameter? Should I completely drop the validate_settings method and just assume users (me + my colleagues) have a properly formatted settings file?
Thank you in advance for your thoughts, I'm very lost here.
Cheers

A: You don't have to test every value, as you're not testing the actual config.  You're just testing the one "unit" which is the validate_settings method.  Running this test won't tell you if your settings file is good, but it does tell you that you won't be able to start the program if your settings file is not good.
You haven't shared the code for validate_settings() but presumably it takes a dictionary of config values, and a list of mandatory values and makes sure that each mandatory value is in the config values keys.
In that case, I think you mock both the dictionary of config values, and the list of mandatory values.  Check the positive case (that it allows a dictionary with the mandatory values) and the negative (that it disallows a missing value).
For what it's worth, you could've gotten away with using Python standard library ConfigParser.

A: Consider to implement a more declarative approach for validate_settings. You wrote

Still, I can't think of a better way other than checking each individual key in each individual dictionay/subdictionary, since each key has a different name, each subdict has a different structure and many different data types are used for values.

I can think of one. I guess a generic description for the settings cannot be much more complex than your actual JSON file? Why not have a complementary description file in JSON for those values, for example, like this:
{
  "global_settings": {
    "param1": "integer",
    "param2": "bool",
    "param3": "double|optional"
  },
  "simulation_settings": {
    "param4": "bool",
    "param5": "bool",
    "param6": "bool|optional"
  },
  "output_settings": {
    "file_settings": {
      "param7": "string"
      "param8": "bool"
      "param9": "bool|optional"
    },
  "param10": "bool"
  }
}

Now, validate_settings can use this description and do the validation for data types and non-optional values in a generic fashion. And that makes the actual testing of validate_settings a whole lot simpler, since for getting full test coverage, you can now use a few simple tests which cover each data type once and the optional/non-optional feature.
Of course, you will also have to proofread the description file to make sure it contains no errors, but that is way less effort than writing a test for each original attribute (and proofread also there is no error in those tests).
As an alternative, you could also have a look at JSON schema, which seems to be way more powerful, but I am not an expert on this.


text:
Q: Does TDengine support automatic table/stable creation? Does TDengine support auto table creation mechanism? For example, I don't want to create table beforehand but data records could be inserted just using the INSERT SQL clause? If so, what are the restriction for this mechanism?

A: yes,TDengine support schemaless mode, that supports create table while insert data.
TDengine support three protocal, once your data structure obey the protocal you can insert the data without create table by yourself.
More info you can refer https://tdengine.com/docs/en/v2.0/insert#schemaless

A: Beside schemaless, another way is automatically create a table when inserting using SQL:
INSERT INTO tb_name USING stb_name TAGS (tag_value1, ...) VALUES (field_value1, ...);

From https://tdengine.com/docs/en/v2.0/taos-sql#insert


text:
Q: Interesting question regarding Weibull distribution, sample mean, and sample median Consider a random sample from a Weibull distribution, $X_i \sim WEI(1,2)$. Find approximate values $a$ and $b$ such that for $n=35$:
(a) $P[a < \bar{X} < b]=0.95$
(b) $P[a < X_{18:35} < b] = 0.95$

Here $\bar{X}=\frac{X_1+\cdots+X_n}n$ (the sample mean) and $X_{18:35}$ is the sample median. Also the pdf of $X_i$ is $2xe^{-x^2}$. We need $P[\bar{X}<b]-P[\bar{X}<a]=0.95$. But is $(a,b)$ unique? If so, why? I think it's not unique.

A: You are right, $a$ and $b$ are not uniquely determined. But if we decide to make $a$ and $b$ as symmetric as possible about the mean, they are determined.
In this case, the mean is $\frac{\sqrt{\pi}}{2}$. The numbers you mentioned in a comment are in fact chosen to be symmetric about this.


text:
Q: Adding a library to classpath for all ANT tasks I need to add a library that becomes by default available to all ANT tasks. Is this possible without changing my ANT script?

A: Yes it's possible, by placing the jar in your $ANT_HOME/lib directory.


text:
Q: Why am I experiencing long non-GC related application pauses? I have been seeing extremely long application pauses in the GC logs that are seemingly not related to garbage collection. The application is on a 16GB heap and allocated memory throughput is quite large. I understand that the GC logs will show pauses that aren't necessarily related to GC and that seems to be the case here.
Also, during these pauses the CPU hits 100%, there is no disk or memory I/O and there is no logging activity (due to all the application threads being stopped).
Any ideas on what may be causing these long pauses, or any suggestions on how I can track the root cause down?
Here is the relevant snippet from the logs (notice the 151 second pause):
2015-04-21T06:30:04.834-0500: 217179.483: [GC (Allocation Failure)2015-04-21T06:30:04.849-0500: 217179.483: [ParNew
Desired survivor size 43614208 bytes, new threshold 6 (max 6)
- age   1:   19876896 bytes,   19876896 total
- age   2:   15903904 bytes,   35780800 total
- age   3:     617120 bytes,   36397920 total
- age   4:      34096 bytes,   36432016 total
- age   5:     399896 bytes,   36831912 total
- age   6:      71112 bytes,   36903024 total
: 706301K->45145K(766784K), 0.0681632 secs] 19029029K->18368371K(25080640K), 0.0684183 secs] [Times: user=0.44 sys=0.00, real=0.08 secs]
2015-04-21T06:30:05.816-0500: 217180.453: Total time for which application threads were stopped: 1.8507910 seconds
2015-04-21T06:30:09.171-0500: 217183.812: [GC (Allocation Failure)2015-04-21T06:30:09.171-0500: 217183.812: [ParNew
Desired survivor size 43614208 bytes, new threshold 6 (max 6)
- age   1:   14812976 bytes,   14812976 total
- age   2:    3411968 bytes,   18224944 total
- age   3:   14952032 bytes,   33176976 total
- age   4:     430048 bytes,   33607024 total
- age   5:      32864 bytes,   33639888 total
- age   6:     374880 bytes,   34014768 total
: 726745K->43352K(766784K), 0.0673428 secs] 19049971K->18366645K(25080640K), 0.0675792 secs] [Times: user=0.48 sys=0.00, real=0.06 secs]
2015-04-21T06:30:09.249-0500: 217183.886: Total time for which application threads were stopped: 0.0763406 seconds
2015-04-21T06:32:43.960-0500: 217338.603: Total time for which application threads were stopped: 151.1866188 seconds
2015-04-21T06:32:43.975-0500: 217338.607: [GC (GCLocker Initiated GC)2015-04-21T06:32:43.975-0500: 217338.607: [ParNew
Desired survivor size 43614208 bytes, new threshold 4 (max 6)
- age   1:   18173880 bytes,   18173880 total
- age   2:    9659800 bytes,   27833680 total
- age   3:    3400176 bytes,   31233856 total
- age   4:   14928944 bytes,   46162800 total
- age   5:     375056 bytes,   46537856 total
- age   6:      31880 bytes,   46569736 total
: 727682K->56678K(766784K), 0.0759093 secs] 19050975K->18380341K(25080640K), 0.0760795 secs] [Times: user=0.58 sys=0.00, real=0.08 secs]
2015-04-21T06:32:44.053-0500: 217338.684: Total time for which application threads were stopped: 0.0769955 seconds

Here are my JVM settings at the moment:
-Xmx16g
-XX:MaxPermSize=256m
-Dcom.sun.management.jmxremote
-Dcom.sun.management.jmxremote.authenticate=true
-Dcom.sun.management.jmxremote.login.config=JmxFileLoginModule
-Dcom.sun.management.jmxremote.port=8082
-Dcom.sun.management.jmxremote.ssl=false
-Dfile.encoding=UTF8
-Djava.awt.headless=true
-Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager
-Xloggc:{fileLoc}
-XX:+DisableExplicitGC
-XX:+PrintAdaptiveSizePolicy
-XX:+PrintGCApplicationStoppedTime
-XX:+PrintGCCause
-XX:+PrintGCDateStamps
-XX:+PrintGCDetails
-XX:+PrintTenuringDistribution
-XX:+UseConcMarkSweepGC
-XX:+UseParNewGC
-XX:GCLogFileSize=50M
-XX:NumberOfGCLogFiles=10
-XX:ReservedCodeCacheSize=256M
-XX:-UseGCLogFileRotation
-XX:+PrintSafepointStatistics
-XX:+SafepointTimeout
-XX:SafepointTimeoutDelay=4000
-XX:+PrintSafepointStatistics

UPDATE:
I forgot to include my safepoint logging here. This is what my safepoint log looks like for the 151 second pause experienced above:
217338.603: [sweeping nmethods, 0.0000036 secs]
             vmop                    [threads: total initially_running wait_to_block]    [time: spin block sync cleanup vmop] page_trap_count
    217187.422: GenCollectForAllocation          [     140         46              1    ]      [     1     0151184     2     0    ]  0

The block time is 0, but it appears right next to the sync time, so the sync time is actually 151184.
For other GC-related pauses the safepoint log appears like this:
107100.562: [sweeping nmethods, 0.0000015 secs]
         vmop                    [threads: total initially_running wait_to_block]    [time: spin block sync cleanup vmop] page_trap_count
107100.563: GenCollectForAllocation          [     117          0              0    ]      [     0     0     0     0 38238    ]  0

So, the GC pause shows as vmop time and the non-GC pauses show as sync time. I'll have to read more about what this means.

A: We've experienced a similar problem that appeared to be a JVM bug JDK-8041984.
I'm not sure this is your case as well, but consider updating to JDK 8u45 or 7u80.
Whenever you see this problem again try to take a forced stack dump with the native frames during this long pause:
jstack -F -m <PID>

This will help to identify what the VM is doing even if the process is not responding.

A:
The block time is 0, but it appears right next to the sync time, so the sync time is actually 151184.

You're reading the output wrong, due to tabs the headers are not properly aligned, you need to count columns.
As I understand it it's basically waiting 151 seconds to reach a safepoint because a mutator-thread remains a live despite a safepoint trap being active.
This can happen either when it spends too much time in native code or as @apangin mentions when compiler threads do excessive amounts of work.
I think there were also some cases where the compiler would optimize away a safepoint in a loop backedge when it could prove that the loop finishes in a finite amount of time, which could take several seconds in loops iterating over long counters.


text:
Q: Generate wadl from existing CXF rest service I have working JAX-RS service implemented with CXF. How can I generate wadl? Or is there something like with jersey  http://path.to.your/restapp/application.wadl out there already? is there a maven plugin just like for wsdl, java to wsdl? I've searched for answers couldn't find.

A: There are a lot of possible ways to generate WADL using CXF:

*

*You can sent REST call (using Postman, for example) to the base
REST URL and it will automatically create WADL for all services
available from there. It can help to structure REST API. For
example:

*

*http://app.com/purchase/?_wadl - create WADL for purchase API

*http://app.com/profile/?_wadl - create WADL for user profile API

*CXF 3.0.0 and 2.7.11 introduce java2wadl plugin for generating WADL at the build time. Details clould be found here.

*All available feature of CXF regarding WADL are located in CXF docs.

After WADL has been generated it would be nice to transform XML to more readable form. One of the solutions that I found was XSL usage to generate HTML. I have used XSL from github project. Steps to link XSL to XML and generate pretty HTML report:

*

*Download wadl.xsl;

*Copy wadl.xsl to the folder that contains wadl.xml file that was generated by CXF;

*Add required header to wadl.xml to the very beginning of the file:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="wadl.xsl"?>

*Replace in wadl.xml generated <application ...> header using
<wadl:application xmlns:wadl="http://wadl.dev.java.net/2009/02"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://wadl.dev.java.net/2009/02 wadl.xsd ">

*Add to every tag 'wadl' namespace. For example:
<resource> -> <wadl:resource>
</resource> -> </wadl:resource>

*Open wadl.xml using IE

*You will get something like this (example_wadl.xml from github project):

A: If you are using a recent version of CXF, just hit the service with a ?_wadl parameter.


text:
Q: FaceBook Graph API: Search beyond immediate circle Is it possible to search for users which are beyond my immediate circle using FB graph API?
If not, does having a paid subscription account help to overcome this hurdle?
I'm using following graph query but seems to be restricted within my circle:
https://graph.facebook.com/search?q=xx+yy&limit=5000&type=user&access_token=*
Also if I increase the offset using pagination in the next call, It will still returns the same set of user IDs. So not sure if I'm passing the parameters incorrectly or missing some other parameters.
Thanks for all your help in advance!

A: Not sure what you mean by your immediate circle in terms of Facebook but I assume you mean your friends. The Graph API allows you to search for all public objects (source) - this means every person (according to answers on this page since names are always publicly available - that's my understanding), not only people who you are friends with on Facebook.
Hence, when you're searching for "John" you should get everyone called John if you're using the Graph API correctly - make sure your access token is valid (you do not need any special permissions to search for people) and your syntax follows the example from here.
In order to test your query I suggest you use the Graph API Explorer before adding the query to your application code. It's a quick way to see if the error is in your query or elsewhere. For example, if you want to find everyone named John, use this link http://developers.facebook.com/tools/explorer?method=GET&path=search%3Fq%3DJohn%26type%3Duser. Just make sure to click Get access token on the right if you're using the Explorer for the first time, otherwise the query will return an error.


text:
Q: Javascript, looping through gridview checking hidden values I need some help :). Im trying to build a Javascript that goes through a gridview on my page and for each row checks the hiddenvalue that is stored in a certain cell of that row. It should then check this against a filtervalue and if it doesnt match hide the row in question.
How can I do this?

A: While not the most elegant, this should get you started in the right direction:
<script type="text/javascript">
    function HideEvenValueRows() {
        var tGrid = document.getElementById('<%= GridView1.ClientID%>');
        for (var i = 0; i < tGrid.rows.length; ++i) {
            var inputs = tGrid.rows[i].getElementsByTagName("input");
            for (var j = 0; j < inputs.length; ++j) {
                if (inputs[j].type == "hidden") {
                    var k = inputs[j].value * 1;
                    if (k % 2 == 0) {
                        tGrid.rows[i].style.visibility = "collapse";
                    }
                }
            }
        }
    }
</script>


text:
Q: Filter dropdown is not showing on Datatable I am trying to filter adatatable column with a dropdown and I followed the steps in the documentation here: https://datatables.net/examples/api/multi_filter_select.html
However, my dropdowns are still not appearing at the footer of the table, so I was wondering what was wrong. The table is well initialized with the search and pagination appearing, just not the dropdown.
This is how I initialize the table:
//initialize datatable
myTbl = $('#myTbl').DataTable({
    initComplete: function () {

        this.api().columns().every( function () {

            var column = this;
            var select = $('<select><option value=""></option></select>')
                .appendTo( $(column.footer()).empty() )
                .on( 'change', function () {
                    var val = $.fn.dataTable.util.escapeRegex(
                        $(this).val()
                    );

                    column
                        .search( val ? '^'+val+'$' : '', true, false )
                        .draw();
                } );

            column.data().unique().sort().each( function ( d, j ) {
                select.append( '<option value="'+d+'">'+d+'</option>' )
            } );
        } );
    },
    columnDefs: [ {
        targets: [0]
    }],
     pageLength: 5,
     language: {
        search: '',
        searchPlaceholder: "Search"
    },
    columns: [{
        data: function(d) { return d['name']}
    }]
});

This is how I declare my table in HTML:

Appreciate any help thanks in advance!
EDIT
I managed to figure out what was the issue, in case anyone is facing the same issue, I changed 'initComplete' to 'drawCallback' and also added an empty row in the tfoot tag and it works now.


text:
Q: Why to use MPI_Wait in MPI_Send? I would like to understand why should I use MPI_Wait to wait for an MPI request to complete?
So, in the end of MPI_Send scope I would use the MPI_Wait method, but why?
In my comprehension MPI_Send just send a message and doesn't wait a request to complete, but
the MPI_ISend do!
Thanks.

A: To summarize what @Hristo Iliev said, you shouldn't (and can't) call MPI_WAIT for a call to MPI_SEND. Calling MPI_WAIT requires that you pass in an MPI_Request object which you get as a return value from an MPI_I<something> function. Without that object, MPI doesn't know what you're trying to wait on.
So your reasoning in the end is correct. You don't wait on an MPI_SEND, but you do (and must) wait on an MPI_ISEND.


text:
Q: Is it possible to create a list in WSS 3.0 based on a custom template using SharePoint web services? I want to create a SharePoint list using SharePoint web services (instance is SharePoint Services v3.0). That list should be built from the custom list template that I have created previously. Browsing through MSDN documentation resulted in the following resolutions:
services.ListsService.AddList(title, description, templateID);

or
services.ListsService.AddListFromFeature(title, description, featureGUID, templateID);

Now, if we take a look at the first implementation, there is a problem as the templateID doesn't exist for my custom template - it refers to the default ones instead.
The second implementation is no good either as I need the templateID again, but I also need the feature GUID which I have no idea how to get. Could anyone help please? Thanks.

A: It has been confirmed to me from people from Microsoft that, unfortunately, it is not possible to utilize features to create a SharePoint list using SharePoint web services. It can be either done by developing custom web service, or by using Object Model.


text:
Q: Dealing with point lights and exact reflections in path tracing Trying to implement Monte Carlo path tracing, I've hit a snag in the light sampling procedure.
Usually, the procedure goes as follows:

*

*Trace a ray starting from the camera (or from a previous point) until a surface point is reached.

*Once a surface point is reached, generate a point at random on a light source in the scene.

*Compute the geometry term, describing whether that light can attain the current point on the surface (this term is either 0 or 1).

*If this geometry term is 1, compute the contribution of that light by multiplying by an attenuation factor (for how far the light is) and by the BRDF of the material.

I've left out a few details about how things are randomly selected, but never mind that for the moment (see e.g. "Luminaire Sampling in Distribution Ray Tracing").
The problem, as I see it, is that both the BRDF and the distribution of light in light sources are not actual functions, but rather measures.
For instance, the BRDF of a perfectly reflecting mirror is, for each incoming angle, a dirac delta "function" in the reflected direction (i.e. a measure supported on one point, with a mass of 1 at that point). Similarly, a point light (as opposed to an area light) is modelled by a dirac delta, as opposed to a density function.
It seems important to get the distinction straight, as it allows proper importance sampling. For instance, when sampling a BRDF, one could either:

*

*Sample all outgoing directions uniformly, and scale by the corresponding reflection distribution "function",

*Sample according directly to the BRDF, and not scale afterwards.

Anything in between is also possible, and important, as perfect importance sampling is not going to be possible for complex BRDFs.
Now, in the case that the BRDF is actually a dirac delta, we see that it becomes extremely important to sample according to the BRDF: sampling randomly, we have to dismiss the contribution with probability 1 (because the BRDF is supported at a single point, which we have probability 0 to choose when sampling directions uniformly), but if we do hit lucky and get the reflected direction (at which the mass is), then we have to scale the contribution to be infinitely large! If we sample according to the BRDF, we always generate the reflected direction, and don't have to scale anything (and particular don't run into any infinities).
My problem is then the following: how do you "multiply" the BRDF by the contribution of  the light, in the case where they are both general measures and not just functions? How does one properly "importance sample" at this step, when considering both the importance sampling of the BRDF and the distribution of lights in the scene? (The sampling procedure for the light should take into account both the light distribution and the BRDF, so to avoid infinities.)
Ideally, one would need sampling procedures that never produce infinities, infinities which should just be artifacts of bad sampling mechanisms (as in the above). So, for the subsequent four scenarios, the calculated contribution should always be finite:

*

*continuous BRDF (e.g. Lambertian diffuse material) with area lights

*continous BRDF with point lights

*discrete BRDF (e.g. perfect mirror) with area lights

*discrete BRDF with point lights

Of course, ideally this would work for any measure for both the BRDF and for the lights, but it seems being able to get the above 4 cases right is where most of the work is.

A: If you've got a Dirac delta from a completely specular path to a point light source, you can still evaluate the total integrated contribution of the delta.  (If your BRDF is not a purely specular Dirac delta, you can and probably should handle it with ordinary ray-tracing...)
Note that this "delta path" will act differently from an ordinary ray path.  Specifically, the color of an ordinary ray represents luminance (units: lumens/steradian/m^2), which is invariant with respect to distance, and -- BRDF sampling aside -- is only multiplied by coefficients of reflection and transmission.
However, the color of a "delta ray" represents illuminance (units: lumens/m^2), which is not invariant with respect to distance (it falls off as 1/r^2).  Also, unlike luminance, a delta path will be affected by the curvature of specular reflectors and refractors along the path.
To take into account the paraxial behavior of curved specular surfaces, you will need to evaluate the derivative of the ray source with respect to the viewing angle at the other end.  This should be representable by a 2x2 Jacobian matrix, which is multiplied at each reflection by a Jacobian representing the local curvature of the surface.  Your distance calculations will also modify this matrix -- e.g., consider that a perfect lens might yield an illuminance that increases with distance, as you approach the focal point.  Which also suggests you will need to handle possible singularities, where caustics focus a point light source...
Because your frame buffer has finite resolution, rendering a delta should normally (outside of caustic singularities) yield a finite (though possibly quite high) brighness.  For the sake of simplicity, assume that each sample contributes to exactly one pixel:  the units above suggest that you must divide the illuminance of the "delta path" by the solid angle of your pixel, to make it comparable with the luminance of your ordinary rays.  (Note that solid angle will vary per pixel -- for a standard camera, you must include a cos(theta) factor)
You should be able to do something similar to terminate a purely-specular path at a non-specular surface.  I would guess that the statistics of a "delta ray" might also be different from those of conventional rays;  you will need to figure out exactly how they fit into your Monte Carlo framework.


text:
Q: Type definition: expected UnionAll, got TypeVar In the Julia manual for v0.6 I find the following:
abstract type Pointy{T} end
struct Point{T} <: Pointy{T}
    x::T
    y::T
end

This works fine, and I thought the following should as well:
abstract type Foo{V, F} end
struct Bar{V, F} <: Foo{V, F}
    x::V{F}
end

The definition of Bar gives, however, the following error
ERROR: TypeError: Type{...} expression: expected UnionAll, got TypeVar

What is wrong, and how can I achieve what I really want, namely to specify that V<:AbstractVector and F<:AbstractFloat?

A: Try this:
julia> abstract type Foo{T} end

julia> struct Bar{T<:AbstractFloat,V<:AbstractVector{T}} <: Foo{T}
           x::V
       end

julia> Bar{T}(v::AbstractVector{T}) = Bar{T,typeof(v)}(v) # constructor
Bar

julia> Bar(rand(3))
Bar{Float64,Array{Float64,1}}([0.387467, 0.535419, 0.240748])

julia> Bar(rand(Int, 3))
ERROR: TypeError: Bar: in T, expected T<:AbstractFloat, got Type{Int64}
Stacktrace:
 [1] Bar(::Array{Int64,1}) at ./REPL[4]:1

A: Another option (got it to work concurrently with @tholy's answer and uses the same route of having V "include" the parameter F). To get it to work nicely, an external constructor should be added, like @tholy's answer (maybe this was a bit redundant, but it uses the where syntax)
struct Bar{V, F} <: Foo{V,F}
    x::V
    Bar{V,F}(x::V) where {F, V<:AbstractVector{F}} = new(x)
end

and this works like so:
julia> Bar{Vector{Int},Int}([1,2,3])
Bar{Array{Int64,1},Int64}([1, 2, 3])

julia> Bar{Vector{Int},Float64}([1,2,3])
ERROR: MethodError: Cannot `convert` an object of type Array{Int64,1} to an object of type Bar{Array{Int64,1},Float64}
This may have arisen from a call to the constructor Bar{Array{Int64,1},Float64}(...),
since type constructors fall back to convert methods.

A: Based on the answers of @tholy and @DanGetz I messed about a bit and came up with an answer I liked:
abstract type Foo{V} end
struct Bar{V <: AbstractVector{<:AbstractFloat}} <: Foo{V}
    x::V
end

julia> Bar(rand(5))
Bar{Array{Float64,1}}([0.722314, 0.159418, 0.13561, 0.288794, 0.347009])

julia> Bar(2.0:5.0)
Bar{StepRangeLen{Float64,Base.TwicePrecision{Float64},Base.TwicePrecision{Float64}}}(2.0:1.0:5.0)

julia> Bar(2:5)
ERROR: MethodError: Cannot `convert` an object of type UnitRange{Int64} to an object of type Bar

I like this because it seems simpler, the default constructor works directly, and I don't get "doubling" of the floating point typevar, that is, Bar{Array{Float64,1}} instead of Bar{Float64,Array{Float64,1}}.
Not sure if there are any drawbacks to this version, though. Also, I still don't understand why some of my efforts work and some fail with syntax or other errors.


text:
Q: Set gradient programmatically not working when set during setClickListener. Why? I programmatically set the gradient (as per the approach shared in https://stackoverflow.com/a/52289927/3286489)
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    setTextGradient()  // Set here, and it is working
    btn_press_me.setOnClickListener {
       // Do nothing
    }
}

private fun setTextGradient() {
    val paint: TextPaint = text_happy.paint
    val width = paint.measureText(text_happy.text.toString())

    val textShader: Shader = LinearGradient(
        0f, 0f, width, text_happy.textSize, intArrayOf(
            Color.parseColor("#F97C3C"),
            Color.parseColor("#FDB54E"),
            Color.parseColor("#64B678"),
            Color.parseColor("#478AEA"),
            Color.parseColor("#8446CC")
        ), null, TileMode.CLAMP
    )
    text_happy.paint.shader = textShader
}

This works. However, if I move setTextGradient() into the setOnCLickListner, why it is not working?
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    btn_press_me.setOnClickListener {
        setTextGradient()  // Move here and it is not working.
    }
}

private fun setTextGradient() {
    val paint: TextPaint = text_happy.paint
    val width = paint.measureText(text_happy.text.toString())

    val textShader: Shader = LinearGradient(
        0f, 0f, width, text_happy.textSize, intArrayOf(
            Color.parseColor("#F97C3C"),
            Color.parseColor("#FDB54E"),
            Color.parseColor("#64B678"),
            Color.parseColor("#478AEA"),
            Color.parseColor("#8446CC")
        ), null, TileMode.CLAMP
    )
    text_happy.paint.shader = textShader
}

A: Apparently, I need to invalidate it after setting it
    private fun setTextGradient() {
        val paint: TextPaint = text_happy.paint
        val width = paint.measureText(text_happy.text.toString())

        val textShader: Shader = LinearGradient(
            0f, 0f, width, text_happy.textSize, intArrayOf(
                Color.parseColor("#F97C3C"),
                Color.parseColor("#FDB54E"),
                Color.parseColor("#64B678"),
                Color.parseColor("#478AEA"),
                Color.parseColor("#8446CC")
            ), null, TileMode.CLAMP
        )
        text_happy.paint.shader = textShader
        text_happy.invalidate()  // Add the invalidation here
    }