text:
Q: Send an email with SendGrid and C# .NET Core 3.x I'm trying to send an email with SendGrid (Nuget package v. 9.15.1) in C# and .NET Core 3.1
I have a project that I use it as Nuget package where I have the logic to send an email. In my ConsoleApp I'm using this package. When I try to send an email, I can debug until when I invoke SendEmailAsync. After that the application stops.
SendGridResponse rtn = new SendGridResponse();

SendGridMessage message = new SendGridMessage();
message.From = new EmailAddress(request.FromAddress, request.FromName);
message.AddTo(new EmailAddress(request.ToAddress, ""));
message.Subject = request.Subject;
message.PlainTextContent = request.PlainTextContent;
message.HtmlContent = request.HtmlContent;

try
{
    Response response = await _client.SendEmailAsync(message);
    if (response.StatusCode == System.Net.HttpStatusCode.OK)
    {
        rtn.StatusCode = (int) response.StatusCode;
        rtn.Message = "Email sent";
    }
    else
    {
        rtn.StatusCode = (int) response.StatusCode;
    }
}
catch(Exception ex)
{
    rtn.StatusCode = (int) HttpStatusCode.BadRequest;
    rtn.Message = ex.Message;
}

In the Output window I only can see that:

'ConsoleApp1.exe' (CoreCLR: clrhost): Loaded 'Anonymously Hosted DynamicMethods Assembly'.
'ConsoleApp1.exe' (CoreCLR: clrhost): Loaded 'C:\Projects\ConsoleApp1\bin\Debug\netcoreapp3.1\SendGrid.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
  The program '[14896] ConsoleApp1.exe' has exited with code 0 (0x0).


text:
Q: Jquery onclick on ids not working for the ids returning from the ajax request I have document.ready function for image hover.
When the image id sign_up_close is there in the document the hover is working. If the same id is coming from the AJAX request then the hover is not working in JQuery.
Please give a solution, I have so many functions like this to be worked on AJAX request. The AJAX request is coming with the image with the id sign_up_close.
$(document).ready(function(){
    $("img#sign_up_close").hover(function(){
        $("img#sign_up_close").attr("src","images/buttons/btn_type1_23_close_pp_icon_.gif");
    },function(){
        $("img#sign_up_close").attr("src","images/buttons/btn_type1_23_close_pp_icon.gif");
    });
});

A: If Paolo Bergantino is correct, another viable alternative is to use Jquery's LiveQuery.
Documentation can be found at http://docs.jquery.com/Plugins/livequery
Your code would probably look something like this:
$(document).ready(function(){
        $("img#sign_up_close").livequery(function() {
            $(this).hover(function() {
                $("img#sign_up_close").attr("src","images/buttons/btn_type1_23_close_pp_icon_.gif");
            }, function() {
                $("img#sign_up_close").attr("src","images/buttons/btn_type1_23_close_pp_icon.gif");
            });
        });
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: Adding data to MySQL DB with PDO not working I am trying to re-learn my web development skills for a current application project I am working on.  I have verified my PHP back-end is getting the data passed to it from the HTML/JS form on the front-end.  But when I submit the form the webpage does not mention any errors.  Everything looks fine until I look at the database and see nothing was added.  I do not see the echo at the end either that data was successfully added, or that it failed to add data.
register.php
<?php
    include "conn.php";

    if(empty($_POST['firstName']) || empty($_POST['lastName']) || empty($_POST['email']) || empty($_POST['password']) || empty($_POST['pin'])) {
        echo "
Error: Please fill out all required fields.";
    } else if($_POST['password'] != $_POST['confirmPassword']) {
        echo "
Error: Passwords do not match.";
    } else if($_POST['pin'] != $_POST['confirmPin']) {
        echo "
Error: Pin codes do not match.";
    } else if(strlen($_POST['password']) > 20 || strlen($_POST['password']) < 8) {
        echo "
Error: Passwords must be between 8 and 20 characters in length.";
    } else if(strlen($_POST['pin']) != 4) {
        echo "
Error: Pin codes must be a maximum of 4 characters.";
    } else if(strlen($_POST['firstName']) > 50 && strlen($_POST['lastName']) > 50 && strlen($_POST['email']) > 50) {
        echo "
Error: First Name, Last Name, and E-mail fields must be shorter than 50 characters in length.";
    } else if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
        echo "
Error: You must use a valid e-mail address.";
    } else {
        echo "

Successfully checked all data!";

        $options = [
            'cost' => 12,
        ];
        $hash = password_hash($_POST['password'], PASSWORD_BCRYPT, $options);
        $numericPin = (int)$_POST['pin'];
        $currentDateTime = date("Y-m-d H:i:s");

        $stmt = $conn->prepare("INSERT INTO account (firstName, lastName, email, password, pin, registerDate) VALUES (:firstName, :lastName, :email, :password, :pin, :registerDate)");
        $stmt->bindParam(":firstName", $_POST['firstName']);
        $stmt->bindParam(":lastName", $_POST['lastName']);
        $stmt->bindParam(":email", $_POST['email']);
        $stmt->bindParam(":password", $hash);
        $stmt->bindParam(":pin", $numericPin);
        $stmt->bindParam(":registerdate", $currentDateTime);

        if($stmt->execute()) {
            echo "

Data added successfully";
        } else {
            echo "

Failed to add data";
        }
    }
?>

MySQL DB Structure:
MySQL DB Structure Picture Link

A: You have a misspelled placeholder
":registerdate"

You have this in the SQL
 $stmt = $conn->prepare("INSERT INTO account (firstName, lastName, email, password, pin, registerDate) VALUES (:firstName, :lastName, :email, :password, :pin, :registerDate)");

Specifically :registerDate vs :registerdate, casing matters here.
A few other things:
change include to require ask youself will the script work without it, well no. Then it needs to be require.  Include won't give you an error when it fails to find the file.
Change your validation to help your end users
 $errors = [];
if(empty($_POST['firstName']) || empty($_POST['lastName']) || empty($_POST['email']) || empty($_POST['password']) || empty($_POST['pin']))
    $errors[] ="
Error: Please fill out all required fields.";

if($_POST['password'] != $_POST['confirmPassword'])
   $errors[] ="
Error: Passwords do not match.";

if($_POST['pin'] != $_POST['confirmPin'])  ....

Then count the array
if(count($errors) > 0 ){
    echo implode("\n", $errors);
}else{
    //--- do insert

}

This way you can show them all the errors at once.  Otherwise they have to submit, correct, submit, correct etc etc...  This will get very frustrating very quickly and the last thing you want to do is frustrate your users, they may just leave.  I have and will leave sites that don't show me the errors right away, I would rather find a site offering what I want that is properly build then deal with one that can't even do proper validation.  It makes me wonder what else cant be trusted on the site. (but that is me and I have experience in this thing).
Naming Conventions (opinion):
I always name DB fields all lowercase with spaces replaced with _.  This reduces a lot of these kinds of issues because, is it registerdate, registerDate or RegisterDate.
There are a few other things related to table names that I do, but I won't bore you with all that.
Cheers!

A: So just to add the answer here, it was simple.  I added a try/catch block around where the statement was being executed (and where the script was dying).  Found that there was some kind of duplicate placeholder usage or mismatch.  Then I double checked my placeholders and found :registerDate was bound as :registerdate.  Fixed and boom, adding to database.  Thanks all for helping!


text:
Q: Windows Server 2016 scheduled task schedule must be in future We have a 2012 server that has about 20 scheduled tasks that are used for monitoring.  We have built a 2016 server to replace it and as I move tasks to the new server I have run into an issue.  Most of our tasks run every few minutes.
In Server 2012 we would schedule the task to start at 1200AM of the current day (so a time in the past) and reoccur every X minutes.  The task would start at its next scheduled time.  Perfect.
In Server 2016 schedules that start in the past don't run.  So we had to schedule it to start in the future.  This is fine until you reboot.  Now the start time is in the past and it won't run.  It doesn't even register a failed run.  The Next Run Time column shows that it should run but doesn't.

Besides creating two triggers, one that starts in the future and another that starts on reboot (which we don't want to do since some tasks should only run at specified times), is there a better way?  This seems to be a bug.  The 2012 version worked great.
UPDATE
There is a workaround for this.  Create a one time schedule that runs indefinitely.  This works after restarts just like you would expect.  I know this isn't great for schedules that are "weird" but works fine for things that we want to run every 3 minutes or whatever.

A: FYI - I have confirmed with Microsoft through a support ticket I opened yesterday that this is a bug.  The support tech confirmed it is internally classified as a bug and a patch is being developed.  I was given a target date of release of the patch for July/August.
This affects both Windows 10 and Server 2016.  My test systems were patched through to yesterday's cumulative update.  The issue did not occur in Server 2012 R2 and Windows 7.
EDIT - As of possibly August, but definitely September 2017, this issue is fixed on systems I have tested it on.

A: This problem only seems to affect tasks with the Repeat task every: ... option set.
So far, I was under the impression that trigger at X, then repeat every 10 minutes is just a needlessly complicated way to write trigger at every xx:x0 in Task Scheduler.
Apparently, it isn't. Apparently, it means exactly what it says: The task is triggered at X and then, and only then it is repeated. No initial trigger, no repetition. I seems that there is no simple way to schedule trigger at every xx:x0 in Task Scheduler (or is there? That might make a good separate Serverfault question.) The fact that the "Next Run Time" column shows something different is not very helpful.
We "solve" this problem by scheduling the task to run at 12:00 every day (instead of only one day) and then repeating every ... minutes for 1 day. This means that if a reboot occurs, at 12:00, the tasks will resume. It's not ideal, but it's an acceptable compromise here.
I guess you could lower the "task downtime" to 1 hour by creating one trigger for every hour and have the task repeat afterwards every ... minutes for 1 hour.
Surprisingly, it seems like it has always been that way (see the first comment to this answer), we just never noticed until now. According to the other comments of the linked answer, the canonical way to solve this issue is to activate the Run task as soon as possible after a scheduled start is missed option.
So, yes, it's a bug, but it's the "Next Run Time" column which is buggy, not the actual scheduling.

A: 1. Windows 2016 Server necessarily require these options in your job:

*

*Run task as soon as possible after a schedule start is missed or

*If the task fails, restart every

I noted these options in the screenshot
2. Add additional trigger. Such as:

*

*When creating or editing task

*When you start

etc. within the meaning of: to move a task to start at the desired time
3. In some tasks in Windows 2016 - implemented this approach.


text:
Q: Exiting a thread blocking on TCP read in C# My server/client start a new thread "readerThread()" for reading incoming tcp traffic. This thread blocks on read(). How can i exit this readerThread().
One way is to start another thread which closes the socket when the thread is to be exited so the read would exit. is there a more cleaner/better way to do it.

A: I misunderstood the question. Here is what I think you should do.

*

*If you created the socket in parent thread, and only use the new thread to read incoming data, then I would suggest calling Socket.Shutdown().This way the Receive methods will return 0 (no bytes read), and you can exit from thread's method. Shutdown will disable send/receive, but if there is any data in buffer that is waiting to be sent/received it will ensure that it is sent/received before closing the socket. Your Receive method will return 0 if you call shutdown while the socket is blocked on Receive, but it will throw a socket exception with Socket error code = Shutdown (or 10058). So be ready to catch and handle it.

*If you create the socket in new thread, and its accepting new connections (Socket.Listen() and Socket.Accept) then you can connect with that socket from your parent thread and Send 0 bytes. You can exit new thread when Receive methods returns 0 bytes.

*If you are creating the socket in new thread, and it can only a client (Connects with other socket) then this is not a good approach at all. You may have to Abort the thread (not recommended), unless you configure your server to send 0 bytes when you want your client socket to close, but this way your client app will be dependent on server for closing the socket.

A: If you're using a blocking read() command, you should almost always have another control thread that is in charge of shutting it down and cleaning up the socket.
Typically though, I would use a select() call that times out after 1 second or so to test if there is data to be read, and each timeout cycle checks if a shutdown status flag has been set by another thread.
But if you go with pure blocking, use a control thread as you suggest.

A: I would use Asnyncronous Socket communication.  I wrote an article which demos this on my blog.  ou can read here:
http://www.andrewrea.co.uk/blog/2009/06/09/Part1SocketProgrammingWithCJAVACAndActionScript30EstablishingABaseConnectionAndCommunicationWithCServerAndAS3.aspx
Andrew

A: I'm somewhat puzzled what exactly you are doing: there is no read() method for the Socket class in .NET.
My recommendation is to create a second socket, which is listening on a specific port, and have the thread block in Socket.Select instead. Connecting to that second socket should be taken as a shutdown request (perhaps after proper authentication, e.g. by sending an application password over that socket).

A: Another way to do it is to send a 0 byte packet to your listening socket from somewhere else in your own application when you want to shut it down.
I've found that's a slightly cleaner approach than closing the coket from another thread since an exception will be thrown by the listening thread if you close the socket on it.


text:
Q: google talk / libjingle developer forum Does anyone know if there is a libjingle developer forum?
The link provided at  https://developers.google.com/talk/libjingle/index under "Support" throws a "You do not have permission to access this group. (#418)" error.
Other places I could find are http://code.google.com/p/libjingle/issues/list, but that is only for bugs. And the activity at Stackoverflow seems low.

A: I was going to ask the same question, and this question has been open for 2 months, which makes me think the answer is no. Also, I'll add that the link to google talk help center on the google talk blog goes to archive.org! I searched for other google groups that cover libjingle and they are filled with spam.
Moreover, the current compilation instructions for Mac OS X require a lot of work (I documented this here: http://blog.bjornroche.com/2012/09/compiling-libjingle-on-os-x.html). So I'm guessing this means google is quietly reducing their level of support for libjingle.
I think the best place to get support is right here.

A: I mailed one of the google developers and he told me that libjingle does not have a specific forum. He suggested we try the WebRTC mailing list instead
https://groups.google.com/forum/?fromgroups#!forum/discuss-webrtc
Since libjingle is effectively a subset of WebRTC, and WebRTC has a more active community.
Although if you have an issue, you can add the issue to:
http://code.google.com/p/libjingle/issues/list


text:
Q: Convert RDD of LabeledPoint to DataFrame toDF() Error I have a dataframe df which contains 13 values separated with comma. I want to get in df2 a dataFrame wich contains labeledPoint. firt value is label, twelve others are features. I use a split and select method to divide string with 13 value into an array of 13 values. map method allow me to create labeledPoint. Error come when i use toDF() method to convert RDD to DataFrame
df2 = df.select(split(df[0], ',')).map(lambda x: LabeledPoint(float(x[0]),x[-12:])).toDF()

org.apache.spark.SparkException: Job aborted due to stage failure:
when I look in the stackerror I find:
IndexError: tuple index out of range.
in order to do test, I executed :
display(df.select(split(df[0], ',')))

i obtain my 13 values in an array for each row:
["2001.0","0.884123733793","0.610454259079","0.600498416968","0.474669212493","0.247232680947","0.357306088914","0.344136412234","0.339641227335","0.600858840135","0.425704689024","0.60491501652","0.419193351817"]

any Idea?

A: The Error come from the index x[0] should be replace by x[0][0].
So :
df2 = df.select(split(df[0], ',')).map(lambda x: LabeledPoint(float(x[0][0]), x[0][-12:])).toDF()


text:
Q: Include an image in itemize in a beamer presentation I have to do a presentation with beamer. In a frame I want to insert an image as a object in itemize, so in the first step is only visible the writings, while in the second step the image appears. Here is my code:
\documentclass{beamer}
\usepackage[italian,english]{babel}
\usepackage[latin1]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{amsmath}
\usepackage{ragged2e}
\usepackage{media9}

\begin{document}

\begin{frame}
\frametitle{Key Variables in the \textit{Bubble} Phenomena}
\begin{itemize}
\setbeamercovered{transparent}
\item[]<1-> The mean value $\bar{\beta}_{i,t}$ of the intensity parameter is crucial for the development of the synchronization phase, hence it also affects the production volume:
%\vspace{0.1cm}
\begin{center}
\item[]<2-> {\includegraphics[width=.45\textwidth]{gdp_betaC}}
\end{center}
\end{itemize}
\vspace{2cm}
\end{frame}

I don't know why, but if I use itemize with different writings as steps the code works, but if I include the image in the second step, the latter appears together with the first one.

A: You can use the overlay specification for \includegraphics:
\documentclass{beamer}
\usepackage[italian,english]{babel}
\usepackage[latin1]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{amsmath}
\usepackage{ragged2e}
\usepackage{media9}

\begin{document}

\begin{frame}
\frametitle{Key Variables in the \textit{Bubble} Phenomena}
\begin{itemize}
\setbeamercovered{transparent}
\item[] The mean value $\bar{\beta}_{i,t}$ of the intensity parameter is crucial for the development of the synchronization phase, hence it also affects the production volume:
\begin{center}
\item[] \includegraphics<2->[width=.45\textwidth]{example-image-a}
\end{center}
\end{itemize}
\end{frame}

\end{document}

If you don't want the text to "jump" from slide to slide, use overlayarea:
\documentclass{beamer}
\usepackage[italian,english]{babel}
\usepackage[latin1]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{amsmath}
\usepackage{ragged2e}
\usepackage{media9}

\begin{document}

\begin{frame}
\frametitle{Key Variables in the \textit{Bubble} Phenomena}
\begin{overlayarea}{\textwidth}{\textheight}
\begin{itemize}
\setbeamercovered{transparent}
\item[] The mean value $\bar{\beta}_{i,t}$ of the intensity parameter is crucial for the development of the synchronization phase, hence it also affects the production volume:
\begin{center}
\item[] \includegraphics<2->[width=.45\textwidth]{example-image-a}
\end{center}
\end{itemize}
\end{overlayarea}
\end{frame}

\end{document}

It's not clear to me why you are killing the itemize labels with \item[].


text:
Q: Using JPA+Google App Engine: No META-INF/persistence.xml files were found in the CLASSPATH I am new to Google App Engine. I've been around errors in my project for the last three days.
I set up JPA 2.0 with my Google App Engine project. The client is an Android application. When I am trying to insert an Entity, I am getting the following Warnings/Erros in my Google App Engine Logs. And I am not able to insert any Entities.
I put the persistence.xml file in the CLASSPATH. Also, I am using the option: "Discover annotated class automatically" in my project JPA configs. Please, let me know if I forgot to put any relevant code here.
Log:
com.google.api.server.spi.SystemService invokeServiceMethod: Could not initialize class com.sample.EMF
java.lang.NoClassDefFoundError: Could not initialize class com.sample.EMF
    at com.sample.GroupEndpoint.getEntityManager(GroupEndpoint.java:159)
    at com.sample.GroupEndpoint.insertGroup(GroupEndpoint.java:96)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:45)
    at com.google.api.server.spi.SystemService.invokeServiceMethod(SystemService.java:359)
    at com.google.api.server.spi.SystemServiceServlet.execute(SystemServiceServlet.java:127)
    at com.google.api.server.spi.SystemServiceServlet.doPost(SystemServiceServlet.java:85)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1166)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:388)
    at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
    at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182)
    at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:765)
    at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:418)
    at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
    at org.mortbay.jetty.Server.handle(Server.java:326)
    at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542)
    at org.mortbay.jetty.HttpConnection$RequestHandler.headerComplete(HttpConnection.java:923)
    at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404)
    at com.google.tracing.TraceContext$TraceContextRunnable.runInContext(TraceContext.java:437)
    at com.google.tracing.TraceContext$TraceContextRunnable$1.run(TraceContext.java:444)
    at com.google.tracing.CurrentContext.runInContext(CurrentContext.java:188)
    at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContextNoUnref(TraceContext.java:308)
    at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContext(TraceContext.java:300)
    at com.google.tracing.TraceContext$TraceContextRunnable.run(TraceContext.java:441)
    at java.lang.Thread.run(Thread.java:724)

My Entity class:
package com.sample;
import javax.persistence.Basic;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;

import com.google.appengine.api.datastore.Key;

@Entity
public class Group {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Key key;

    private String name;

    @Basic
    @ManyToOne
    private User owner;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public User getOwner() {
        return owner;
    }

    public void setOwner(User owner) {
        this.owner = owner;
    }

    public Key getKey() {
        return key;
    }
}

My Endpoint class:
    package com.sample;
    import java.util.List;
import javax.annotation.Nullable;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.EntityNotFoundException;
import javax.persistence.Query;

import com.google.api.server.spi.config.Api;
import com.google.api.server.spi.config.ApiMethod;
import com.google.api.server.spi.config.ApiNamespace;
import com.google.api.server.spi.response.CollectionResponse;
import com.google.appengine.api.datastore.Cursor;
import com.google.appengine.datanucleus.query.JPACursorHelper;

@Api(name = "groupendpoint", namespace = @ApiNamespace(ownerDomain = "sample.com", ownerName = "sample.com", packagePath = ""))
public class GroupEndpoint {

    /**
     * This method lists all the entities inserted in datastore.
     * It uses HTTP GET method and paging support.
     *
     * @return A CollectionResponse class containing the list of all entities
     * persisted and a cursor to the next page.
     */
    @SuppressWarnings({ "unchecked", "unused" })
    @ApiMethod(name = "listGroup")
    public CollectionResponse<Group> listGroup(
            @Nullable @Named("cursor") String cursorString,
            @Nullable @Named("limit") Integer limit) {

        EntityManager mgr = null;
        Cursor cursor = null;
        List<Group> execute = null;

        try {
            mgr = getEntityManager();
            Query query = mgr.createQuery("select from Group as Group");
            if (cursorString != null && cursorString != "") {
                cursor = Cursor.fromWebSafeString(cursorString);
                query.setHint(JPACursorHelper.CURSOR_HINT, cursor);
            }

            if (limit != null) {
                query.setFirstResult(0);
                query.setMaxResults(limit);
            }

            execute = (List<Group>) query.getResultList();
            cursor = JPACursorHelper.getCursor(execute);
            if (cursor != null)
                cursorString = cursor.toWebSafeString();

            // Tight loop for fetching all entities from datastore and accomodate
            // for lazy fetch.
            for (Group obj : execute)
                ;
        } finally {
            mgr.close();
        }

        return CollectionResponse.<Group> builder().setItems(execute)
                .setNextPageToken(cursorString).build();
    }

    /**
     * This method gets the entity having primary key id. It uses HTTP GET method.
     *
     * @param id the primary key of the java bean.
     * @return The entity with primary key id.
     */
    @ApiMethod(name = "getGroup")
    public Group getGroup(@Named("id") Long id) {
        EntityManager mgr = getEntityManager();
        Group group = null;
        try {
            group = mgr.find(Group.class, id);
        } finally {
            mgr.close();
        }
        return group;
    }

    /**
     * This inserts a new entity into App Engine datastore. If the entity already
     * exists in the datastore, an exception is thrown.
     * It uses HTTP POST method.
     *
     * @param group the entity to be inserted.
     * @return The inserted entity.
     */
    @ApiMethod(name = "insertGroup")
    public Group insertGroup(Group group) {
        EntityManager mgr = getEntityManager();
        try {
            mgr.persist(group);
        } finally {
            mgr.close();
        }
        return group;
    }

    /**
     * This method is used for updating an existing entity. If the entity does not
     * exist in the datastore, an exception is thrown.
     * It uses HTTP PUT method.
     *
     * @param group the entity to be updated.
     * @return The updated entity.
     */
    @ApiMethod(name = "updateGroup")
    public Group updateGroup(Group group) {
        EntityManager mgr = getEntityManager();
        try {
            if (!containsGroup(group)) {
                throw new EntityNotFoundException("Object does not exist");
            }
            mgr.persist(group);
        } finally {
            mgr.close();
        }
        return group;
    }

    /**
     * This method removes the entity with primary key id.
     * It uses HTTP DELETE method.
     *
     * @param id the primary key of the entity to be deleted.
     */
    @ApiMethod(name = "removeGroup")
    public void removeGroup(@Named("id") Long id) {
        EntityManager mgr = getEntityManager();
        try {
            Group group = mgr.find(Group.class, id);
            mgr.remove(group);
        } finally {
            mgr.close();
        }
    }

    private boolean containsGroup(Group group) {
        EntityManager mgr = getEntityManager();
        boolean contains = true;
        try {
            Group item = mgr.find(Group.class, group.getKey());
            if (item == null) {
                contains = false;
            }
        } finally {
            mgr.close();
        }
        return contains;
    }

    private static EntityManager getEntityManager() {
        return EMF.get().createEntityManager();
    }

}

EMF Class:
    package com.sample;
    import javax.persistence.EntityManagerFactory;
    import javax.persistence.Persistence;
public final class EMF {
    private static EntityManagerFactory emfInstance;

    private EMF() {
    }

    public static EntityManagerFactory get() {
        if(emfInstance == null) {
            emfInstance = Persistence
                    .createEntityManagerFactory("transactions-optional");
        }
        return emfInstance;
    }
}

persistence.xml file:
<?xml version="1.0" encoding="UTF-8" ?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
        http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0">

    <persistence-unit name="transactions-optional">
        <provider>org.datanucleus.api.jpa.PersistenceProviderImpl</provider>
        <properties>
            <property name="datanucleus.NontransactionalRead" value="true"/>
            <property name="datanucleus.NontransactionalWrite" value="true"/>
            <property name="datanucleus.ConnectionURL" value="appengine"/>
            <property name="datanucleus.singletonEMFForName" value="true"/>
        </properties>

    </persistence-unit>

</persistence>

Update: I know, the endpoints and persistence.xml, EMF were generated by the Plugin. But when I set up JPA, these errors come to me and I don't know how to solve this.

A: I finally solved my problem. Just to let you know what I did...

*

*I followed step-by-step this tutorial on Google Developers: https://developers.google.com/appengine/docs/java/datastore/jpa/overview-dn2#Setting_Up_JPA_2_0
Specially regarding: persistence.xml and its location.
Also, I did not trust on the automatic tracing of the Annotated Entities, so I transformed my persistence.xml into:
<?xml version="1.0" encoding="UTF-8" ?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
        http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
    version="1.0">

    <persistence-unit name="transactions-optional">
        <provider>org.datanucleus.api.jpa.PersistenceProviderImpl</provider>
            <class>com.sample.DeviceInfo</class>
            <class>com.sample.Group</class>
            <class>com.sample.User</class>
            <exclude-unlisted-classes>true</exclude-unlisted-classes>
        <properties>
            <property name="datanucleus.NontransactionalRead" value="true" />
            <property name="datanucleus.NontransactionalWrite" value="true" />
            <property name="datanucleus.ConnectionURL" value="appengine" />
            <property name="datanucleus.singletonEMFForName" value="true" />
            <property name="javax.persistence.query.timeout" value="5000" />
            <property name="datanucleus.datastoreWriteTimeout" value="10000" />
        </properties>

    </persistence-unit>

</persistence>

And also fixed my classpath to point to the right folders.
Thanks everybody who helped me!

A: The Google Plugin for Eclipse can create these files automatically for you when you create an Entity class.


text:
Q: Acceptable replacement for WinExec()? I want to run a command that the user defined in an INI file.
The commands can be EXE files, or other files (e.g. DOC files) and parameters should be allowed.
Since WinExec() can handle arguments (e.g. "cmd /?"), but ShellExec() can handle Non-EXE files (e.g. "Letter.doc"), I am using a combination of these both.
I am concerned about future Windows versions, because WinExec() is deprecated, and even from the 16 bit era.
Here is my current function:
procedure RunCMD(cmdLine: string; WindowMode: integer);

  procedure ShowWindowsErrorMessage(r: integer);
  begin
    MessageDlg(SysErrorMessage(r), mtError, [mbOK], 0);
  end;

var
  r, g: Cardinal;
begin
  // We need a function which does following:
  // 1. Replace the Environment strings, e.g. %SystemRoot%  --> ExpandEnvStr
  // 2. Runs EXE files with parameters (e.g. "cmd.exe /?")  --> WinExec
  // 3. Runs EXE files without path (e.g. "calc.exe")       --> WinExec
  // 4. Runs EXE files without extension (e.g. "calc")      --> WinExec
  // 5. Runs non-EXE files (e.g. "Letter.doc")              --> ShellExecute
  // 6. Commands with white spaces (e.g. "C:\Program Files\xyz.exe") must be enclosed in quotes.

  cmdLine := ExpandEnvStr(cmdLine);

  // TODO: Attention: WinExec() is deprecated, but there is no acceptable replacement
  g := WinExec(PChar(cmdLine), WindowMode);
  r := GetLastError;
  if g = ERROR_BAD_FORMAT then
  begin
    // e.g. if the user tries to open a non-EXE file
    ShellExecute(0, nil, PChar(cmdLine), '', '', WindowMode);
    r := GetLastError;
  end;
  if r <> 0 then ShowWindowsErrorMessage(r);
end;

function ExpandEnvStr(const szInput: string): string;
// http://stackoverflow.com/a/2833147/3544341
const
  MAXSIZE = 32768;
begin
  SetLength(Result, MAXSIZE);
  SetLength(Result, ExpandEnvironmentStrings(pchar(szInput),
    @Result[1],length(Result)));
end;

Microsoft recommends using CreateProcess(), but I do not accept it as a real replacement for WinExec().
For example, given following command line:
"C:\Program Files\xyz.exe" /a /b /c

Since ShellExecute() and CreateProcess() require a strict separation of command and arguments, I would have to parse this string myself. Is that really the only way I can go? Has someone written a public available code featuring this functionality?
Additional note: The process should not be attached to the caller. My program will close, right after the command has started.

A: CreateProcess() is the replacement for WinExec(). The documentation explicitly states as much.
And BTW, the error handling in your original code is completely wrong.  You are misusing GetLastError().  In fact, neither WinExec() nor ShellExecute() even report errors with GetLastError() to begin with.  So, even if WinExec() or ShellExecute() are successful (and you are not even checking if ShellExecute() succeeds or fails), you risk reporting random errors from earlier API calls.
Try something more like this:
procedure RunCMD(cmdLine: string; WindowMode: integer);

  procedure ShowWindowsErrorMessage(r: integer);
  var
    sMsg: string;
  begin
    sMsg := SysErrorMessage(r);
    if (sMsg = '') and (r = ERROR_BAD_EXE_FORMAT) then
      sMsg := SysErrorMessage(ERROR_BAD_FORMAT);
    MessageDlg(sMsg, mtError, [mbOK], 0);
  end;

var
  si: TStartupInfo;
  pi: TProcessInformation;
  sei: TShellExecuteInfo;
  err: Integer;
begin
  // We need a function which does following:
  // 1. Replace the Environment strings, e.g. %SystemRoot%  --> ExpandEnvStr
  // 2. Runs EXE files with parameters (e.g. "cmd.exe /?")  --> WinExec
  // 3. Runs EXE files without path (e.g. "calc.exe")       --> WinExec
  // 4. Runs EXE files without extension (e.g. "calc")      --> WinExec
  // 5. Runs non-EXE files (e.g. "Letter.doc")              --> ShellExecute
  // 6. Commands with white spaces (e.g. "C:\Program Files\xyz.exe") must be enclosed in quotes.

  cmdLine := ExpandEnvStr(cmdLine);
  {$IFDEF UNICODE}
  UniqueString(cmdLine);
  {$ENDIF}

  ZeroMemory(@si, sizeof(si));
  si.cb := sizeof(si);
  si.dwFlags := STARTF_USESHOWWINDOW;
  si.wShowWindow := WindowMode;

  if CreateProcess(nil, PChar(cmdLine), nil, nil, False, 0, nil, nil, si, pi) then
  begin
    CloseHandle(pi.hThread);
    CloseHandle(pi.hProcess);
    Exit;
  end;

  err := GetLastError;
  if (err = ERROR_BAD_EXE_FORMAT) or
     (err = ERROR_BAD_FORMAT) then
  begin
    ZeroMemory(@sei, sizeof(sei));
    sei.cbSize := sizeof(sei);
    sei.lpFile := PChar(cmdLine);
    sei.nShow := WindowMode;

    if ShellExecuteEx(@sei) then Exit;
    err := GetLastError;
  end;

  ShowWindowsErrorMessage(err);
end;

A: Although similar ShellExecute and CreateProcess serve a different purpose.
ShellExecute can open non executable files.   It looks up the information in the registry for the associated program for the given file and will execute it.   ShellExecute is also great for launching the default web browser and you can pass a URL to it it.
So if you were to pass an TXT file to ShellExecute it would open the associated program such as notepad.    However it would fail with CreateProcess.
CreateProcess is a lower level function, that allows you to have better control over the input and output from the the process.    For example you can call command line programs that have text output with CreateProcess and capture that output and react according.
Given the concerns you have you will need to use ShellExecute.    You will however need to split the command from the parameters.   This is would be the first non escaped whitespace character.
I personally rarely call ShellExecute or CreateProcess directly.   I tend to use on of the following functions from the JCL that wrap these functions.
JclMiscel.pas

*

*CreateDosProcessRedirected

*WinExec32

*WinExec32AndWait

*WinExecAndRedirectOutput

*CreateProcessAsUser

*CreateProcessAsUserEx

JclShell.pas

*

*ShellExecEx

*ShellExec

*ShellExecAndWwait

*RunAsAdmin

JclSysUtils.pas

*

*Execute  (8 Overloaded versions and is the one I use the most)


text:
Q: How can I call an anonymous function (stored in string) with an argument in JavaScript? I have the following situation in JavaScript:
Click

The handleClick function receives the second argument as a object with a onSuccess property containing the function definition...
How do I call the onSuccess function (which is stored as string) -and- pass otherObject to that function? (jQuery solution also fine...)?
This is what I've tried so far...
function handleClick(element, options, otherObject) {
    options.onSuccess = 'function() {alert(\'test\')}';

    options.onSuccess(otherObject); //DOES NOT WORK
    eval(options.onSuccess)(otherObject); //DOES NOT WORK
}

A: You really don't need to do this. Pass the function around as a string, i mean. JavaScript functions are first-class objects, and can be passed around directly:

  Click

...
function handleClick(element, options, otherObject) {
    options.onSuccess(otherObject); // works...
}

But if you really want to do it your way, then cloudhead's solution will do just fine.

A: Try this:
 options.onSuccess = eval('function() {alert(\'test\')}');
 options.onSuccess(otherObject);

A: It only worked on my FF when I added an assignmnet into a dummy variable:
 options.onSuccess = 'dummyVariable = function(x) {alert("x=" + x);}';
 f = eval(options.onSuccess);
 f(5);


text:
Q: Отслеживание нажатия кнопки в electron Есть div который содержит в себе еще два div, один с иконкой а другой с текстом, сделал таким способом реакцию на нажатие
addEventListener('click', event => {
    onClick(event.srcElement.id);
});

function onClick(id){
    console.log(id);
}

при нажатии на div все ок, в консоль выводится id этого div, но если нажать на иконку или текст, выводится id иконки или текста. Но ведь функция вызвалась, а привязана она к нажатию не иконки или текста, а div. Как отследить конкретно id этого div без jQuery и т.д и т.п?

A: Судя по коду событие привязано совсем не к div, а к window. Повесьте событие на div.addEventListener, а вместо event.srcElement.id используйте div.id


text:
Q: How to loop over the query results of a comments system with replies? I am trying to display comments from database. Some comments are children of other comments (parents), so in my database I put a field of parent with null as default value, if the new comment is a child comment I insert the id of the parent comment in that field.
Insertion works fine but I am facing issues with displaying system. I try to display every child comment under its paren, with my code parent element are displayed but children remains empty.
I have tried with the print_r function to see if there is data in the array, it shows data, I think i am missing something or I'm having some logical error in my code construction.
if(is_array($this->comments))
{
    $comments = array();
    $parent_array = array();
?>

    <?php
    foreach($this->comments as $key => $value) {
        if($value['parent'] === 0) {
            $comments[] = $value;
        } else {
            $parent_array['parent'][] = $value;
            $comments[] = $parent_array;
        }
    }
    foreach($comments as $key => $value) {
    ?>

        - <?php echo $value['id']; ?>

 <?php echo $value['title'] ; ?>

 <?php echo $value['description'] ; ?>

    <?php
    }
}
?>

A: Looked at your code, I don't think you are grouping your comments and sub-comments well. Try this
<?php
       $all_comments = [];

       foreach($this->comments as $key => $value){
          if($value['parent'] === 0)
          {
            $all_comments[$value['id']]['comment'] = $value;
          } else {
            $all_comments[$value['parent']]['subcomment'][] = $value;
          }
       }

       foreach($all_comments as $comment){
          // display only main comments here
          if(isset($comment['comment'])) {
            ?>

            - <?php echo $comment['comment']['id']; ?>

 <?php echo $comment['comment']['title'] ; ?>

 <?php echo $comment['comment']['description'] ; ?>

            <?php
               if(isset($comment['subcomment'])) {
                   displaySubComment($all_comments, $comment);
               }
          }
     }

     function displaySubComment($all_comments, $comment)
     {
       foreach($comment['subcomment'] as $subcomment) {
          ?>

 Sub-Comments

 <?php echo $subcomment['title'] ; ?>

 <?php echo $subcomment['description'] ; ?>

          <?php
          // re-iterate over itself, if more comments exist under a comment and display all
          if(array_key_exists($subcomment['id'], $all_comments)) {
             displaySubComment($all_comments, $all_comments[$subcomment['id']])
          }
       }
     }
?>


text:
Q: don't know how to override parent widget's style I have defined a custom Rectangle widget and am trying to assign a custom stylesheet to it. Can anybody help and tell why the below-quoted code does not paint Rectangle in red? Options 1. and 3. in the code show a white color which is inherited from QWidget, I suppose. And, option 2. makes my widget hidden, probably because Window's stylesheet dominates.
import sys

from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget

class Rectangle(QWidget):

  def __init__(self, parent):
      super(Rectangle, self).__init__(parent)
      self.setGeometry(20, 20, 200, 400)
      self.setAutoFillBackground(True)

      # 1.
      self.setObjectName = "Rectangle#rect"
      self.setStyleSheet("Rectangle#rect {background-color: red;}")

      # 2.
      # self.setStyleSheet("Rectangle {background-color: red;}")

      # 3.
      # self.setStyleSheet("{background-color: red;}")

class Window(QMainWindow):

    def __init__(self):
        super(Window, self).__init__()

        self.setGeometry(200, 200, 300, 500)
        self.setWindowTitle("Test")
        self.setAutoFillBackground(True)
        self.setStyleSheet("Window {background-color: blue;}")

        rect = Rectangle(self)
        self.show()

def run():
    app = QApplication(sys.argv)
    GUI = Window()
    sys.exit(app.exec_())

run()


text:
Q: How can I switch seamlessly between wired and wireless network? My laptop is usually connected via wifi (old T61 with Intel
WM3945ABG). For most of my work, this is sufficient. Now and then, I'd
like to hook up to my fine 1GB wired ethernet. But if I do it naively,
nfs mounts start to hang. (If I unmount all nfs before the change, all
is fine).
For example, my backup starts via anacron. This involes mounting the
backup drive on my server via nfs4. Most likely, I'm on wifi if this
happens. If I now plug in my ethernet cable, all access to the backup
drive result in a uninterruptible sleep. As the backup takes quite
some time (slow wifi, remember?), I'm not able to unmount and remount
the backup drive.
This involes blocked dialogues and shells (maybe they scan all
mountpoints when opened, I don't know).
I'm with Linux since Kernel 2.0.2 and to be honest, this is the /only/
thing with Linux that really drives me crazy, because I'm not able to
solve it.
Is there a way to transparently exchange wired and wireless networking?
Oh, some missing facts:
Currently, I'm using WICD, but I tried NetworkManager before. I'm
considering a systemd-only approach...
% /sbin/iwconfig wlan0

wlan0     IEEE 802.11  ESSID:"the-grue"
      Mode:Managed  Frequency:2.422 GHz  Access Point: 64:70:02:A2:67:DE
      Bit Rate=54 Mb/s   Tx-Power=15 dBm
      Retry short limit:7   RTS thr:off   Fragment thr:off
      Power Management:off
      Link Quality=70/70  Signal level=-33 dBm
      Rx invalid nwid:0  Rx invalid crypt:0  Rx invalid frag:0
      Tx excessive retries:0  Invalid misc:476   Missed beacon:0

% mount | grep nfs
zem:/backup on /media/backup type nfs4
(rw,relatime,vers=4.1,rsize=65536,wsize=65536,namlen=255,soft,proto=tcp,port=0,timeo=600,retrans=2,sec=sys,clientaddr=192.168.178.63,local_lock=none,addr=192.168.178.2)

Both networks use the same IP and so on...
Please tell me, if you need further information!

A: Without some help on the other side, either where your WLAN and GB LAN converge (i.e. your home router), or where the other communication point is, you can't.
And that's really not a Linux issue, it's because networking protocols are the way they are (for historical reasons): Both TCP and UDP don't support fail-over multihoming, i.e. having several interfaces with different IP addresses at one end that can all be used equivalently.
That said, there are a few ways to make something like this work, but none of them are easy, I haven't tried to implement one of them myself, and it will take considerable effort to make them work, if they work at all:
1) Instead of TCP and UDP, use a protocol that allows fail-over multihoming, for example SCTP. While SCTP is natively available in the Linux kernel, not many use it. So you'll have to find an application that does what you want and supports SCTP on both ends, and good luck with that. Or you'll have to modify existing applications like NFS or your backup to support SCTP, and again, good luck with that.
Edit: I found there is a wrapper command called withsctp that makes the wrapped application use SCTP instead of TCP. I tested with nc and socat with two pairs of veth connections to a network namespaces, and failover multihoming works out of the box: shutting down the pair where the connection was initiated doesn't interrupt transmission, which gets moved to the other pair. But it looks like both network interfaces need to be visible when the connection is established, as the available addresses are part of the SCTP handshake.
I didn't test, but this may work for your backup program, or FUSE remote filesystems like SSHFS, or even kernel filesystems like NFS.
2) You can bond several interfaces together, see linux/Documentation/networking/bonding.txt in the kernel sources. This is really just meant to bond e.g. parallel LAN connections in a datacenter. You'll need to do this on both sides, e.g. your PC and your router (which means you might need to recompile the Linux kernel of your firmware for the router), and you'll have to make sure both interfaces are reasonably static (esp. WLAN). If you get this work, I'd be interested in the details.
3) You can try to setup the router so it gives both your WLAN and your LAN interface exactly the same IP address, and disables your WLAN interface as soon as it sees the LAN. That will require quite a bit of fiddling with the router internals, and again, if you get this work, I'd be interested in the details.
There are probably other, equally obscure methods. Writing a script that unmounts/remounts NFS, and checks you're not in the middle of a backup before activating the LAN interface might be easier.


text:
Q: Combining RxJava 2 observables where some may never emit I'm working on a chat client which needs to combine data from two different Rx sources:

*

*A REST gateway which fetches an initial list of available chats and their messages: Observable<List<Conversation>> getConversations()

*A websocket gateway which emits new messages as they arrive: Observable<Message> getMessages()
Both observables should be combined in a single Observable<ConversationsModel> where ConversationsModel holds the conversation list and contains the logic to add messages to a given conversation.
The combined observable should emit the updated ConversationsModel every time either of the observables emits: on subscription the REST observable emits once and the websocket connection is established. Then, any new messages coming through the socket gateway should be added to the model, which is then re-emitted.
Here's my current solution which works, but I'm not happy with it since the ConversationsModel needs to be created outside the stream:
ConversationsModel conversations = new ConversationsModel();
conversationsObservable = restGateway.getConversations().map(list -> conversations.setConversations(list))
    .mergeWith(socketGateway.getMessages().map(message -> conversations.addMessage(message)))
    .doOnSubscribe(disposable -> socketGateway.connect())
    .doOnDispose(() -> socketGateway.disconnect())
    .replay(1)
    .refCount();

What I'm looking for is something rather like this:
conversationsObservable = restGateway.getConversations().map(list -> new ConversationsModel(list))
    .withLatestFrom(socketGateway.getMessages(), (conversationsModel, message) -> conversationsModel.addMessage(message))
    .doOnSubscribe(disposable -> socketGateway.connect())
    .doOnDispose(() -> socketGateway.disconnect())
    .replay(1)
    .refCount();

The problem is that withLatestFrom (as well as all other operators I've tried so far) does not emit anything until all observables have emitted at least once. In practice this means my UI will be blocked until the first message arrives through the socket connection, which is of course unacceptable.


text:
Q: How to make a script to test passwords on router settings I have changed the firmware of my router but now I cannot authenticate on my router settings. On 192.168.1.1 it requests login and password but mine isn't working. The login is probably root and I believe that the password has 8 chars.
So I want to try to get the password by brute force. I'm looking for suggestions to do it, like which language and something similar to look or if anyone already made that.
My experience is mostly C, C++ and Java.

A: Not really a programming question.
The tool you're looking for is probably hydra. Note that brute-forcing will take a lot of time. You will be better of searching the web for default passwords and/or do a factory reset of the router.


text:
Q: Fill Two Arrays on the fly From stdin File in Bash I wrote a bash script that reads a file from stdin $1, and needs to read that file line by line within a loop, and based on a condition statement in each iteration, each line tested from the file will feed into one of two new arrays lets say named GOOD array and BAD array. Lastly, I'll display the total elements of each array.
#!/bin/bash

      for x in $(cat $1); do
        #testing something on x
        if [ $? -eq 0 ]; then
          #add the current value of x into array called GOOD
        else
          #add the current value of x into array called BAD
        fi
      done

      echo "Total GOOD elements: ${#GOOD[@]}"
      echo "Total BAD elements: ${#BAD[@]}"

What changes should i make to accomplish it?

A: #!/usr/bin/env bash

# here, we're checking the number of lines more than 5 characters long
# replace with your real test
testMyLine() { (( ${#1} > 5 )); }

good=( ); bad=( )
while IFS= read -r line; do
  if testMyLine "$line"; then
    good+=( "$line" )
  else
    bad+=( "$line" )
  fi
done <"$1"

echo "Read ${#good[@]} good and ${#bad[@]} bad lines"

Note:

*

*We're using a while read loop to iterate over file contents. This doesn't need to read more than one line into memory at a time (so it won't run out of RAM even with really big files), and it doesn't have unwanted side effects like changing a line containing * to a list of files in the current directory.

*We aren't using $?. if foo; then is a much better way to branch on the exit status of foo than foo; if [ $? = 0 ]; then -- in particular, this avoids depending on the value of $? not being changed between when you assign it and when you need it; and it marks foo as "checked", to avoid exiting via set -e or triggering an ERR trap when your boolean returns false.

*The use of lower-case variable names is intentional. All-uppercase names are used for shell-builtin variables and names with special meaning to the operating system -- and since defining a regular shell variable overwrites any environment variable with the same name, this convention applies to both types. See http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html


text:
Q: Parametrized subsets As far as I understood it, you can only parametrize subsets by values itself
subset MoreThanZero where * > 0

But, is there a direct way of implementing something like this?
subset MoreThan[\x] where * > x

And then declare
my MoreThan[1000] $thousand-plus

Maybe a roundabout way would be to use parameterized roles, but I was thinking about a more direct approach. Is there one?

A: Probably the easiest option is to create a type that provides a custom parameterize method, and then using the MOP to construct a subset type based on that:
class MoreThan {
    method ^parameterize(Mu, $limit) {
        Metamodel::SubsetHOW.new_type:
            name => "more than $limit",
            refinee => Numeric,
            refinement => * > $limit
    }
}

Then this:
my MoreThan[0] $x = 1;
say $x;
my MoreThan[2] $y = 3;
say $y;
$y = 1;

Produces:
1
3
Type check failed in assignment to $y; expected more than 2 but got Int (1)
  in block <unit> at ss.p6 line 14


text:
Q: Inconsistent margin for footer (Word 2007) Margins between text and footers in different page of the document is inconsistent. Margins also change while editing the footer.
page 11:

page 11 with footer selected:

page 12:

page 12 with footer selected:


text:
Q: Connect configuration item (CI) from CMDB to Customer I have the latest version of OTRS(5.0.14) with the following packages:

*

*DynamicFieldITSMConfigItem

*GeneralCatalog

*ITSM-CIAttributeCollection

*ITSMConfigurationManagement

*ITSMCore

Is it possible to relate CIs to company and/or to customer user natively or with some free package? Please, give me some examples.
Is it possible to have an auto-complete field which will populates only with CIs of the selected company/customer? See: i.imgur.com/hYTUl92.jpg
Thanks.

A: Owner field in CI definition can be used to define the customer.


text:
Q: Enable Session state in sharePoint 2010 I setup a test box computer with server 2008 (standard edition, not R2 and not hyper-v editing). I then installed SharePoint 2010. I was amazed how easy the whole setup went (the prerequisites  setup on the SharePoint disk made this process oh so easy – great install system). Really this was just so easy.
This test box is being used for testing Access web services. I am able to well publish access applications to this test server and Access applications publish and run just fine on the web SharePoint site through an web browser.
However, the only thing that does not work is when I launch a Access report. The error message I get back is
This report failed to load because session state is not turned on.
Here is a screen shot:

I can't seem to find the setting anywhere to turn session state on. Any hints or links on how to enable session state in SharePoint 2010 would be most appreciated.

A: On Todds blog you can find a post which explains how to turn on session state in SharePoint 2010.

A: Here is the solution:
http://geekdeck.com/sharepoint-2010-this-report-failed-to-load-because-session-state-is-not-turned-on/

A: Probably not in SharePoint  head over to the IIS configuration and see whether session state is enabled there. I am not aware of anything in the SharePoint forms (I did set up 2010 on the weekend) that indicates session state. And as session state on farms is an administrator action (state server etc.), maybe they simply did not activate it?;)


text:
Q: How do I boost a result based on a static value in ElasticSearch? How can I boost results based on their document type?
We're using ElasticSearch to power the search feature on a website. My client has asked if their Products and Services pages can bubble up to the top of the results, but not in a totally artificial way.
For example, say the results as they stand right now were:

Result
Score

News Article 1
99

News Article 2
80

News Article 3
70

Service 1
60

News Article 4
50

Product 2
40

News Article 5
30

Maybe we give Products and Services a 25 point boost so the results would come out in a semi-organic manner, like so.

Result
Score

News Article 1
99

Service 1
85

News Article 2
80

News Article 3
70

Product 2
65

News Article 4
50

News Article 5
30

A: You can try using a combination of bool/should clause along with boost applied on the term query
{
  "query": {
    "bool": {
      "should": [
        {
          "match_all": {}
        },
        {
          "term": {
            "name": {
              "value": "Product 2",
              "boost": 25
            }
          }
        },
        {
          "term": {
            "name": {
              "value": "Service 1",
              "boost": 25
            }
          }
        }
      ]
    }
  }
}


text:
Q: Sort List of object based on start date of the course I need to sort a list of courses with a start date the dates is Strings.
The sort should be based on the start date, my date in the list is looks like:

*

*03:20

*04:10

*09:40

*08:00

*08:50

*01:50

*02:30

Note That the sort here is custom and every item with start date from 01 until 07 should be below dates from 08 until 12
for example the list above will be:

*

*08:00

*08:50

*09:40

*01:50

*02:30

*03:20

*04:10

How can I achieve this, I tried this:
int compare = this.getStartDate().compareTo(o.getStartDate());
if (compare > 0 && this.getStartDate().charAt(1) >= '1' && this.getStartDate().charAt(1) <= '7')
        return -1;
if (compare < 0 && o.getStartDate().charAt(1) < '1' && o.getStartDate().charAt(1) > '7')
        return 1;
return compare;

A: Use this method that converts the times below "08:00" to times greater than "12:00" by adding 12 to the hour part:
public static String getValue(String s) {
    String[] splitted = s.split(":");
    int hour = Integer.parseInt(splitted[0]);
    if (hour < 8) {
        hour += 12;
        splitted[0] = String.valueOf(hour);
    }
    return splitted[0] + ":" + splitted[1];
}

now compare like this:
return getValue(this.getStartDate()).compareTo(getValue(o.getStartDate()));

A: java.time
Don't represent your time of day by strings in your model. Use a proper time-of-day class. Java has one built in (from Java 8 and on; also backported to Java 6 and 7): LocalTime.
public class Course implements Comparable<Course> {

    private static final LocalTime START_OF_COURSE_DAY = LocalTime.of(8, 0);
    /** Constant for PM of day (afternoon) */
    private static final int PM = 1;
    private static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern("hh:mm");

    LocalTime time;

    /**
     * @param timeString
     *          If the time string begins with 08 through 11, it is in AM, otherwise in PM
     */
    public Course(String timeString) {
        // Even though the time string is in either AM or PM,
        // just parse the hour as hour of day and adjust afterward.
        time = LocalTime.parse(timeString);
        if (time.isBefore(START_OF_COURSE_DAY)) {
            // time is in PM
            time = time.with(ChronoField.AMPM_OF_DAY, PM);
        }
        // toString() should give the same string back
        if (! toString().equals(timeString)) {
            System.out.println("Unexpected time format: " + timeString);
        }
    }

    @Override
    public int compareTo(Course o) {
        return time.compareTo(o.time);
    }

    @Override
    public String toString() {
        return time.format(TIME_FORMATTER);
    }

}

Since LocalTime is comparable (has a natural order that agrees with the ordering we want), the implementation of compareTo is a one-liner.
Let's try it out:
        List<Course> listOfCourses = Arrays.asList(
                new Course("03:20"),
                new Course("04:10"),
                new Course("09:40"),
                new Course("08:00"),
                new Course("08:50"),
                new Course("01:50"),
                new Course("02:30"),
                new Course("12:30"));
        listOfCourses.sort(Comparator.naturalOrder());

        listOfCourses.forEach(System.out::println);

Output is:

08:00
08:50
09:40
12:30
01:50
02:30
03:20
04:10

Link: Oracle tutorial: Date Time explaining how to use java.time.


text:
Q: How do I remove the "from iPhone" dock icon popping up, MacOS High Sierra I updated my OS to High Sierra, 10.13.5, and started seeing a weird dock icon pop up whenever I open a mail app on my iPhone. I want to get rid of this feature. Dock Preferences do not seem to have option to remove it. Thanks

A: Turn off Handoff.  That's the phone handing off the mail to the Mac.


text:
Q: Change text in google Pay giftcard When creating a giftcard in google pay via API I everytime see the wording "Geschenkkarte":

My goal is to change this wording to "Guthabenkarte". Is there a way to do this? I tried every string I could find in the documentation: https://developers.google.com/pay/passes/rest/v1/giftcardclass
Is there a way to do that?

A: As per https://developers.google.com/pay/passes/guides/pass-verticals/gift-cards/design#card-title the card title cannot be edited.
You can ask for this as a feature request see https://support.google.com/pay/merchants/contact/instore_merchant_support?visit_id=637189488311884461-3625029917&rd=1


text:
Q: c++ (why) does move constructor delete operator= I have a vector with structs
Struct S {
    S( double a, double b ) : a_(a), b_(b) {}
    double a_;
    double b_;
    S(S&&) = default;   //ADDED
}

and I use emplace back to add instances of s to the vector
v.emplace_back( x, y );

Since it doesn't seem to be guaranteed that compilers will add a move constructor, I thought there is no harm in adding a default move constructor, so I added the line commented as ADDED.
However, this seemed to have disabled the operator= as I get the compile error
/opt/rh/devtoolset-3/root/usr/include/c++/4.9.2/bits/stl_algo.h:868: error: use of deleted function 'S& S::operator=(const S&)'
         *__result = _GLIBCXX_MOVE(*__first);
                   ^

I dont understand why that is the case. Is my implementation of S(S&&) the wrong way to do it?
EDIT:
The error is thrown when using erase-remove
v.erase(std::remove_if(v.begin(), v.end(), deleteIf), v.end());

A: A default copy assignment operator will be automatically provided (performing a memberwise copy) unless the class declares a copy assignment operator, deletes the copy assignment operator, or declares a move operation. The reason for this is that the compiler assumes that if you declare any move operation, it is likely that your class holds data which should not be copied, and so it forces you to implement the copy assignment operator yourself, in an attempt to enforce the Rule of Five.
There's an excellent chart showing when default constructors and assignment operators are provided in this slideshow, slide 30.

A: Some older implementations of STL containers use the assignment operator when they resize the underlying containers. To resize, they allocate memory, default construct the initial objects, copy the objects over to the new container by using the assignment operator, and then release the previous objects.
On a related topic, if you are going to make an object Move-Constructible, you should also make it Move-Assignable.
Since the only data members in your struct are double's - primitive types that don't allocate resources - you don't need a move constructor for this struct.


text:
Q: How can i optimize MariaDB's my.cnf file? (with mysqltuner result) I am using MariaDB & Apache (LAMP) and my VPS Ram is 512MB.
Now the problem is sometimes when i use top, the MariaDB process is using 506MB of RAM so i want to optimize my MariaDB.
Here is my ./mysqltuner.pl's result:
[!!] Currently running unsupported MySQL version 10.0.11-MariaDB-log
[OK] Operating on 32-bit architecture with less than 2GB RAM

-------- Storage Engine Statistics -------------------------------------------
[--] Status: +ARCHIVE +Aria +BLACKHOLE +CSV +FEDERATED +InnoDB +MRG_MyISAM
[--] Data in MyISAM tables: 33M (Tables: 94)
[--] Data in InnoDB tables: 6M (Tables: 111)
[--] Data in CSV tables: 0B (Tables: 2)
[--] Data in PERFORMANCE_SCHEMA tables: 0B (Tables: 52)
[!!] Total fragmented tables: 4

-------- Security Recommendations  -------------------------------------------
[OK] All database users have passwords assigned

-------- Performance Metrics -------------------------------------------------
[--] Up for: 8m 39s (3K q [7.657 qps], 39 conn, TX: 32M, RX: 513K)
[--] Reads / Writes: 98% / 2%
[--] Total buffers: 94.0M global + 26.3M per thread (50 max threads)
[!!] Maximum possible memory usage: 1.4G (282% of installed RAM)
[OK] Slow queries: 0% (0/3K)
[OK] Highest usage of available connections: 4% (2/50)
[OK] Key buffer size / total MyISAM indexes: 4.0M/3.9M
[OK] Key buffer hit rate: 99.0% (29K cached / 281 reads)
[OK] Query cache efficiency: 40.9% (2K cached / 6K selects)
[OK] Query cache prunes per day: 0
[OK] Sorts requiring temporary tables: 0% (0 temp sorts / 481 sorts)
[!!] Temporary tables created on disk: 35% (75 on disk / 213 total)
[OK] Thread cache hit rate: 94% (2 created / 39 connections)
[OK] Table cache hit rate: 493% (79 open / 16 opened)
[OK] Open file limit used: 0% (52/65K)
[OK] Table locks acquired immediately: 100% (1K immediate / 1K locks)
[OK] InnoDB buffer pool / data size: 64.0M/6.3M
[OK] InnoDB log waits: 0
-------- Recommendations -----------------------------------------------------
General recommendations:
    Run OPTIMIZE TABLE to defragment tables for better performance
    MySQL started within last 24 hours - recommendations may be inaccurate
    Reduce your overall MySQL memory footprint for system stability
    When making adjustments, make tmp_table_size/max_heap_table_size equal
    Reduce your SELECT DISTINCT queries without LIMIT clauses
Variables to adjust:
  *** MySQL's maximum memory usage is dangerously high ***
  *** Add RAM before increasing MySQL buffer variables ***
    tmp_table_size (> 16M)
    max_heap_table_size (> 8M)

and here is my my.cnf's content:
[client]
port = 3306
socket = /tmp/mysql.sock

[mysqld]
port = 3306
socket = /tmp/mysql.sock

basedir = /usr/local/mariadb
datadir = /data/mariadb
pid-file = /data/mariadb/mysql.pid
user = mysql
bind-address = 0.0.0.0
server-id = 1

skip-name-resolve
#skip-networking
back_log = 300

max_connections = 20
max_connect_errors = 6000
open_files_limit = 65535
table_open_cache = 128
max_allowed_packet = 4M
binlog_cache_size = 1M
max_heap_table_size = 8M
tmp_table_size = 16M

read_buffer_size = 2M
read_rnd_buffer_size = 8M
sort_buffer_size = 8M
join_buffer_size = 8M
key_buffer_size = 4M

thread_cache_size = 8

query_cache_size = 8M
query_cache_limit = 2M

ft_min_word_len = 4

log_bin = mysql-bin
binlog_format = mixed
expire_logs_days = 30

log_error = /data/mariadb/mysql-error.log
slow_query_log = 1
long_query_time = 1
slow_query_log_file = /data/mariadb/mysql-slow.log

performance_schema = 0

#lower_case_table_names = 1

skip-external-locking

default_storage_engine = InnoDB
#default-storage-engine = MyISAM
innodb_file_per_table = 1
innodb_open_files = 500
innodb_buffer_pool_size = 64M
innodb_write_io_threads = 4
innodb_read_io_threads = 4
innodb_thread_concurrency = 0
innodb_purge_threads = 1
innodb_flush_log_at_trx_commit = 2
innodb_log_buffer_size = 2M
innodb_log_file_size = 32M
innodb_log_files_in_group = 3
innodb_max_dirty_pages_pct = 90
innodb_lock_wait_timeout = 120

bulk_insert_buffer_size = 8M
myisam_sort_buffer_size = 8M
myisam_max_sort_file_size = 10G
myisam_repair_threads = 1

interactive_timeout = 28800
wait_timeout = 30

[mysqldump]
quick
max_allowed_packet = 16M

[myisamchk]
key_buffer_size = 8M
sort_buffer_size = 8M
read_buffer = 4M
write_buffer = 4M

I have no idea what i can do. Help me please!

A: You should use the last version available on github.
Memory advice seems to be wrong andhave been corrected since.
Temporary table can be configurated with tmp_table_size and max_heap_table_size variable.
https://www.percona.com/blog/2007/01/19/tmp_table_size-and-max_heap_table_size/


text:
Q: filter: progid:DXImageTransform.Microsoft.AlphaImageLoader I am writing some css that requires background-size: 100% 100%.
Unfortunately, as this is a css3 property, it is un supported in IE8 and below. However, I read about a hack, which I have tried using below:
#submit{
  filter: progid:DXImageTransform.Microsoft.AlphaImageLoader( enabled='true'
src='/images/btn.png', sizingMethod='scale');

  -ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader( enabled='true'
src='/images/btn.png', sizingMethod='scale')";

  background: url('/images/btn.png') no-repeat;
  background-size: 100% 100%;
}

#submit is the id of a submit button.
Unfortunately, this doesn't seem to be work. Any solutions?

A: filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(
src='images/logo.gif',
sizingMethod='scale');

-ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(
src='images/logo.gif',
sizingMethod='scale')";

This would scale it to the size of the whole page. But there is no real deal to ensure that background-size is working in IE. Even the MSDN Documentation tells that.

*

*http://msdn.microsoft.com/en-us/library/cc351024%28VS.85%29.aspx#color
And btw: this is a possible duplicate of How do I make background-size work in IE?

A: The best approach is to avoid AlphaImageLoader completely and use gracefully degrading PNG8 instead, which are fine in IE. If you absolutely need AlphaImageLoader, use the underscore hack _filter as to not penalize your IE7+ users.
Please check this link for your reference. https://developer.yahoo.com/performance/rules.html#no_filters=


text:
Q: Send values from one browser tab to another in nextjs and populate formik form I have a form in next with a single input e.g. name on my page. On submit I would like the browser to open a new tab which contains a form with more inputs e.g. name, address, age. How can I pre-populate the name in the new tab?
I was considering the useContext hook but as far as I can tell that does not work across tabs. Do I need to use Redux at this point?
Edit: My attempt using localStorage so far:
// User inputs name which on submit is
// saved to local storage and /register page is opened
const Home: NextPage = () => {
  return (
    <Formik
          initialValues={{ name: '' }}
          onSubmit={(values) =>
            localStorage.setItem('name', values.name)
          }
        >
          {() => (
            <Form>

                <InputBox
                  type="text"
                  id="name"
                  name="name"
                  htmlFor="name"
                  label="Name"
                  placeholder=""
                />
                <button
                  type="submit"
                  // ? Not sure using window is the correct way to do this in nextjs
                  onClick={(event) => window.open('/register', '_blank')}
                >
                  Start KYC
                </button>

            </Form>
          )}
    </Formik>
)

import { Field, Form, Formik } from 'formik'
import { NextPage } from 'next'
import React from 'react'

const Register: NextPage = () => {
  let nameInit = ''
  React.useEffect(() => {
    if (typeof window !== 'undefined') {
      console.log('You are on the browser')
      //  can use localStorage here
    } else {
      console.log('You are on the server')
      //  can't use localStorage
    }
    nameInit = localStorage.getItem('name') ?? ''
    console.log(nameInit)
  }, [])
  return (
    <Formik
      initialValues={{
        name: nameInit,
      }}
      onSubmit={async (values) => {
        console.log(values)
      }}
    >
      {() => (
        <Form className="space-y-8 divide-y divide-gray-200">

              First name

            <Field
              type="text"
              name="name"
              id="name"
              autoComplete="given-name"
            />

            <button
              type="submit"
            >
              Submit
            </button>

        </Form>
      )}
    </Formik>
  )
}

Inspecting the page I can see that the value is being set and the console.log at the end of the useEffect also returns the expected value. But the form is still not being populated... My guess is the form is rendered before the useEffect is executed? When I just write the code in the function body instead of using useEffect it seems that is being executed on the server where localStorage is not available.

A: You're closer than you think! It works across tabs, but you might be using <link> or  tags to navigate.
If you use the built in next/link, your app won't refresh and useContext will work for you. Your app will also take advantage of Next JS's speed optimisations. Example:
import Link from "next/link"

const Nav = () => (
  <Link href="gosomewhere">
    I'm a Link
  </Link>
)


text:
Q: Proving cardinality of an uncountable sum I'm trying to prove the following thing:
For a family $\mathcal{A}$ of countable sets such that $|\bigcup\mathcal{A}|$ is uncountable and such that $\big|\{A\in\mathcal{A}: x\notin A\}\big| \leq\aleph_0$ for every $x\in\bigcup\mathcal{A}$, we have $|\bigcup\mathcal{A}|=\aleph_1$.
Of course cardinality of this sum is at least $\aleph_1$. To show the other inequality, I firstly tried to find an injection from $\mathcal{A}$ to the set of all countable ordinals thinking that I might assign a type for every $A$ in the family and get $|\mathcal{A}|\leq\aleph_1$ (and proceed with $|\bigcup\mathcal{A}|\leq|\mathcal{A}|\cdot|A|)$. Sadly that's a dead-end, because sets of this family can be of the same ordinal type.
Now I'm thinking of a contradiction if I assume $|\bigcup\mathcal{A}|=\aleph_{\alpha}$, but can't find any as of yet.
Could you help me, give a hint?

A: Suppose the size of the union is $\ge\aleph_2$. Then there are at least $\aleph_2$-many $A$s. Fix distinct elements $x_\alpha$ ($\alpha<\omega_1$) of the union $\bigcup \mathcal{A}$. By the hypothesis, each $x_\alpha$ is in all but countably many of the $A$s. But then:

*

*What can you say about the size of the set $\{A\in\mathcal{A}: \exists \alpha<\omega_1(x_\alpha\not\in A)\}$?

*How does this compare with the size of $\mathcal{A}$?

*Why does this violate the assumption that each $A\in\mathcal{A}$ is countable?

A: By contradiction, suppose $f:\cup \mathcal A\to \omega_2$ is an injection. Let $g:\omega_1\to \mathcal A$ also be an injection. For $x\in \omega_2$ let $h(x) =\min \{y\in \omega_1: f(x)\in g(y)\}.$ We know $h(x)$ exists because $\{y\in \omega_1: f(x)\not \in g(y)\}$ is countable.
Since $h:\omega_2\to \omega_1$, there exists $y\in \omega_1$ such that $|h^{-1}\{y\}|=\omega_2.$ But $h^{-1}\{y\}$ is countable because $$x\in h^{-1}\{y\}\implies h(x)=y\implies f(x)\in g(y)\implies x\in f^{-1}(g(y)),$$ while $f$ is an injection and $g(y)\in \mathcal A$ is countable.


text:
Q: About tbb tasks When working with tasks, for example with this:
class MyTask: public tbb::task {
  private:
    int x;
  private:
    void DoSomething(...){...} // Invoked only inside execute
    void DoMore(...){...}  // Invoked only inside execute
  public:
    MyTasks(...){...}
    tbb::task* execute(){...}
};

Once the task is running, is it possible to execute concurrently DoSomething() or DoMore() or those methods can only be invoked by the thread that started the execution of the task?.
I read that TBB allows job stealing, but what it steals? Does it steal a piece of data, compute it and return the result to the main thread or could it be possible for the stealing to execute the private methods?
Sorry If my question isn't clear!
Thanks.

A: TBB steals a task, i.e. an instance of a class derived from tbb::task. The method execute() of the task is then invoked. This method is executed by a single thread, but it can produce new tasks that are put into thread's local task pool, and can be stolen by other threads.
In your case, the private methods that are only called by execute() will not run concurrently.


text:
Q: I'm getting an Uncaught TypeError: Cannot read property 'ID' of null. Only when trying to access the last two items of an Object Edit
So I figured out it has something to do with the value of one of the items in the object.
Date Introduced: "2020-01-01T00:00:00.000Z" - No bueno
Date Introduced: "01/01/2020" - Muy bien
It was the only difference and works now that it has been changed. Does anyone know why this might be?
Background Info:
I have a web app with 3 buttons. Depending on the button you press it changes the status of a row with a matching ID on a google sheet. After each button click it then updates #output (just a div that I can place some text in) with the new status.
 $(function(){
      var object = randomControllerID()

      var text = 'You have controller with ID: ' + object.ID + '
Currently the status is: '+ object.Working
      $('#output').html(text)

      $('#Yes').click(function(){
      google.script.run.withSuccessHandler(onSuccess).sheetUpdate(object.rowNumber,3,this.id)
      })
      $('#No').click(function(){
      google.script.run.withSuccessHandler(onSuccess).sheetUpdate(object.rowNumber,3,this.id)
      })
      $('#Dead').click(function(){
      google.script.run.withSuccessHandler(onSuccess).sheetUpdate(object.rowNumber,3,this.id)
      })
    })
    function onSuccess(data) {
        console.log(data)
            var text = 'You have controller with ID: ' + data.ID + '
You changed the status to: '+ data.Working
            $('#output').html(text)
        }

Problem:
The google sheet update works for everything however, the onSuccess function returns null and doesn't update #output if the ID is equal to either of the last two rows on the spreadsheet. I have no idea why. The error I get when ID is equal to either of the two last items is:
Cannot read property 'ID' of null
If in the .gs I hardcode controller as either of the two last rows in the spreadsheet, data comes back as an object with ID as one of the keys. So I'm not sure why it would pass correctly for every other value except the last two rows.
function sheetUpdate(controller,column,value) {

  var ss = SpreadsheetApp.openById('X')
  var sheet = ss.getSheetByName("Controllers");
  var range = sheet.getDataRange();
  var values = range.getValues();
  values[controller][column] = value
  range.setValues(values)

  var data = getControllerData(values[controller][0])
  Logger.log(data[0])
  return data[0]
}

//pass in controller ID and get back all details as an object
function getControllerData(controllerID){
  var ss = SpreadsheetApp.openById('X')
  var sheet = ss.getSheetByName('Controllers')
  var range = sheet.getDataRange()
  var values = range.getValues()
  var obj = {}
  var result = []
  var headers = values[0]
  var cols = headers.length
  var row = []
  for (var i = 1; i < values.length; i++){
    row = values[i];
    obj = {};
    for (var col = 0; col < cols; col++){
      obj[headers[col]] = row[col];
    }
    result.push(obj);
  }

  var object = result.filter(function(item) {
  if(item.ID === controllerID) {
    return item
    }
  })

return object
}

A: Dates get converted to objects
If you have a value in a cell that is formatted as a date, getting the value from the sheet will result in a date object. Doesn't matter exactly what format it shows up in in the sheet, it will always be a date object once it gets to the Apps Script.
For example with this data:

With this script:
function dateTests() {
  file = SpreadsheetApp.getActive();
  sheet = file.getSheetByName("Sheet1");
  range = sheet.getDataRange();
  values = range.getValues();

  console.log(values[0][0])
  console.log(JSON.stringify(values[0][0]))
}

// OUTPUT

Tue May 05 2020 00:00:00 GMT+0200 (Central European Summer Time)
"2020-05-04T22:00:00.000Z"

Which is what a Date object looks like.
The advantage is that you have all the methods of the JavaScript Date object available to you.
If you don't want this to be an object then make sure to select all the column and go to Format > Number > Plain Text in the UI. Be careful though because Sheets will try to auto-detect formats, and if it recognises a date, it may convert it to that format.
To make your code really robust, you can even do something like this to check if its a date object:
if (date instanceof Date) {
  // Treat as object
} else {
  // Treat as string
}

So whether you are copying from or to your sheet, you can coerce your data into the right format for you.


text:
Q: Place longtblr caption below table By default, the longtblr environment of the tabularray has a caption argument which places the caption above the table:

\begin{table}
    \centering
    \begin{longtblr}[
        caption = {A breakable longtblr environment.}
    ]{
        colspec = {|cccc|},
        rowhead = 1,
    }
        \hline
        A & B & C & D \\
        \hline
        Value 1 & Value 2 & Value 3 & Value 4 \\
        \hline
        \pagebreak
        Value 5 & Value 6 & Value 7 & Value 8 \\
        \hline
    \end{longtblr}
\end{table}

How would one place the repeated table caption A breakable longtblr environment. below each individual table?

A: \documentclass{article}

\usepackage{tabularray}

\DefTblrTemplate{firsthead,middlehead,lasthead}{default}{
}
\DefTblrTemplate{firstfoot}{default}{
  \UseTblrTemplate{contfoot}{default}
  \UseTblrTemplate{caption}{default}
}
\DefTblrTemplate{middlefoot}{default}{
  \UseTblrTemplate{contfoot}{default}
  \UseTblrTemplate{capcont}{default}
}
\DefTblrTemplate{lastfoot}{default}{
  \UseTblrTemplate{note}{default}
  \UseTblrTemplate{remark}{default}
  \UseTblrTemplate{capcont}{default}
}

\begin{document}

    \centering
    \begin{longtblr}[
        caption = {A breakable longtblr environment.}
    ]{
        colspec = {|cccc|},
        rowhead = 1,
    }
        \hline
        A & B & C & D \\
        \hline
        Value 1 & Value 2 & Value 3 & Value 4 \\
        Value 1 & Value 2 & Value 3 & Value 4 \\
        Value 1 & Value 2 & Value 3 & Value 4 \\
        Value 1 & Value 2 & Value 3 & Value 4 \\
        Value 1 & Value 2 & Value 3 & Value 4 \\
        Value 1 & Value 2 & Value 3 & Value 4 \\
        Value 1 & Value 2 & Value 3 & Value 4 \\
        Value 1 & Value 2 & Value 3 & Value 4 \\
        Value 1 & Value 2 & Value 3 & Value 4 \\
        Value 1 & Value 2 & Value 3 & Value 4 \\
        Value 1 & Value 2 & Value 3 & Value 4 \\
        Value 1 & Value 2 & Value 3 & Value 4 \\
        Value 1 & Value 2 & Value 3 & Value 4 \\
        Value 1 & Value 2 & Value 3 & Value 4 \\
        Value 1 & Value 2 & Value 3 & Value 4 \\
        Value 1 & Value 2 & Value 3 & Value 4 \\
        Value 1 & Value 2 & Value 3 & Value 4 \\
        Value 1 & Value 2 & Value 3 & Value 4 \\
        Value 1 & Value 2 & Value 3 & Value 4 \\
        Value 1 & Value 2 & Value 3 & Value 4 \\
        Value 1 & Value 2 & Value 3 & Value 4 \\
        Value 1 & Value 2 & Value 3 & Value 4 \\
        Value 1 & Value 2 & Value 3 & Value 4 \\
        Value 1 & Value 2 & Value 3 & Value 4 \\
        Value 1 & Value 2 & Value 3 & Value 4 \\
        Value 1 & Value 2 & Value 3 & Value 4 \\
        Value 1 & Value 2 & Value 3 & Value 4 \\
        Value 1 & Value 2 & Value 3 & Value 4 \\
        Value 1 & Value 2 & Value 3 & Value 4 \\
        Value 1 & Value 2 & Value 3 & Value 4 \\
        Value 1 & Value 2 & Value 3 & Value 4 \\
        Value 1 & Value 2 & Value 3 & Value 4 \\
        Value 1 & Value 2 & Value 3 & Value 4 \\
        Value 1 & Value 2 & Value 3 & Value 4 \\
        Value 1 & Value 2 & Value 3 & Value 4 \\
        Value 1 & Value 2 & Value 3 & Value 4 \\
        Value 1 & Value 2 & Value 3 & Value 4 \\
        Value 1 & Value 2 & Value 3 & Value 4 \\
        Value 1 & Value 2 & Value 3 & Value 4 \\
        Value 1 & Value 2 & Value 3 & Value 4 \\
        Value 5 & Value 6 & Value 7 & Value 8 \\
        \hline
    \end{longtblr}

\end{document}


text:
Q: Using a local file in html for a PyQt5 webengine I am trying to embed a plotly graph into a PyQt5 webengine view. I was able to do so using the following:
open plotly in qwebview in interactive mode
If you read it, the article explains that you can't directly include the javascript in the HTML when using the webengine view (it has issues loading files above 2 MB). However, I'm trying to make it so that the source for the javascript is a local copy of plotly-min.js (saved in the project folder) so that anyone using the program doesn't need an internet connection to view the graphs it generates. I've tried to follow a few examples on html, but to no avail.
The original code that does work with an internet connection is:
raw_html = '<meta charset="utf-8" />'
raw_html += ''
raw_html += ''
raw_html += plot(fig, include_plotlyjs=False, output_type='div')
raw_html += ''

temp_view = QWebEngineView()
temp_view.setHtml(graph)

If I understand it correctly, I need to change this part:

I honestly do not know HTML. This is the only HTML in the code (the rest is in Python 3). Does anyone know why the above might not work and what I need to change? I have a suspicion I might somehow be running into the 2 MB limit the above question referenced, as different variations I've found online for how to reference a local file in HTML don't seem to change anything.

A: Many browsers for security reason disable the loading of local files, but as noted in the following forum you can enable that capability with:
sys.argv.append("--disable-web-security")

Assuming the .js is next to your .py file:
.
├── main.py
└── plotly-latest.min.js

you can use the following example:
import sys
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5.QtCore import QDir, QUrl

import plotly
import plotly.graph_objs as go

sys.argv.append("--disable-web-security")
app = QApplication(sys.argv)

x1 = [10, 3, 4, 5, 20, 4, 3]
trace1 = go.Box(x = x1)
layout = go.Layout(showlegend = True)
data = [trace1]

fig = go.Figure(data=data, layout = layout)

path = QDir.current().filePath('plotly-latest.min.js')
local = QUrl.fromLocalFile(path).toString()

raw_html = '<meta charset="utf-8" />'
raw_html += ''.format(local)
raw_html += ''
raw_html += plotly.offline.plot(fig, include_plotlyjs=False, output_type='div')
raw_html += ''

view = QWebEngineView()
view.setHtml(raw_html)
view.show()

sys.exit(app.exec_())

A: I had problems running the example of @eyllanesc under Ubuntu 16.04 / 18.04 with NVIDIA driver.
First I had to downgrade PyQt5 5.10.1 to 5.10.0 to avoid:
[0525/114545.216138:WARNING:stack_trace_posix.cc(648)] Failed to open file: /home/tmp/.gl5Qb0Tf (deleted)
  Error: Datei oder Verzeichnis nicht gefunden
Could not find QtWebEngineProcess
[3032:3032:0525/114545.495351:FATAL:zygote_host_impl_linux.cc(182)] Check failed: ReceiveFixedMessage(fds[0], kZygoteBootMessage, sizeof(kZygoteBootMessage), &boot_pid).
...

But this should be fixed for the future in PyQt5 5.11
The second problem was the linking of the shader (ubuntu 16.04):
QOpenGLShaderProgram::uniformLocation(qt_Matrix): shader program is not linked
QOpenGLShaderProgram: could not create shader program
QOpenGLShader: could not create shader
QOpenGLShader: could not create shader
shader compilation failed:

Under ubuntu 18.04 in VirtualBox:
Received signal 11 SEGV_MAPERR 000000000000
#0 0x7faa83f029a5 <unknown>
#1 0x7faa82c42501 <unknown>
#2 0x7faa83f02d3d <unknown>
#3 0x7faa9228a890 <unknown>
  r8: 0000000000000001  r9: 0000000002d5d3d0 r10: 0000000000000002 r11: 00007faa8ec4a000
 r12: 0000000002d386b0 r13: 0000000002d59b50 r14: 0000000000000000 r15: 00007faa8ed3b280
  di: 0000000000001f01  si: 00007faa8ed3d210  bp: 0000000002d52e40  bx: 0000000000000001
  dx: 0000000002e52220  ax: 0000000002e52220  cx: 0000000000000000  sp: 00007ffce38c2b78
  ip: 0000000000000000 efl: 0000000000010202 cgf: 002b000000000033 erf: 0000000000000014
 trp: 000000000000000e msk: 0000000000000000 cr2: 0000000000000000
[end of stack trace]
Calling _exit(1). Core file will not be generated.

that can be solved by following the advise of dcortesi fixing an 4 year old Ubuntu bug:
if sys.platform.startswith( 'linux' ) :
    from OpenGL import GL

Putting it all togehter:
requirements.txt
PyQt5 == 5.10.0
PyOpenGL
plotly

webview.py
import sys

if sys.platform.startswith( 'linux' ) :
    from OpenGL import GL

from PyQt5.QtWidgets import QApplication
from PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5.QtCore import QDir, QUrl

import plotly
import plotly.graph_objs as go

sys.argv.append("--disable-web-security")
app = QApplication(sys.argv)

x1 = [10, 3, 4, 5, 20, 4, 3]
trace1 = go.Box(x = x1)
layout = go.Layout(showlegend = True)
data = [trace1]

fig = go.Figure(data=data, layout = layout)

path = QDir.current().filePath('plotly-latest.min.js')
local = QUrl.fromLocalFile(path).toString()

raw_html = '<meta charset="utf-8" />'
raw_html += ''.format(local)
raw_html += ''
raw_html += plotly.offline.plot(fig, include_plotlyjs=False, output_type='div')
raw_html += ''

view = QWebEngineView()
view.setHtml(raw_html)
view.show()

sys.exit(app.exec_())

One can download the the latest plotly.js here. I used plotly.js v1.38.0 for this example.

A: In case it's helpful to anybody, I went a different direction with a solution. Instead of relying on the QWebEngineView.setHTML method, I decided to use a named temporary file to write the html to the disk, then load that into a QUrl to load into the QWebEngineView using the QUrl.fromLocalFile and QWebEngineView.setUrl methods.
Altogether I applied this into a custom PlotlyWidget class, so here's the full thing in case it's helpful to anyone.
Some special care had to be taken to ensure the temporary files get deleted when the PlotlyWiget goes out of scope and gets garbage collected (i.e. the __del__ override).
import os
import tempfile
import plotly
from PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5.QtCore import QUrl

class PlotlyWidget(QWebEngineView):

    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self.plotly_fig = None
        self.html_file = None

    def load_fig(self, plotly_fig):
        self.plotly_fig = plotly_fig
        self.plotly_fig.update_layout(font={'size':18})
        self.update_fig()

    def update_fig(self):
        html = ''
        html += plotly.offline.plot(self.plotly_fig, output_type='div', include_plotlyjs=True)
        html += ''

        if self.html_file is not None: # close previous tempfiles so that they delete from disk properly
            self.html_file.close()
            os.unlink(self.html_file.name)

        self.html_file = tempfile.NamedTemporaryFile(suffix='.html', delete=False)
        with open(self.html_file.name, 'w') as file:
            file.write(html)
        url = QUrl.fromLocalFile(self.html_file.name)
        self.setUrl(url)

    def closeEvent(self, event):
        """Delete the temp file on close event."""
        super().closeEvent(event)
        if self.html_file is not None:
            self.html_file.close()
            os.unlink(self.html_file.name)
            self.html_file = None

    def __del__(self):
        """Handle temp file close (and deletion) if QWebEngineView is garbage collected instead of closed."""
        if self.html_file is not None:
            self.html_file.close()
            os.unlink(self.html_file.name)

Typical usage is then to generate a plotly figure and then send it to the load_fig method like:
# from within QMainWindow or other QWidget instance
    fig = go.Figure()
    fig.add_scatter(y=ydata, x=xdata)

    self.ploty_widget = PlotlyWidget()
    self.ploty_widget.load_fig(fig)
    self.ploty_widget.show()


text:
Q: Should I update my program from C to modern C or C++? I have an old program written in C from the 1990's.  I would like to update it so that it will work for the next persons and on modern compilers.  Currently I am using a really old version of TurboC to make changes.  Should I be focusing on rewriting this in modern C or C++?  Which will be the easiest to bring this code up to date without having to rewrite too much and be able to reuse most of the existing code?
My programming background has mostly been in hprogramming languages like Perl, Python, PHP, Powershell, and Visual Basic, so I am not too familiar with the differences between C and C++.

A: C and C++ are different languages, not different versions of the same language. Stick to C, although you could use the fancy features of newer versions of the standard, like C99.

A: Your last sentence pretty much answers your sentiment. If you aren't familiar with the differences and you only know older languages I wouldn't update this program unless there is something horribly wrong with it that is affecting many users.
You could update it just within the C world to adhere to C99 or C11 if you have a newer compiler

A: Given:
have an old program written in C from the 1990's.
You have two questions:
Should I be focusing on rewriting this in modern C?
Maybe, maybe not.  I would try to adhere to a standard C89, C99, or C11.  This mainly depends on your tools and how much new development will happen.
Do you like declaring variables other than at the beginning of scope?  If so, then possibly update to C99.  Are you using any tools that really like C89 and show errors or warnings with C99 conventions?  If so, then stick to C89.
If the program is continually being updated and you are hiring young people, then newer conventions might be beneficial.
Should I be focusing on rewriting this in C++?
No.

A: Most well-written C programs are also valid C++ programs, or require just a little adaptation. The opposite is not true.
It's probably easier to stick with ANSI/ISO C and leave both doors open for the next maintainer.

A: It's probably about the same effort to move to a modern C compiler vs. a modern C++ compiler. The evolution of C and C++ have diverged where each has similar features but they're not source compatible.
There are a few factors that would lead me to choose to update to C++:

*

*Modern C doesn't seem to enjoy as much support as C++. For example many new things in C seem to get implemented only as required by C++, especially in the Microsoft world. VS doesn't even support C99 except for what's in C++, let alone C11.

*C++ is a better C: "C++ is "a better C" in the sense that it supports the styles of programming done using C with better type checking and more notational support (without loss of efficiency)." This is still true of modern versions of C.

*C++ adds features that support some very powerful techniques. Really making use of them may be best left to library developers, but that means C++ can support really great libraries.


text:
Q: ansible get root dir of or any other way to get parant directory i have ansible project that has this structure
./home/
/home/main.yml
/home/linux/test/foo/test.yml
/home/windows/
/home/include/utils.yml

i want to be able to include the utils.yml from each playbook that can be in every dir so i need to know the starting point and then add the include dir
now i like to use import_tasks
so i do from /home/linux/test/foo/test.yml:
- import_tasks: "{{ playbook_dir }}/include/utils.yml"
  tags: [ run_linux ]

and in utils i have :
- name: Download from linux
  get_url:
    dest: "{{ SOME_DES }}/"
    url: "{{ url}}"
  tags[ run_linux]

the problem I'm getting that I'm getting
Could not find or access '/home/linux/test/foo/include/utils.yml' on the Ansible Controller.

of course, playbook_dir give the current running dir , but how can i get the root dir ? where the
main.yml is ?


text:
Q: How to draw nodes with "stubs" in Latex? I'm trying to draw this in latex.
Anyone know how?

A: Use the calc-library and do the following:
\usetikzlibrary{calc}

\begin{document}

\begin{tikzpicture}
    \node[draw=black, circle, fill=green] (A) at (0,0) {A};
    \draw let \p1=(A) in (A) -- (\x1+40,\y1+10);
\end{tikzpicture}

\end{document}

Using the let-statement it allows you to specify a reference point (or even more) to use it's coordinates for further calculation.