text:
Q: Get renderUI to work mid way through an observeEvent I have a renderUI that I need to update mid way through an observeEvent.
Basically, When I click on the load button in the below example, firstly input$Test1 needs to update with new values, then I need the renderUI to update, then I need to update the input values in this renderUI. (This usually comes from me loading a file, but this simplified version should suffice)
I have simplified this below. Basically, I need input$DynamicTwo to be filled in on the first pass - It currently only fills in once I've clicked on input$Load twice.
library(shiny)

ui <- navbarPage(
  title = "navbar",
  id = "navbar",
  tabPanel(
    "panel1",
    selectizeInput("Test1",label="Test1: UI on panel2 depends on this",choices=c("One","Two","Three"),multiple=T,selected="One"),
    actionButton("Load","Make Test1=Two and fill in DynamicTwo with B")
  ),
  tabPanel(
    "panel2",
    uiOutput("DynamicOnTest1")
  )
)

server <- function(input, output, session) {

  output$DynamicOnTest1<- renderUI({
    lapply(input$Test1,function(x) {
      selectizeInput(paste("Dynamic",x,sep=""),paste("Dynamic",x), choices=c("A","B","C"),multiple=TRUE)
    })
  })

  observeEvent(input$Load ,{
    updateSelectizeInput(session,"Test1",selected="Two")
    #somehow I need to get the renderUI to run in here, before...
    updateSelectizeInput(session,"DynamicTwo",selected="B")
  })

}

shinyApp(ui = ui, server = server)

I've hit a mental brick wall here so any help would be greatly appreciated.

A: There are two workarounds to it, but depending on what you really plan to do with your app, they might be not suitable. But maybe that can help you go through your mental brick wall.
First solution using observe
Create an observer for your dynamic input.
  observeEvent(input$Load ,{
    updateSelectizeInput(session,"Test1",selected="Two")
  })

  observe({
    input[["DynamicTwo"]]
    updateSelectizeInput(session,"DynamicTwo",selected="B")
  })

Second solution using shinyjs::delay
Wait for DynamicOnTest1 to be rendered first, so we are sure that input[["DynamicTwo"]] exists.
ui <- navbarPage(
  title = "navbar",
  id = "navbar",
  tabPanel(
    "panel1",
    selectizeInput("Test1",label="Test1: UI on panel2 depends on this",choices=c("One","Two","Three"),multiple=T,selected="One"),
    actionButton("Load","Make Test1=Two and fill in DynamicTwo with B")
  ),
  tabPanel(
    "panel2",
    uiOutput("DynamicOnTest1")
  ),
  shinyjs::useShinyjs()
)

server <- function(input, output, session) {

  output$DynamicOnTest1<- renderUI({
    lapply(input$Test1,function(x) {
      selectizeInput(paste("Dynamic",x,sep=""),paste("Dynamic",x), choices=c("A","B","C"),multiple=TRUE)
    })
  })

  observeEvent(input$Load ,{
    updateSelectizeInput(session,"Test1",selected="Two")
    shinyjs::delay(1000, updateSelectizeInput(session,"DynamicTwo",selected="B"))
  })
}

shinyApp(ui = ui, server = server)


text:
Q: How to add OAuth2 Configuration to swagger in undertow java I am following this document, https://github.com/swagger-api/swagger-core/wiki/1.3--1.5-Migration#setting-up-additional-information-authorization-info
In this they ask to add bootstrap servlet, My problem is I am adding this bootstrap class in
My bootstrap class
@Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);

        Info info = new Info()
                .title("Swagger Petstore")
                .description("This is a sample server Petstore server.  You can find out more about Swagger " +
                        "at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/).  For this sample, " +
                        "you can use the api key `special-key` to test the authorization filters.")
                .termsOfService("http://swagger.io/terms/")
                .contact(new Contact()
                        .email("apiteam@swagger.io"))
                .license(new License()
                        .name("Apache 2.0")
                        .url("http://www.apache.org/licenses/LICENSE-2.0.html"));

        ServletContext context = config.getServletContext();
        Swagger swagger = new Swagger()
                .info(info);
        swagger.securityDefinition("testauth",
                new OAuth2Definition()
                        .implicit("http://localhost:8002/oauth/dialog")
                        .scope("email", "Access to your email address")
                        .scope("pets", "Access to your pets"));
        swagger.tag(new Tag()
                .name("pet")
                .description("Everything about your Pets")
                .externalDocs(new ExternalDocs("Find out more", "http://swagger.io")));
        swagger.tag(new Tag()
                .name("store")
                .description("Access to Petstore orders"));
        swagger.tag(new Tag()
                .name("user")
                .description("Operations about user")
                .externalDocs(new ExternalDocs("Find out more about our store", "http://swagger.io")));
        context.setAttribute("swagger", swagger);
    }

MY app.class
 @ApplicationPath("/")
    public class App extends javax.ws.rs.core.Application {

        public App() {
            this.injector = injector;
            BeanConfig beanConfig = new BeanConfig();
            beanConfig.setVersion("1.0.2");
            beanConfig.setSchemes(new String[] { "http" });
            beanConfig.setHost("localhost:7004");
            beanConfig.setBasePath("test");
            beanConfig.setResourcePackage("com.testpacakge");
            beanConfig.setScan(true);
        }

@Override
    public Set<Class<?>> getClasses() {
        Set<Class<?>> resources = new HashSet<Class<?>>();
        resources.add(Bootstrap.class);
 /// my other resorces
}

@Override
    public Set<Object> getSingletons() {
        final Set<Object> objects = new HashSet<>();

        objects.add(injector.getInstance(Bootstrap.class));
}
        }

and in Main.class
deploymentInfoObj.addServlet(Servlets.servlet("Bootstrap", Bootstrap.class)
.addMapping("/Bootstrap"));

I am adding the Bootstrap in , Application and main class.
But this setting not loaded for swagger.
Any idea to solve this?

A: After adding
.setLoadOnStartup(1)

in Servlet section, it fixed
deploymentInfoObj.addServlet(Servlets.servlet("Bootstrap", Bootstrap.class)
.addMapping("/Bootstrap").setLoadOnStartup(1));

redpajama_set_name: RedPajamaStackExchange


text:
Q: Form doesn't appear until long running method completes I have a C# windows forms application that restores a database backup. After InitializeComponent() I call a GetServers() function that runs a cmd command "sqlcmd -L" and populates a drop down. This takes around 15-20 second to execute.
So when I run the application I have to wait 15-20 seconds before the main form appears. Is there a way to open the form first, and then run the GetServers() function?
private void GetServers()
{
    System.Diagnostics.ProcessStartInfo procStartInfo =
    new System.Diagnostics.ProcessStartInfo("cmd", "/c sqlcmd -L");
    procStartInfo.RedirectStandardOutput = true;
    procStartInfo.UseShellExecute = false;
    procStartInfo.CreateNoWindow = true;

    System.Diagnostics.Process proc = new System.Diagnostics.Process();
    proc.StartInfo = procStartInfo;
    proc.Start();

    string processOutput = proc.StandardOutput.ReadToEnd();

    var lines = processOutput.Split(
    new[] { Environment.NewLine },
    StringSplitOptions.RemoveEmptyEntries);

    foreach (var line in lines)
    {
        if (!line.Trim().ToUpper().Contains("SERVERS:"))
        cbxServer.Items.Add(line.Trim());
    }

}

public Form1()
{
    InitializeComponent();
    GetServers();
}

A: You can try to run your method in Form's Shown-event. That would still make the Form unresponsive until it's done with the GetServers(). The UI is always updated after all code on the UI-thead is executed.
You should check out BackgroundWorker and asyncronous methods.

A: This is a case where you could benefit from using a BackgroundWorker.
First, modify your GetServers method so that it returns the lines collection instead of processing it. Then you can do simething like this (pseudocode and probably not complete, but you get the idea):
public Form1()
{
    InitializeComponent();

    var worker = new BackgroundWorker();
    worker.DoWork += (sender, e) => e.Result = GetServers();
    worker.RunWorkerCompleted += (sender, e) =>
        foreach (var line in (string[])e.Result) {/*Here you add the info to your form*/};

    worker.RunWorkerAsync();
}


text:
Q: How to load balance containers? How to load balance docker containers running a simple web application?
I have 3 web containers running in a single host. How do I load balance my web containers?

A: Put a load balancer, such as haproxy or nginx can even do the job.
Decent Haproxy Documentation
Nginx Howto
Either way, put the load balancer on the host or on a different server that can access the exposed ports on the containers. Nginx will probably be simpler for your needs.
To setup basic nginx load balancing:

http {
upstream myapp1 {
    server CONTAINER_APP0_IP:PORT;
    server CONTAINER_APP1_IP:PORT;
    server CONTAINER_APP2_IP:PORT;
}
server {
    listen 80;
    location / {
        proxy_pass http://myapp1;
    }
}
}


text:
Q: "href" should not empty and link should not work too Senario: I write "anchor" tag,inside it i give "href".After that requirement is that when i click on the link it should do nothing,but we cannot left empty "href" tag too.How could this possible?

A: Standard practice way of declaring empty href would be to use href="#" or  href="javascript:void(0);"
Explanation:
href="#" it's a simple and quick fix, but adds an extra entry to the browser history when clicked.
Link explicitly add a null-effect href attribute, so when clicked it doesn't have any effect and also does't mess with the browser history.

A: kindly use

This should solve your issue.
since the HREF may also be used to identify sections within a document, the HREF contains two components: the URL, which is the actual link, and the clickable text that appears on the page, called the "anchor text."
you could use

or
href="javascript:void(0);"

which essentially means that a void do nothing since evaluation of 0 using void calculates to undefined primitive value.


text:
Q: Will images look sharper on HiDPI devices if their native width is above their CSS width? The iPhone 6 has a resolution of 1334x750px but has a CSS-width of 375px.
What I want to know is if I make an image 750px wide, but set its width to 375px with CSS or HTML, will it look sharper than a native 375px image?

A: Yes, it will if the browser supports HiDPI, which is true for Safari on iOS. CSS pixels only affect CSS layout calculations; they do not affect the rendering of images.
Here's a quick demo I threw together and tested in Safari on iOS Simulator to show you what I mean. You can see that the 500x250 image appears sharper than the 250x125 image even though both are the same size in CSS pixels (with the blue div for comparison).
<!DOCTYPE html>
<meta name=viewport content="width=device-width">

250x125 CSS pixels


text:
Q: Sharing a cluster with Hadoop Is it possible to set Hadoop up so that it plays nicely with other applications on a cluster?
I'm familiar with the Torque+Maui resource scheduler, and with using HadoopOnDemand to provision temporary Hadoop clusters. But that gets pretty cumbersome if lots of people want to use Hadoop: each person has the same headache of setting up and tearing down their own mini hadoop cluster, copying data on and off thier own HDFS, etc.
It would be much cooler if we could have one permanent instance of Hadoop running that people share, with an HDFS that is always up. This would require Hadoop intelligently allocating work to nodes that aren't busy with other applications (like R, say), and not being to greedy when queueing jobs.
Is this possible?

A: Isn't this what the fair scheduler does?
http://hadoop.apache.org/mapreduce/docs/r0.21.0/fair_scheduler.html
We use this to run a permanent hadoop cluster with 30 users. You can have it preempt tasks to reallocate to new pools, and can set individual priorities for each pool too.


text:
Q: Extract sum of coefficients in a binomial expression I have two questions:
(1) Given $(1-x+x^2)^{3n}=c_0 + c_1 x + \dots +c_{6n} x^{6n}$, find $c_0+c_1+ \dots +c_n$.
I manage to find $c_0+c_1+ \dots +c_{6n}$ by putting $x=1$ but I do not know how to find the required sum up to $n$. To me, it seems that it omits terms from $n+1^{th}$ to $6n^{th}$ and thus I do not know how to find it properly.
(2) Futher given $(1+x)^{3n}=k_1 +k_1 x + \dots k_{3n} x^{3n}$, find $c_0 b_0 + c_1 b_1 +\dots c_{3n}b_{3n}$.
I have no idea on how this is related to question (1).
Thanks in advance.

A: Set $x=1/y$ in the first relation and multiply by $y^{6n}$ to get
$$(1-y+y^2)^{3n}=c_0y^{6n}+c_1y^{6n-1}+\cdots+c_{6n}$$
Set $x=y$ in the second to get $(1+y)^{3n}=k_0+k_1y+k_2y^2+\cdots+k_{3n}y^{3n}$
So, $\sum_{r=0}c_rk_r$ is the coefficient of $y^{6n}$ in
$$(1-y+y^2)^{3n}\cdot(1+y)^{3n}=\left[(1-y+y^2)(1+y)\right]^{3n}=(1+y^3)^{3n}$$
Now the $r$th term of $(1+y^3)^{3n}$ is $$\binom{3n}r(y^3)^r=\binom{3n}ry^{3r}$$
So, we need $3r=6n\iff r=?$


text:
Q: oledb excel some date-columns return null I am reading a xlsx-file via oledb. There are some rows where a column (containing a date-string) returns null and some rows where the column (also containing a date-string) returns the date-string. In excel the column-type is set to "date".
Here is my connection-string:

$"Provider=Microsoft.ACE.OLEDB.12.0;Data
  Source={PATH_TO_FILE};Extended Properties=\"Excel 12.0
  Xml;HDR=NO\""

Here is the command-text to query the data:

$"SELECT * FROM [SHEET_NAME$A4:BC] WHERE
  F1 IS NOT NULL"

Here is how i read the data from the data-record:
var test = dataRecord.GetValue(dataRecord.GetOrdinal("F39"));

Her are some examples what the inspector shows me when test contains the date-string:
{07.01.1975 00:00:00}
{03.08.1987 00:00:00}
{03.10.1988 00:00:00}
{01.05.1969 00:00:00}
{20.12.2016 00:00:00}
{18.07.2011 00:00:00}

In other cases the inspector only show:
{}

Here is a screenshot from the xlsx-document where i have marked a line in red where the return-value is empty and green where the actual date-string is returned:

The date-strings are formatted like dd.mm.yyyy
Why do these rows return an empty value instead of the date-string?

As suggested by AndyG i have checked if the date-string values might fail in dependece of the format ("dd.mm.yyyy" vs. "mm.dd.yyyy"). But there are cases which are invalid for "mm.dd.yyyy" that dont fail.

A: I was not able to solve the problem, but was able to bypass it, by changing the column-type in Excel to text.
I had to copy the whole xls-file, delete the content of the copy, set the column-type to text, copy the content from the first file and paste it into the second file. Otherwise Excel was changing the date-strings to the numbers which are used to store the date.
Now I can read the cells correctly.

A: Two years too late but after struggling with this for the better part of several hours I hope this might help someone:
It sounds likely the first row in your excel document contains column names and not actual data, which means they are of a different Excel data type (General/Text + DateTime).
The fix to handle is pretty simple - adjust your connection string to reflect this using the HDR property in Extended Properties:
$"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={PATH_TO_FILE};Extended Properties=\"Excel 12.0 Xml;HDR=YES\""

HDR = true means the first row contains field names
You can read more about it here:
https://www.connectionstrings.com/ace-oledb-12-0/
Additionally, if you are encountering this on odd lines in your document like OP, ensure that the data type is identical for the entire column, except your column titles if using HDR=true
Excel can sometimes flip DateTime fields to General fields which would cause this behavior


text:
Q: 500 Error using value in HTML and calling JSP/Java Hey in the following code I have some error but don't know what it's causing. I made a drop down menu to select an option in the HTML. The content and the value of the option of the select block should be different. And currently I'm getting a 500 error .
When the content and the value is just "resultset.getInt(4)" the program works and the operation to the database is execute.
That's my HTML file:
<%@page import="javax.sql.DataSource"%>
<%@page import="javax.naming.Context"%>
<%@page import="javax.naming.InitialContext"%>
<%@page import="java.sql.Connection"%>
<%@page import="java.sql.PreparedStatement"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.SQLException"%>
<%@page import="java.sql.Date"%>
<%@page import="java.sql.*"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>

<meta charset="ISO-8859-1">
<title>Allocation Paket</title>

    <form action="paket_update.jsp" method="post">

        <%ResultSet resultset =null;
          ResultSet resultset1 =null;%>
                <%
                Context initContext = new InitialContext();
                DataSource ds = (DataSource) initContext.lookup("java:/comp/env/jdbc/myoracle");
                try(Connection con= ds.getConnection()){
                    con.setAutoCommit(false);

                    Statement statement = con.createStatement() ;
                    Statement statement1 = con.createStatement() ;

                    resultset =statement.executeQuery("SELECT m.vorname, m.nachname, m.angestelltennummer, b.svnr FROM bote b JOIN mitarbeiter m ON m.svnr = b.svnr") ;
                    resultset1 =statement1.executeQuery("SELECT paketnummer FROM paket") ;

                %>
                Bote:

                    <select name="bote">
                    <%  while(resultset.next()){ %>
                    <option value="<% resultset.getInt(4);%>"><%= resultset.getString(1)+", "+resultset.getString(2)+", " + resultset.getInt(3) %></option>

                     <% } %>
                    </select>

                Paket:

                    <select name="paket">
                    <%  while(resultset1.next()){ %>
                    <option ><%= resultset1.getInt(1) %></option>
                     <% } %>
                    </select>

                                <%
                    }catch(Exception e)
                    {
                         out.println("wrong entry"+e);
                    }
                %>

        <input type="submit" value="Insert"/>
    </form>

    Zur Startseite

That's my jsp file (update paket):
<%@page import="javax.sql.DataSource"%>
<%@page import="javax.naming.Context"%>
<%@page import="javax.naming.InitialContext"%>
<%@page import="java.sql.Connection"%>
<%@page import="java.sql.PreparedStatement"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.SQLException"%>
<%@page import="java.sql.Date"%>
<%@page import="java.sql.*"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>

<meta charset="ISO-8859-1">
<title>Update Paket</title>

    <%
    Context initContext = new InitialContext();
    DataSource ds = (DataSource) initContext.lookup("java:/comp/env/jdbc/myoracle");
    String s="Der Bote wurde erfolgreich zugewiesen!";
    try(Connection con= ds.getConnection()){
        con.setAutoCommit(false);
        String query = "UPDATE paket SET BOTE = ? WHERE PAKETNUMMER=?";

        try(PreparedStatement stmt = con.prepareStatement(query)){
            int svnr = Integer.parseInt(request.getParameter("bote"));
            int paketnummer =  Integer.parseInt(request.getParameter("paket"));

            stmt.setInt(1,svnr);
            stmt.setInt(2,paketnummer);

            stmt.execute();

            con.commit();

        } catch (SQLException ex) {
            out.println("Fehler: " + ex.getMessage() + " (" + ex.getSQLState() + ')');
            s="Der Bote wurde nicht zugewiesen";
            try {
                con.rollback();
            } catch (SQLException ignore) {
                out.println("Rollback nicht erfolgreich! Fehler: " + ignore.getMessage() + " ("
                        + ignore.getSQLState() + ')');
            }
        }

    }catch (SQLException ex) {
        out.println("Fehler: " + ex.getMessage() + " (" + ex.getSQLState() + ')');
    }
    out.println(s);
    %>

    Zur Startseite

I hope you can help me^^

A: I suppose this line is wrong, because of a missing = character at the beginning of
"<% resultset.getInt(4);%>":
<option value="<% resultset.getInt(4);%>"><%= resultset.getString(1)+", "+resultset.getString(2)+", " + resultset.getInt(3) %></option>

Because of that nothing is written to out, and all generated option tags have value="". Should be, in my opinion:
<option value="<%= resultset.getInt(4);%>"><%= resultset.getString(1)+", "+resultset.getString(2)+", " + resultset.getInt(3) %></option>


text:
Q: Python turtle UnboundLocalError I keep getting a UnboundLocalError when I try assigning turtle to turtle.Turtle() in a function. Why is it? Is the name used in turtle.py?
import turtle
def make_turtle():
    turtle = turtle.Turtle()
    return turtle

eu = make_turtle()

Traceback (most recent call last):
  File "/home/usr/PycharmProjects/LearningToThinkLikeAComputerScientist/c4 - Functions/test.py", line 6, in <module>
    eu = make_turtle()
  File "/home/luis/PycharmProjects/LearningToThinkLikeAComputerScientist/c4 - Functions/test.py", line 3, in make_turtle
    turtle = turtle.Turtle()
UnboundLocalError: local variable 'turtle' referenced before assignment

A: In the import statement you assign the name turtle.
Then you assign to it in the function. If I have understood this correctly, the python parser first esttablishes thet the name turtle is assigned which makes it local. Then it processes the line turtle = turtle.Turtle() fron right to left. On discovering that you try to retrieve the value pointed to by turtle it is not assigned, you get an error.
Instead try another name:
import turtle

def make_turtle():
    cat = turtle.Turtle()
    return cat

eu = make_turtle()


text:
Q: Can not access object in laravel and has "0" indexes when appliying toArray() I have these tables
clientes

id
  nombre_rz
  ced_rif
  telefono
  id_usuario

solicitantes

id
  nombre
  email
  telefono
  id_cliente

cliente->hasMany('solicitante')

solicitante->belongsTo('cliente')

^ This is well written in the models, just trying not to make a wall of text.
After Authenticating, when i do
$cliente = Cliente::where('usuario_id','=',Auth::id())->with('solicitante')->get();
                    dd($cliente);

or
$cliente = Cliente::where('usuario_id','=',Auth::id())->with(array('solicitante' => function($query)
            {
                $query->where('cliente_id', '=', '35');

            }))->get();
            dd($cliente);

i get this obect
Object from query
And using toArray() i get this
Array from object
And if access index 0 of that array like
$array = $cliente->toArray(); dd($array['0']);

i get
[Index 0 of array][3]
As far as i can see the queries are correct, and the data i need is there, but i don't know why i can't access the object like
$cliente->id; $cliente->telefono, $cliente->solicitante->nombre, $cliente->solicitante->email

It always throws

Undefined property: Illuminate\Database\Eloquent\Collection::$telefono

Can't Understand this behavior.

A: You are returning an array of objects, because you asked Laravel for a group. You can either do
foreach ($cliente as $client)
{
     echo $client->telefono;
     foreach ($client->solicitante as $solicitante)
     {
         $solicitante->nombre;
     }
}

OR you can specify that you only want one result
$cliente = Cliente::where('usuario_id','=',Auth::id())->with('solicitante')->first();
echo $cliente->telefono;
foreach ($client->solicitante as $solicitante)
{
    $solicitante->nombre;
}


text:
Q: A question on direct product of groups A is a finite Abelian group and p is a prime.
  A^p = {a^p ; a is in A} and

  A_p = {a ; a^p =1}

Now it is clear that A/A_p is isomorphic to A^p. But how to prove that A/A^p is isomorphic to A_p?  Clearly they have same order and it is told to show that both of them are elementary abelian. But how?

A: They aren't isomorphic in general if $A$ is infinite. For finite Abelian groups, you can express the group as a direct sum of cyclic groups.
As $A\mapsto A^p$ and $A\mapsto A_p$ are preserved under direct sums, then
all you have to do is to prove the result for finite cyclic groups.


text:
Q: MySQL Connection not available in Flask python I am new to flask.
Flask server give MY SQL Connection not available whenever I call two many API request at a  same time and my server get crash
I do not know my its happening. I also increase connect_timeout to 600 but it still gives the same error.
MySQL timeout Variables are:
SHOW VARIABLES LIKE "%timeout"; SS
This only happened when i call many API request at a same time
Error:
Error given my Flask server SS
My API code.
This API running a Imageproccesing Modal at visualizer.image_processing
and enter detect faces id into MYSQL database
@attendance.route('/groups/mark_attendence', methods=['POST', 'GET'],)
def mark_attendence():
    now = datetime.datetime.now()
    image_b64 = request.get_json()['im']
    group_id = request.get_json()['gid']
    foldername = request.get_json()['folder_name']
    session_id = request.get_json()['sessionid']
    data = urllib.parse.unquote(image_b64)
    data = data.split(',')[1]
    imgdata = base64.b64decode(data)
    filename ="imageToSave" + str(group_id) + ".jpg"
    with open(filename, 'wb') as f:
        f.write(imgdata)
    img = cv2.imread(filename)
    args = Args(folderName=foldername)
    visualizer = Visualizer(args)
    array_findFaces = visualizer.image_processing(img)
    cursor1 = mysql.cursor()
    try:
        if len(array_findFaces) > 0:
                for i in array_findFaces:
                    if(i['text'] != 'Unknown'):
                        cursor1.execute(
                            "UPDATE  usersdb.sessions  SET status = 1 WHERE status = 0 and  sessionid = '"+ str(session_id) +"' and uid = '"+ str(student[1]) +"' ; ")
        else:
            print("----------------No face detected----------------")
    except Exception as e :
        print("exception in mark attendance")
        print(e)
    mysql.commit()
    cursor1.close()
    cursor2 = mysql.cursor()
    cursor2.execute("select name, pic,status,usersdb.sessions.updated_at,uid,email from usersdb.user join usersdb.sessions on usersdb.user.id = usersdb.sessions.uid  where  usersdb.sessions.sessionid = '" + str(session_id) + "'")
    data = cursor2.fetchall()
    cursor2.close()
    then = datetime.datetime.now()
    print("time taken to mark attendence")
    print(then - now)
    finaljson = json.dumps({'Faces': array_findFaces,"Attendance":"nothing"},indent=4, sort_keys=True, default=str)
    return finaljson

I connect my Flask server to MYSQL using a package called my mysql.connector
import mysql.connector

try:
   mysql = mysql.connector.connect(
   host="localhost",
   user="root",
   passwd="******",
   database="usersdb")
except:
   print("Error connecting to database")

and imported my mysql connection like that
import json
from config.db_connect import mysql // imported mysql connection
from sqlite3 import Date
import jsonpickle
from json import JSONEncoder
import flask
import os
import datetime
import numpy as np
from flask import Blueprint,request
from face_2 import Visualizer
import io
import cv2, os, base64, uuid, shutil
import urllib.parse
from PIL import Image

At the Sametime i also call another API parallel to first API
@attendance.route('/groups/markbyuid', methods=['POST'])
def mark_by_uid():
    uid = request.get_json()['uid']
    status = request.get_json()['status']
    sessionId = request.get_json()['sessionId']
    try:

        cursor = mysql.cursor()
        cursor.execute(" update usersdb.sessions set status = '" +str( status) + "' where uid = '" + str(uid) + "' and sessionid = '" + str(sessionId) + "' ")
        mysql.commit()
        cursor.close()
    except Exception as e:
        print('exception is here ')
        print(e)
    return flask.jsonify({'data': 'success'})

So both two api called at a same time
Moreover sometime give MySQL Connection not available. Segmentation Fault. Segmentation Fault Error SS and my server stopped
Why my server stopped and gives error when two API's called at same Time? I checked my API's routes many time it looks fine. Reminder both API's Update the same database table


text:
Q: Can "night mode" or Flux be used in an RDP session The bright white light from my work machine hurts my eyes. I'm trying to use "Night Mode" in Windows 10, or Flux. However, neither of them work, I assume because I'm in an RDP session? Is there a workaround for this?

A: You can't use any display correction inside the RDP session itself, Most of the regular display properties are locked out as you're only viewing remotely.
The simplest method would be to apply any screen correction to your local machine, which would then also affect the displayed remote image.


text:
Q: Guides, tutorials for beginner iOS Game development iPhone/iPad? Am in iOS development. Currently am working for commercial iOS apps for iPhone and iPad. Now, i want to develop game apps for iPhone. But, i just struggling where i need to start with? And what are the skills i need to have for game development? Could you please suggest me any your great ideas on this?

A: You can check out cocos2d, it's a nice free open-source framework for game development that has plenty of tutorials (e.g. here) and books written about. I've used it for some time now and I'm very satisfied with it.

A: This site has many game development tutorials for beginners.


text:
Q: Salesforce - Sync with a public calendar via Salesforce Outlook Connector I have Exchange 2010 and Outlook 2010.  I am trying to sync a public Outlook calendar with Salesforce using the Salesforce.  According to Idea Exchange (here and here), it's not possible (although the second link does contain a workaround that uses a Salesforce license).  When I install the Salesforce Outlook Connector and select the calendar to sync with, I only see my personal calendar under my email address, not any public calendars.  If I select a "New" and navigate to the public calendar and try to create a sub-folder, I get a message saying "Could not create new folder: MAPI_E_NO_ACCESS"
How can I sync this public folder? If this would show under my email address, I could just select it.  Is there a way to get this to work?

A: While it isn't an immediate solution you could vote up the ideas:
IdeaExchange: make Public Calendar events first-class citizens
IdeaExchange: Salesforce for Outlook: Enable synching to public folder
API access to public calendars should make this possible.


text:
Q: How to use WordPress as home page in Magento I'm trying to set up WordPress one page website as home page in Magento. So basically what I would like to create is WordPress split screen website and after you click on section, this will display already built Magento website.
Is anything like that possible to do? If so, can anyone recommend me how to approach this?
Thank you in advance for all replies!


text:
Q: Weblogic deployement IE8 emulation is it possible to customize a Weblogic Domain in order to force every web application deployed on it to emulate IE8?
Thanks so much,
Daniele

A: It is not possible to do that in the content server, but it is possible in the web server: link


text:
Q: Neo4j Unmanaged Extension Spring context does not load I am attempting to stand up an unmanaged extension with a spring context.  I have been trying to follow these resources:
https://groups.google.com/forum/#!topic/neo4j/AZUVcFxvI_k
https://github.com/spring-projects/spring-data-neo4j/tree/master/spring-data-neo4j-rest
https://inserpio.wordpress.com/2014/04/30/extending-the-neo4j-server-with-spring-data-neo4j/
http://docs.spring.io/spring-data/data-graph/snapshot-site/reference/html/#d5e1991
I have been unable to inject a service from the spring context using the @Context annotation.  I cannot see what I am missing.
I have uploaded my project: here
I have this line of configuration in conf/neo4j-server.properties
org.neo4j.server.thirdparty_jaxrs_classes=test.testload=/loader

This is the error from the log file:
Feb 05, 2015 3:50:10 PM com.sun.jersey.server.impl.application.WebApplicationImpl _initiate
INFO: Initiating Jersey application, version 'Jersey: 1.9 09/02/2011 11:17 AM'
Feb 05, 2015 3:50:11 PM com.sun.jersey.server.impl.application.WebApplicationImpl _initiate
INFO: Initiating Jersey application, version 'Jersey: 1.9 09/02/2011 11:17 AM'
Feb 05, 2015 3:50:11 PM com.sun.jersey.api.core.PackagesResourceConfig init
INFO: Scanning for root resource and provider classes in the packages:
test.testload
Feb 05, 2015 3:50:11 PM com.sun.jersey.api.core.ScanningResourceConfig logClasses
INFO: Root resource classes found:
class test.testload.HelloWorldResource
Feb 05, 2015 3:50:11 PM com.sun.jersey.api.core.ScanningResourceConfig init
INFO: No provider classes found.
Feb 05, 2015 3:50:11 PM com.sun.jersey.server.impl.application.WebApplicationImpl _initiate
INFO: Initiating Jersey application, version 'Jersey: 1.9 09/02/2011 11:17 AM'
Feb 05, 2015 3:50:11 PM com.sun.jersey.spi.inject.Errors processErrorMessages
SEVERE: The following errors and warnings have been detected with resource and/or provider classes:
SEVERE: Missing dependency for constructor public test.testload.HelloWorldResource(org.neo4j.graphdb.GraphDatabaseService,test.testload.service.TestService) at parameter index 1

What am I missing that will allow me to access the spring context? Why is the Plugin Lifecycle class called out in: META-INF/services/org.neo4j.server.plugins.PluginLifecycle being ignored?

A: AFAIK the implementations if PluginLifecycle are not detected via serviceloader, so get rid of META-INF/services/org.neo4j.server.plugins.PluginLifecycle.
Instead move your PluginLivecycle implementation (ImportConfig) to a package being exposed in config org.neo4j.server.thirdparty_jaxrs_classes - in your case test.testload instead of test.testload.config.


text:
Q: Issue with installing factory_girl_rails gem I'm following a TDD tutorial by Thoughtbot, and it is great but a little bit out of date. Everything worked fine until I tried to install the factory_girl_rails v 4.0 gem and run bundle, as instructed. Factory Girl is currently at v. 4.4.0 but the workshop is specific so I am trying to keep with the versions they use when possible.
Bundler said:
Gem::RemoteFetcher::FetchError: Errno::ECONNRESET: Connection reset by peer - SSL_connect (link omitted b/c SO won't let me post it)
An error occurred while installing factory_girl (4.4.0), and Bundler cannot continue.
Make sure that `gem install factory_girl -v '4.4.0'` succeeds before bundling.

So I did this:
gem install factory_girl_rails
ERROR:  Could not find a valid gem 'factory_girl_rails' (>= 0), here is why:
      Unable to download data from (link omitted b/c SO won't let me post it/) - Errno::ECONNRESET: Connection reset by peer - SSL_connect (link omitted b/c SO won't let me post it)
ERROR:  Possible alternatives: factory_girl_rails

Tried to figure out if this was maybe just something to do with my connection. Took out the line from my gemfile & ran bundle, all fine.
After searching around discovered maybe the problem was that my version of Ruby was 1.9.3, so I updated to 2.1.2 using RVM.
Now when I run bundle I get this:
Gem::RemoteFetcher::FetchError: Errno::ECONNRESET: Connection reset by peer - SSL_connect (https://rubygems.org/gems/rake-10.3.2.gem)
An error occurred while installing rake (10.3.2), and Bundler cannot continue.
Make sure that `gem install rake -v '10.3.2'` succeeds before bundling.

So I tried:
gem install rake -v '10.3.2'
ERROR:  Could not find a valid gem 'rake' (= 10.3.2), here is why:
      Unable to download data from https://rubygems.org/ - Errno::ECONNRESET: Connection reset by peer - SSL_connect
ERROR:  Possible alternatives: rake

same error with gem install rake
Here's my rake version:
rake --version
rake, version 10.1.0

I feel like I'm heading into the mire here and worry that I will end up making things worse if I continue to monkey around! It seems like I should back up to Ruby v. 1.9.3, but if I run
rvm --default use ruby-1.9
ruby-1.9.3-p547 is not installed.

To install do: rvm install ruby-1.9.3-p547
It seems like a bad idea to go backwards.

A: It seems like there might be an ssl problem somewhere. I'd try running rvm osx-ssl-certs update all in your terminal, and trying again.


text:
Q: not capturing escape characters in renderPrint of R Shiny In my R Shiny app, I would like to properly display text that contains escape characters (e.g. \n \t ...)
in my ui.R:
textOutput('textDisplay')

in my server.R:
output$textDisplay <- renderPrint({cat('line1\nline2')})

But the Shiny just displays 'line1 line2'
Normally, cat('line1\nline2') would correctly treat \n as a newline. Can someone help?

A: renderPrint is more fun in a way, as it will output HTML just as it is written. So your server.R should read:
output$textDisplay <- renderPrint({cat('line1<br/>line2')})

to do what you expect it to do.


text:
Q: Как взять несколько строк из текста между символами возврата каретки? Есть текст:
"Привет\n\nМне нужно взять эту часть текста.\n\n Бла-бла\nБла-бла\Бла-бла."

Нужно взять часть текста(несколько предложений), которые находятся между символами "\n\n". Реально ли это сделать? Ну или хотя бы до символа "\n\n".

A: public static void main(String[] args)
{
String text = "Привет\n\nМне нужно взять эту часть текста.\n\n Бла-бла\nБла-бла\nБла-бла.";
String[] result = text.split("\n\n");
//Вывод отдельных предложений
for(int i = 0;i < result.length;i++)
{
  System.out.println(result[i]);
}

}

A: Так?
 String string = "Привет\n\nМне нужно взять эту часть текста.\n\n Бла-бла\nБла-бла\nБла-бла.";
 String []splitArray = string.split("\n\n");

Дополнено
Нужная строка будет вторым элементом в массиве.

A: В случае, если нужно найти все варианты строк между \n\n, можно использовать такой вариант:
String s = "Привет\n\nМне нужно взять эту часть текста.\n\nБла-бла\nБла-бла\n\nБла-бла.";
Pattern p = Pattern.compile("\n\n([\\s\\S]+?)\n\n");
Matcher m = p.matcher(s);
int i = 0;
while (m.find(i)) {
    System.out.println("'" + m.group(1) + "'");
    i = m.start(1);
}

Результат:
'Мне нужно взять эту часть текста.'
'Бла-бла
Бла-бла'

Если нужно первое вхождение - можно заменить цикл на простое условие:
if (m.find()) {
    System.out.println(m.group(1));
}

Если между \n\n не может быть других переносов строк, то логично упростить регулярное выражение и использовать \n\n(.+)\n\n.

A: public String findSubstring (String text, char firstSearchSymbol, char secondSearchSymbol) {
    try{
       return text.substring(text.indexOf(firstSearchSymbol)+1, text.indexOf(secondSearchSymbol));
    }
    catch (StringIndexOutOfBoundsException e) {
        return text;
    }
}


text:
Q: How to set CCSID for MQQueueManager from code? I have some strange problem. I think I followed documentation correctly but my code doesn't work. I have this very simple hard coded test (NUnit):
[TestFixture]
public class MQQueueTests {

    public const string MessageContent = "<test>This is test message</test>";

    public static void Main(string[] args) {
        var tests = new MQQueueTests();
        tests.PutAndGetMessage();
    }

    [Test]
    public void PutAndGetMessage() {
        var properties = new Hashtable
                             {
                                 {MQC.HOST_NAME_PROPERTY, "TestServer"},
                                 {MQC.CHANNEL_PROPERTY, "Test.Channel"},
                                 {MQC.PORT_PROPERTY, 1415},
                                 // Is this correct? It looks like it is not
                                 // enough because adding this line didn't solve
                                 // the problem.
                                 {MQC.CCSID_PROPERTY, 437}
                             };

        using (var manager = new MQQueueManager("Test.Queue.Manager", properties)) {
            using (MQQueue queue = manager.AccessQueue("Test.Queue",
                MQC.MQOO_OUTPUT | MQC.MQOO_INPUT_AS_Q_DEF)) {

                MQMessage message = new MQMessage();
                message.WriteUTF(MessageContent);
                queue.Put(message);

                MQMessage readMessage = new MQMessage();
                queue.Get(readMessage);

                Assert.AreEqual(MessageContent, readMessage.ReadUTF());

                queue.Close();
            }
            manager.Disconnect();
        }
    }
}

I'm running the test application either from console or through Resharper 6 test runner. If I run the application in test runner I always get following exception:

IBM.WMQ.MQException : MQRC_CHANNEL_CONFIG_ERROR (reason code is 2539)

The exception is thrown by MQQueueManager.Connect (called by its constructor).
If I check MQ logs I see:

AMQ9541: CCSID supplied for data conversion not supported.
EXPLANATION: The program ended because, either the source CCSID '437'
  or the target CCSID '852' is not valid, or is not currently supported.
ACTION: Correct the CCSID that is not valid, or ensure that the
  requested CCSID can be supported.

If I run the application from the console I got the same error but if I change the code page for console by calling
chcp 437

My test application works. How can I configure code page from code?

A: Well I found a workaround - it can probably solve my problem but I'm not very satisfied with it. I can set up MQCCSID environment variable either globally or by calling:
Environment.SetEnvironmentVariable("MQCCSID", "437");

That will configure code page. Still I would like to use properties of a new MQQueueManager instance to setup code page.

A: Both of these are answers correct. For Windows Forms Project setting the environment variable MQCCSID the same as the ccsid of the Queue Manager that you are trying to connect will be enough.
- the 2nd  solution

HKEY_LOCAL_MACHINE->SYSTEM->CurrentControlSet->Control->Nls->CodePage>OEMCP value.

i had a web application(web forms) that only worked with the 2nd solution

A: change your system locale to English(United States), on windows 7 Regional Settings -> Administrative->Change System locale. also after do that you can check it in regedit value.
regedit->HKEY_LOCAL_MACHINE->SYSTEM->CurrentControlSet->Control->Nls->CodePage  check OEMCP value.


text:
Q: Scale tikz arrow length relative to its starting point How can I scale an arrow so that the scaling is based on its starting point? In my example you see my problem. The black arrow should be scaled down by fifty percent to give the red arrow (as if (0,2) would be the origin). Instead I get the blue arrows, because scaling simply multiplies all the coordinate entries. I tried two methods with the same unwanted behavior. Do you know a simple way to get what I intended? Thanks!
\documentclass{article}
\usepackage{tikz}
\begin{document}

\begin{tikzpicture}
\draw [thin,gray!40,step=1] (0,0) grid (4,4);
\node at (-.3,-.3){(0,0)};
\draw [->, very thick] (0,2) -- (4,4);
\draw [->, thick, red] (0,2) -- (2,3);
\draw [->, thick, blue, scale=.5] (0,2) -- (4,4);
\begin{scope}[scale=.25]
\draw [->, thick, blue] (0,2) -- (4,4);
\end{scope}
\end{tikzpicture}

\end{document}

A: If I understand you correctly, you want to scale the length of the arrow down. This suggests to

*

*switch to relative coordinates, i.e. to replace (0,2) -- (4,4) by (0,2) -- ++ (4,2), and then to

*just scale the ++ piece, e.g. (0,2) -- ++ ([scale=0.5]4,2).

\documentclass{article}
\usepackage{tikz}
\begin{document}

\begin{tikzpicture}
\draw [thin,gray!40,step=1] (0,0) grid (4,4);
\node at (-.3,-.3){(0,0)};
\draw [->, very thick] (0,2) -- (4,4);
\draw [->, thick, red] (0,2) -- (2,3);
\draw [->, thick, blue] (0,2) -- ++ ([scale=.5]4,2);
\draw [->, thick, purple] (0,2) -- ++ ([scale=.25]4,2);
\end{tikzpicture}

\end{document}


text:
Q: BaseAdapter causing ListView to go out of order when scrolled I'm having problems with some BaseAdapter code that I adapted from a book. I've been using variations of this code all over the place in my application, but only just realized when scrolling a long list the items in the ListView become jumbled and not all of the elements are displayed.
It's very hard to describe the exact behavior, but it's easy to see if you take a sorted list of 50 items and start scrolling up and down.
class ContactAdapter extends BaseAdapter {

    ArrayList<Contact> mContacts;

    public ContactAdapter(ArrayList<Contact> contacts) {
        mContacts = contacts;
    }

    @Override
    public int getCount() {
        return mContacts.size();
    }

    @Override
    public Object getItem(int position) {
        return mContacts.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view;
        if(convertView == null){
            LayoutInflater li = getLayoutInflater();
            view = li.inflate(R.layout.groups_item, null);
            TextView label = (TextView)view.findViewById(R.id.groups_item_title);
            label.setText(mContacts.get(position).getName());
            label = (TextView)view.findViewById(R.id.groups_item_subtitle);
            label.setText(mContacts.get(position).getNumber());
        }
        else
        {
            view = convertView;
        }
        return view;
    }

}

A: To further clarify the answer of CommonsWare, here is some more info:
The li.inflate operation (needed here for parsing of the layout of a row from XML and creating the appropriate View object) is wrapped by an if (convertView == null) statement for efficiency, so the inflation of the same object will not happen again and again every time it pops into view.
HOWEVER, the other parts of the getView method are used to set other parameters and therefore should NOT be included within the if (convertView == null){ }... else{ } statement.
In many common implementation of this method, some textView label, ImageView or ImageButton elements need to be populated by values from the list[position], using findViewById and after that .setText or .setImageBitmap operations.
These operations must come after both creating a view from scratch by inflation and getting an existing view if not null (e.g. on a refresh).
Another good example where this solution is applied for a ListView ArrayAdapter appears in https://stackoverflow.com/a/3874639/978329

A: You are only putting data in the TextView widgets when they are first created. You need to move these four lines:
        TextView label = (TextView)view.findViewById(R.id.groups_item_title);
        label.setText(mContacts.get(position).getName());
        label = (TextView)view.findViewById(R.id.groups_item_subtitle);
        label.setText(mContacts.get(position).getNumber());

to be after the if/else block and before the method return, so you update the TextView widgets whether you are recycling the row or creating a fresh one.


text:
Q: Integrating over this region? I need to find the volume of the region bounded by $z=4-x^2, x+y=2$, and the coordinate planes.
I know I use and triple integral, and integrate one, but I can't figure out the limits on $y$. I know that $0\leq z \leq 4-x^2$, and $0 \leq x \leq 2$, but what y's limits?


text:
Q: Swift String contain , or . but not both I want to write the following in a more elegant way:
let number = "1,2922.3"

if number.contains(",") || number.contains(".") && !(number.contains(".") && number.contains(",")) {
    // proceed
}

That is, I want to proceed if the number has "." or ",", but not them both.
There has to be a better way?
I don't want to use an extension, as this is in a single place in my code.

A: You can use SetAlgebra:
func validate(_ string: String) -> Bool {
    let allowed = Set(",.")
    return !allowed.isDisjoint(with: string) && !allowed.isSubset(of: string)
}

validate("1,2922.3") // false
validate("1,29223") // true
validate("12922.3") // true
validate("129223") // false

To explain a bit:

*

*!allowed.isDisjoint(with: string) because you want to exclude strings that contain neither . and ,.

*!allowed.isSubset(of: string) because you want to exclude strings that contain both . and ,.


text:
Q: How to read custom multiline log using Spark I'm trying to parse custom log files using the regex patterns with spark:
My log file:
2018-04-11 06:27:36 localhost debug: localhost received discover from 0.0.0.0
2018-04-11 06:27:36 localhost debug:     sec = 0.4
2018-04-11 06:27:36 localhost debug:     Msg-Type = text
2018-04-11 06:27:36 localhost debug:     Content = XXXXXXXXXX
2018-04-11 06:27:34 localhost debug: localhost sending response to 0.0.0.0
2018-04-11 06:27:34 localhost debug:     sec = 0.3
2018-04-11 06:27:34 localhost debug:     Msg-Type = text
2018-04-11 06:27:34 localhost debug:     Content = XXXXXXXXXX
...

Here's a snippet of my code:
case class Rlog(dateTime: String, server_name: String, log_type: String, server_addr:String, action: String, target_addr:String, cost:String, msg_type:String, content:String)
case class Slog(dateTime: String, server_name: String, log_type: String, server_addr:String, action: String, target_addr:String, msg_type:String, content:String)

val pattern_1 = """([\w|\s|\:|-]{19})\s([a-z]+)\s(\w+):\s(\w+)\sreceived\s(\w+)\sfrom\s([\.|\w]+)"""
val pattern_2 = """([\w|\s|\:|-]{19})\s([a-z]+)\s(\w+):\s{5}([\w|-]+)\s=\s([\.|\w]+)"""
val pattern_3 = """([\w|\s|\:|-]{19})\s([a-z]+)\s(\w+):\s(\w+)\ssending\s(\w+)\sto\s([\.|\w]+)"""

sc.textFile("/directory/logfile").map(?????)

Is there any way to do that?

A: You can use pattern.unapplySeq(string) inside the map to get a List of all the group matches with the regex.
For example, if you have the string:
val str = "2018-04-11 06:27:36 localhost debug: localhost received discover from 0.0.0.0"

and you run:
pattern_1.unapplySeq(str)

You will get:
 Option[List[String]] = Some(List(2018-04-11 06:27:36, localhost, debug, localhost, discover, 0.0.0.0))

I have used your example for this solution. This answer assumes that a certain log-type and the msg-type, content and seconds associated with it will all be printed with the same timestamp.
// case class defintions here
// regex pattern_1, pattern_2, pattern_3 defined here

val rdd = sc.textFile("file").cache

// Filter in 3 rdds based on the pattern that gets matched
val receivedRdd = rdd.filter(_.matches(pattern_1.toString)).map(pattern_1.unapplySeq(_).get)
val sentRdd = rdd.filter(_.matches(pattern_3.toString)).map(pattern_3.unapplySeq(_).get)
val otherRdd = rdd.filter(_.matches(pattern_2.toString)).map(pattern_2.unapplySeq(_).get)

// Convert it to a dataframe
// Names are matching with case class Rlog and Slog
// To facilitate the conversion to Datasets

val receivedDF = receivedRdd.map{ case List(a,b,c,d,e,f) => (a,b,c,d,e,f)}
                            .toDF("dateTime" , "server_name", "log_type", "server_addr", "action", "target_addr")

val sentDF = sentRdd.map{ case List(a,b,c,d,e,f) => (a,b,c,d,e,f)}
                    .toDF("dateTime" , "server_name", "log_type", "server_addr", "action", "target_addr")

// Convert multiple lines containing msg-type, content etc to single line using pivot
val otherDF = otherRdd.map{ case List(ts , srvr, typ, i1 , i2) => (ts , srvr, typ, i1 , i2) }
                      .toDF("dateTime" , "server_name", "log_type", "i1" , "i2")
                      .groupBy("dateTime" , "server_name", "log_type")
                      .pivot("i1").agg(first($"i2") )
                      .select($"dateTime", $"server_name", $"log_type", $"sec".as("cost") , $"Msg-Type".as("msg_type"), $"Content".as("content"))

otherDF.show
//+-------------------+-----------+--------+----+--------+----------+
//|           dateTime|server_name|log_type|cost|msg_type|   content|
//+-------------------+-----------+--------+----+--------+----------+
//|2018-04-11 06:27:34|  localhost|   debug| 0.3|    text|XXXXXXXXXX|
//|2018-04-11 06:27:36|  localhost|   debug| 0.4|    text|XXXXXXXXXX|
//+-------------------+-----------+--------+----+--------+----------+

// Finally join based on dateTime, server_name and log_type and convert to Datasets

val RlogDS = receivedDF.join(otherDF, Seq("dateTime" , "server_name", "log_type")).as[Rlog]
val SlogDS = sentDF.join(otherDF, Seq("dateTime" , "server_name", "log_type")).as[Slog]

RlogDS.show(false)
//+-------------------+-----------+--------+-----------+--------+-----------+----+--------+----------+
//|           dateTime|server_name|log_type|server_addr|  action|target_addr|cost|msg_type|   content|
//+-------------------+-----------+--------+-----------+--------+-----------+----+--------+----------+
//|2018-04-11 06:27:36|  localhost|   debug|  localhost|discover|    0.0.0.0| 0.4|    text|XXXXXXXXXX|
//+-------------------+-----------+--------+-----------+--------+-----------+----+--------+----------+

SlogDS.show(false)
//+-------------------+-----------+--------+-----------+--------+-----------+----+--------+----------+
//|dateTime           |server_name|log_type|server_addr|action  |target_addr|cost|msg_type|content   |
//+-------------------+-----------+--------+-----------+--------+-----------+----+--------+----------+
//|2018-04-11 06:27:34|localhost  |debug   |localhost  |response|0.0.0.0    |0.3 |text    |XXXXXXXXXX|
//+-------------------+-----------+--------+-----------+--------+-----------+----+--------+----------


text:
Q: How do you store a GameScene so I can transition back to it from an InGame Menu? Hello fellow programmers. Here is the scenario. There is an InGameMenuScene that the user can access during the game that allows them to access settings and such. One of the buttons, BackToGame, on the InGameMenuScene should take you back to the GameScene you were originally on. I'm needing help figuring out how to store a GameScene and then accessing stored GameScene when the BackToGame button is clicked. I tried storing it in the UserDefaults, but I'm having problems accessing it again in the InGameMenu.
Current GameScene:
func menuButtonPressed(){
let savedScene = BInNYGameScene.self
let userDefaults = UserDefaults.standard
    userDefaults.set(savedScene, forKey: "CurrentScene")
    userDefaults.set(count, forKey: "CurrentCount")
    userDefaults.set(hitCount, forKey: "CurrentHitCount")
    userDefaults.synchronize()
}

InGameMenuScene:
 func backToGame(){
    let userDefaults = UserDefaults.standard
    let backToGameScene = userDefaults.object(forKey: "CurrentScene") as! SKScene
    let nextScene = backToGameScene(size: scene!.size)
    nextScene.scaleMode = .aspectFill
    scene?.view?.presentScene(nextScene, transition: transition)

}

Please let me know if there is a better way to store the GameScene and retrieving the GameScene. Thank you!

A: Just keep track of it in your MenuScene before you transition to it
Current GameScene:
func toMenu(){
    let menu = MenuScene(...)
    menu.previousScene = self
    scene?.view?.presentScene(self, transition: transition)

}

InGameMenuScene:
 weak var previousScene : SKScene?
 func backToGame(){
    guard let previousScene = previousScene else{fatalError("No previous scene provided")}
    scene?.view?.presentScene(previousScene, transition: transition)

}


text:
Q: Use of undeclared identifier 'O_DIRECT' Apple LLVM version 10.0.0 (clang-1000.10.44.4)
Target: x86_64-apple-darwin18.0.0
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>

#define _GNU_SOURCE
#define __USE_GNU 1
#include <fcntl.h>

int main()
{
    int fd = open("./test.txt", O_WRONLY|O_DIRECT);

    close(fd);

    return 0;
}

I use clang -o out test.c and get the following result:
test.c:14:39: error: use of undeclared identifier 'O_DIRECT'
    int fd = open("./test.txt", O_WRONLY|O_DIRECT);

How can I solve the problem?
Thank you.

A: With this snippet it is impossible to tell what you are trying to do, but in general do not use nonstandard stuff in applications intended to be portable.
The portable way to accomplish your task is probably fsync.

A: To sum up
For LINUX, the O_DIRECT flag has to be included. For Mac OSX, O_DIRECT is not available. Instead, fcntl(fd, F_NOCACHE, 1) looks to be the canonical solution where fd is the file descriptor of the file. For Windows, there is a flag called FILE_FLAG_NO_BUFFERING as the counterpart in Windows of O_DIRECT
Reference here


text:
Q: How can I get all substrings of a string that consist of a special char and a number after it - C# I have strings in the following format:
string s1 = "#1233 + #343 - #24311";
string s2 = "(#563*#534)/#2333";

For each string, how can I get all the substrings that are of the form #NUMBER?
For instance: #1233, #343, #24311
Note that the number of digits of these numbers is not fixed, and they are not necessarily separated by spaces.

A: As GSerg kindly noted the regular expression, I just want to show the implementation:
MatchCollection matches = Regex.Matches(s1, @"#\d+");

string[] result = matches.Cast<Match>()
                         .Select(match => match.Value)
                         .ToArray();

Console.WriteLine( string.Join(Environment.NewLine, result) );

prints for s1
#1233
#343
#24311


text:
Q: Measuring relative rf signal strength I'm trying to measure the relative signal strength received by a dipole antenna for orientation purposes. I'd like to do so using an ordinary multi-meter.
I don't know much about RF circuits, but this is the circuit I came up with.

I was planning on measuring the resistance across the banana connectors to represent the relative inverse of signal strength.
Would this work? If so, which diodes and transistor should I use? If not, which circuit is best?

A: You need a RF power detector that suits your target frequency and power ranges.
You may also need some kind of band-pass filter if you want to detect a signal whose bandwidth is much narrower than the dipole antenna bandwidth and there are other interfering signals or adjacent channels that could be picked up by the antenna.
If RF is not your field of expertise, I'll recommend using COTS modules because RF is very, very tricky. However, they may be an expensive solution for your application.
Mini-Circuits RF power detectors run at $90 approx, but have huge bandwith and dynamic range. You may find lower priced, less capable, RF power detectors that may still comply with your frequency/power/precision needs. If yours is a DIY project, you could turn to AliExpress and the like to find much cheaper options, but keep in mind that you'll get what you pay for (still, it may be good enough for your needs).
You may want to take a look at this superb hack: a guy called Tim Heavens used one of Mini-Circuits RF power detectors, an Arduino, a LCD and a case and built a RF power meter.
EDIT:
You may also need to match the impedance of the antenna to that of the modules down the RF chain (usually 50 Ohm).

A: Your rectification mechanism needs to be matched to the frequencies you intend to detect. If you take a random full bridge rectifier you are likely not to see anything at all, as the RF waves will bounce off it. Look up literature on RF rectifiers for assistance here.
Furthermore, as RF signal strength is usually very low any considerable distance away from the source, you will be unlikely to ever see enough voltage over the rectifier unless you are practically standing beside the RF source to activate that Q1 base-emitter junction. Without a capacitor after the recitifer you would also see a pulsed waveform there, which is likely at a frequency Q1 cannot handle unless you pick it very carefully.

A: Here is a peak-detector from another answer; the response is LINEAR with input voltage. Installing a diode across the topleft resistor provides a LOG response.

There is no Miller Effect, in that V_collector does not move quickly. Expect to get common-base performance from your transistor, close to 300MHz with branded 2N3904. Or use a genuine RF device. The S11 will be poor. Do you care?

A: Your diagram shows a bridge rectifier .Most of the time they are designed for mains and therefor are far too slow.user 70614 has covered this .The bridge circuit has 2 diode     drops so it will have poorer weak signal performance .Ge diodes have very low drop and are normally found in glass packages and have low capacitance.I used Ge diodes in a mini production run of I think about 25 I think 25 years ago .The field strength meter worked   very well .It was used by Auto electricians for testing RF remotes .A skottkey diode should work fine we did some tests and found that low capacitance diodes worked as well as Ge .High capacitance diodes performed badly .We did not need any more field strength meters so none were produced with low capacitance shottkey diodes .I used a half wave voltage doubling detector and run its output into some case mounted red and black bananna jacks that plugged into a standard DVM .The DVMs that I looked at all had the same plug spacing .So the FSM plugged directly into the DVM sitting on top .Normally the DVM was set on the 300mV range and it worked fine for the job .Placing the DVM on ohms gave even more sensitivity because the DVM was providing current to prebias the diodes .

A: Here is a more broadband design.

simulate this circuit – Schematic created using CircuitLab
By the way, injecting into the EMITTER is an approved method to boost the performance of Trans Impedance Amplifiers.


text:
Q: Testing after_commit with RSpec and mocking I have a model Lead and a callback: after_commit :create, :send_to_SPL
I am using Rails-4.1.0, ruby-2.1.1, RSpec.
1) This spec is not passing:
context 'callbacks' do
  it 'shall call \'send_to_SPL\' after create' do
    expect(lead).to receive(:send_to_SPL)
    lead = Lead.create(init_hash)
    p lead.new_record? # => false
  end
end

2) This spec is not passing too:
context 'callbacks' do
  it 'shall call \'send_to_SPL\' after create' do
    expect(ActiveSupport::Callbacks::Callback).to receive(:build)
    lead = Lead.create(init_hash)
  end
end

3) This one is passing, but I think it is not testing after_commit callback:
context 'callbacks' do
  it 'shall call \'send_to_SPL\' after create' do
    expect(lead).to receive(:send_to_SPL)
    lead.send(:send_to_SPL)
  end
end

What is the best way to test after_commit callbacks in Rails?

A: I thought Mihail Davydenkov's comment deserved to be an answer:

You can also use subject.run_callbacks(:commit).

Also note that this issue (commit callbacks not getting called in transactional tests) should be fixed in rails 5.0+ so you may wish to make a note to remove any workarounds you may use in the meantime when you upgrade.  See: https://github.com/rails/rails/pull/18458

A: Try to use test_after_commit gem
or add following code in spec/support/helpers/test_after_commit.rb - Gist

A: Update for Rails5.
Callback handling has indeed been fixed, but you may still need to use #reload liberally.
An example:
Given a model that defines an after-create callback like so:
after_create_commit { assign_some_association }

You can spec this behavior with:
describe "callbacks" do
  describe "assigning_some_association" do
    subject(:saving) { record.save!; record.reload } # reload here is important

    let(:record) { build(:record) }

    it "assigns some association after commit" do
      expect{ saving }.to(
        change{ record.some_association_id }.from(nil).to(anything)
      )
    end
  end
end

A: I'm using DatabaseCleaner, with a configuration where I can easily switch between transaction and truncation, where the former is preferred, because of speed, but where the latter can be used for testing callbacks.
RSpec before and after handlers work with scopes, so if you want to make truncation a scope, define a before handler;
config.before(:each, truncate: true) do
  DatabaseCleaner.strategy = :truncation
end

And now to use this configuration for a describe, context or it block, you should declare it like:
describe "callbacks", truncate: true do
   # all specs within this block will be using the truncation strategy
  describe "#save" do
    it "should trigger my callback" do
      expect(lead).to receive(:send_to_SPL)
      lead = Lead.create(init_hash)
    end
  end
end

Complete hook configuration: (store in spec/support/database_cleaner.rb)
RSpec.configure do |config|
  config.before(:suite) do
    DatabaseCleaner.clean_with(:truncation)
  end

  config.before(:each) do
    DatabaseCleaner.strategy = :transaction
  end

  config.before(:each, truncate: true) do
    DatabaseCleaner.strategy = :truncation
  end

  config.before(:each) do
    DatabaseCleaner.start
  end

  config.append_after(:each) do
    DatabaseCleaner.clean
  end
end

A: I use something like this
describe 'some method on record' do
  let(:record) { create(:some_record) }
  let(:update_block) { ->(record) { record.save! } } # define an labmda that will be called in a transaction block
  let(:result_method) { :some_method } # define a method to be called
  let(:result) do
    record.class_eval <<~EVAL, __FILE__, __LINE__ + 1
      after_commit :_record_result
       def _record_result
        @_result = public_send(:#{result_method})
      end
    EVAL

    record.transaction do
      update_block.call(record)
    end

    record.instance_variable_get(:'@_result')
  end

  before do
    # apply changes to record
  end

  it 'returns the correct result' do
    expect(result).to eq(some_value)
  end
end


text:
Q: What is the Facebook app ID? I'm creating an online quiz website. I have everything setup and I am just working on the social buttons. At the end of the quiz, I want a share button to appear for Facebook and I want to customize the thumbnail and title and stuff like that based on the user's result.
To do this, I am trying to implement the Facebook Javascript SDK, but it needs an app ID. What is this and where do I get it?

A: You need to create an facebook app for yourself in facebook developer site.
After creating it, you can goto YourApp -> Settings
It will have an APP ID


text:
Q: Запуск приложения из JARа и манифест Доброго всем времени суток! есть небольшая проблемка. создаю я appframework application под maven. в помке прописываю плагин для сборки в jar:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>

<configuration>
      <archive>
        <manifest>
          <addClasspath>true</addClasspath>
          <mainClass>com.international.mainclass</mainClass>
        </manifest>
      </archive>
    </configuration>

  </plugin>

потом запускаю жарку и мне пишет ошибку : can't find main-class com.international.mainclass. в что я не так делаю?
A: Вы забыли написать главный класс, только и всего.
Вы либо вовсе его не написали, либо вы не указали его тут вместо com.international.mainclass.
UPD
А какая разница? В итоге у вас класс-форма и вы её содаёте и показываете обычным образом. Либо у вас main прямо внутри класса-фаормы.


text:
Q: optimizing a grid-based particle system I've implemented a game somewhat similar to this one in Java and currently find that I'm hitting a ceiling number of particles of ~80k. My game board is a 2D array of references to 'Particle' objects, each of which must be updated every frame. Different kinds of 'Particle' have different behaviors and may move or change their state in response to environmental conditions such as wind or adjacent particles.
Some possible 'rules' that might be in effect:

*

*If a Particle of type lava is adjacent to a Particle of type water, both disappear, and the lava is replaced by obsidian

*If a gas Particle is adjacent to a Lava, Fire, Ember, etc. Particle, it will ignite, and produce fire and smoke

*If a sufficient number of dust particles are stacked on top of one another, those at lower levels, as if under pressure, can become sedimentary rock

I've searched around and haven't been able to find any algorithms or data structures that seem particularly well-suited to speeding up the task. It seems that some kind of memoization might be useful? Would a quad tree be of any use here? I've seen them used in the somewhat similar Conway's Game of Life with the Hashlife algorithm. Or, is it the case that I'm not going to be able to do too much to increase the speed?

A: Hashlife will work in principle but there are two reasons why you might not get as much out of it as Conway Life.
Firstly it relies on recurring patterns. The more cell states you have and the less structured the plane the fewer cache hits you'll encounter and the more you'll be working with brute force.
Secondly as another poster noted rules that involve non-local effects will either mean your primitives (in Conway Life 4x4) will need to be bigger so you will have abandon divide and conquer at say 8x8 or 16x16 or whatever size guarantees you can correctly calculate the middle portion in n/2 time.
That's made the worse by the diversity of states. In Conway Life it's common to pre-calculate all 4x4 gridsor at least have nearly all relevant ones in cache.
With 2 states there are only 65536 4x4 grids (peanuts on modern platforms) but with only 3 there are 43046721.
If you have to have 8x8 primitives it gets very big very quickly and beyond any realistic storage.
So the larger the primitive and the more states you have that becomes quickly unrealistic.
One way to address that primitive size is to have the rock rule propagate pressure. So a Rock+n (n representing pressure) becomes Rock+(n+1) in the next generation if it has Rock+m where m>=n above it. Up to some threshold k where it turns to sedimentary Rock.
That means cells are still only dependent on their immediate neighbours but again multiplies up the number of states.
If you have cell types like the 'Bird' in the example given and you have velocities that you don't keep to a minimum (say -1,0,1 in either direction) you'll totally collapse memoization. Even then the chaotic nature of such rules may make cache hits on those areas vanishingly small.
If your rules don't lead to steady states (or repeating cycles) like Conway Life often does the return on memoization will be limited unless your plane is mostly empty.

A: i don't understand your problem clearly but I think cuda or OpenGL (GPU programming in general) can easily handle your ref link: https://dan-ball.jp/en/javagame/dust/

A: I'd use a fixed NxN grid for this mainly because there are too many points moving around each frame to benefit from the recursive subdividing nature of the quad-tree. This is a case where a straightforward data structure with the data representations and memory layouts tuned appropriately can make all the difference in the world.
The main thing I'd do for Java here is actually avoid modeling each particle as an object. It should be raw data like just some plain old data like floats or ints. You want to be able to work with contiguity guarantees for spatial locality with sequential processing and not pay for the cost of padding and the 8-byte overhead per class instance. Split cold fields away from hot fields.
For example, you don't necessarily need to know a particle's color to move it around and apply physics. As a result, you don't want an AoS representation here which has to load in a particle's color into cache lines during the sequential physics pass only to evict it and not use it. Cram as much relevant memory used together into a cache line as you can by separating it away from the irrelevant memory for a particular pass.
Each cell in the grid should just store an index into a particle, with each particle storing an index to the next particle in the cell (a singly-linked list, but an intrusive one which requires allocating no nodes and just uses indices into arrays). A -1 can be used to indicate the end of the list as well as empty cells.
To find collisions between particles of interest, look in the same cell as the particle you're testing, and you can do this in parallel where each thread handles one or more cells worth of particles.
The NxN grid should be very fine given the boatload of moving particles you can have per frame. Play with how many cells you create to find something optimal for your input sizes. You might even have multiple grids. If certain particles don't interact with each other, don't put them in the same grid. Don't worry about the memory usage of the grid here. If each grid cell just stores a 32-bit index to the first particle in the cell, then a 200x200 grid only takes 160 kilobytes with a 32-bit next index overhead per particle.
I made something similar to this some years back in C using the technique above (but not with as many interesting particle interactions as the demo game) which could handle about 10 mil particles before it started to go below 30 FPS and on older hardware with only 2 cores. It did use C as well as SIMD and multithreading, but I think you can get a very speedy solution in Java handling a boatload of particles at once if you do the above.
Data structure:

As particles move from one cell to the next, all you do is manipulate a couple of integers to move them from one cell to the other. Cells don't "own memory" or allocate any. They're just 32-bit indices.
To figure out which cell a particle occupies, just do:
cell_x = (int)(particle_x[particle_index] / cell_size)
cell_y = (int)(particle_y[particle_index] / cell_size)
cell_index = cell_y * num_cols + cell_x

... much cheaper constant-time operation than traversing a tree structure and having to rebalance it as particles move around.


text:
Q: How can I create a select menu in a shell script? I'm creating a simple bash script and I want to create a select menu in it, like this:
$./script

echo "Choose your option:"

1) Option 1
2) Option 2
3) Option 3
4) Quit

And according to user's choice, I want different actions to be executed. I'm a bash shell scripting noob, I've searched the web for some answers, but got nothing really concrete.

A: Bash fancy menu
Try it out first, then visit my page for detailed description.
No need for external libraries or programs like dialog or zenity.
#/bin/bash
# by oToGamez
# www.pro-toolz.net

      E='echo -e';e='echo -en';trap "R;exit" 2
    ESC=$( $e "\e")
   TPUT(){ $e "\e[${1};${2}H";}
  CLEAR(){ $e "\ec";}
  CIVIS(){ $e "\e[?25l";}
   DRAW(){ $e "\e%@\e(0";}
  WRITE(){ $e "\e(B";}
   MARK(){ $e "\e[7m";}
 UNMARK(){ $e "\e[27m";}
      R(){ CLEAR ;stty sane;$e "\ec\e[37;44m\e[J";};
   HEAD(){ DRAW
           for each in $(seq 1 13);do
           $E "   x                                          x"
           done
           WRITE;MARK;TPUT 1 5
           $E "BASH SELECTION MENU                       ";UNMARK;}
           i=0; CLEAR; CIVIS;NULL=/dev/null
   FOOT(){ MARK;TPUT 13 5
           printf "ENTER - SELECT,NEXT                       ";UNMARK;}
  ARROW(){ read -s -n3 key 2>/dev/null >&2
           if [[ $key = $ESC[A ]];then echo up;fi
           if [[ $key = $ESC[B ]];then echo dn;fi;}
     M0(){ TPUT  4 20; $e "Login info";}
     M1(){ TPUT  5 20; $e "Network";}
     M2(){ TPUT  6 20; $e "Disk";}
     M3(){ TPUT  7 20; $e "Routing";}
     M4(){ TPUT  8 20; $e "Time";}
     M5(){ TPUT  9 20; $e "ABOUT  ";}
     M6(){ TPUT 10 20; $e "EXIT   ";}
      LM=6
   MENU(){ for each in $(seq 0 $LM);do M${each};done;}
    POS(){ if [[ $cur == up ]];then ((i--));fi
           if [[ $cur == dn ]];then ((i++));fi
           if [[ $i -lt 0   ]];then i=$LM;fi
           if [[ $i -gt $LM ]];then i=0;fi;}
REFRESH(){ after=$((i+1)); before=$((i-1))
           if [[ $before -lt 0  ]];then before=$LM;fi
           if [[ $after -gt $LM ]];then after=0;fi
           if [[ $j -lt $i      ]];then UNMARK;M$before;else UNMARK;M$after;fi
           if [[ $after -eq 0 ]] || [ $before -eq $LM ];then
           UNMARK; M$before; M$after;fi;j=$i;UNMARK;M$before;M$after;}
   INIT(){ R;HEAD;FOOT;MENU;}
     SC(){ REFRESH;MARK;$S;$b;cur=`ARROW`;}
     ES(){ MARK;$e "ENTER = main menu ";$b;read;INIT;};INIT
  while [[ "$O" != " " ]]; do case $i in
        0) S=M0;SC;if [[ $cur == "" ]];then R;$e "\n$(w        )\n";ES;fi;;
        1) S=M1;SC;if [[ $cur == "" ]];then R;$e "\n$(ifconfig )\n";ES;fi;;
        2) S=M2;SC;if [[ $cur == "" ]];then R;$e "\n$(df -h    )\n";ES;fi;;
        3) S=M3;SC;if [[ $cur == "" ]];then R;$e "\n$(route -n )\n";ES;fi;;
        4) S=M4;SC;if [[ $cur == "" ]];then R;$e "\n$(date     )\n";ES;fi;;
        5) S=M5;SC;if [[ $cur == "" ]];then R;$e "\n$($e by oTo)\n";ES;fi;;
        6) S=M6;SC;if [[ $cur == "" ]];then R;exit 0;fi;;
  esac;POS;done

A: Not a new answer per se, but since there's no accepted answer yet, here are a few coding tips and tricks, for both select and zenity:
title="Select example"
prompt="Pick an option:"
options=("A" "B" "C")

echo "$title"
PS3="$prompt "
select opt in "${options[@]}" "Quit"; do
    case "$REPLY" in
    1) echo "You picked $opt which is option 1";;
    2) echo "You picked $opt which is option 2";;
    3) echo "You picked $opt which is option 3";;
    $((${#options[@]}+1))) echo "Goodbye!"; break;;
    *) echo "Invalid option. Try another one.";continue;;
    esac
done

while opt=$(zenity --title="$title" --text="$prompt" --list \
                   --column="Options" "${options[@]}")
do
    case "$opt" in
    "${options[0]}") zenity --info --text="You picked $opt, option 1";;
    "${options[1]}") zenity --info --text="You picked $opt, option 2";;
    "${options[2]}") zenity --info --text="You picked $opt, option 3";;
    *) zenity --error --text="Invalid option. Try another one.";;
    esac
done

Worth mentioning:

*

*Both will loop until the user explicitly chooses Quit (or Cancel for zenity). This is a good approach for interactive script menus: after a choice is selected and action performed, menu is presented again for another choice. If choice is meant to be one-time only, just use break after esac (the zenity approach could be further reduced also)

*Both case are index-based, rather than value-based. I think this is easier to code and maintain

*Array is also used for zenity approach.

*"Quit" option is not among the initial, original options. It is "added" when needed, so your array stay clean. Afterall, "Quit" is not needed for zenity anyway, user can just click "Cancel" (or close the window) to exit. Notice how both uses the same, untouched array of options.

*PS3 and REPLY vars can not be renamed. select is hardcoded to use those. All other variables in script (opt, options, prompt, title) can have any names you want, provided you do the adjustments

A: Since this is targeted at Ubuntu you should use whatever backend debconf is configured to use. You can find out the debconf backend with:
sudo -s "echo get debconf/frontend | debconf-communicate"

If it says "dialog" then it likely uses whiptail or dialog. On Lucid it's whiptail.
If that fails, use bash "select" as explained by Dennis Williamson.

A: I have used Zenity, which seems always there in Ubuntu, works very well and has many capabilities. This is a sketch of a possible menu:
#! /bin/bash

selection=$(zenity --list "Option 1" "Option 2" "Option 3" --column="" --text="Text above column(s)" --title="My menu")

case "$selection" in
"Option 1")zenity --info --text="Do something here for No1";;
"Option 2")zenity --info --text="Do something here for No2";;
"Option 3")zenity --info --text="Do something here for No3";;
esac

A: If you only want a very simple menu that shows "in place" and you can continue typing after that - without any fancy external dialog program, then you can use ANSI escape sequences and a simple loop to render the list and allow a cursor to be moved on top of it.
The answer here by user360154 already has everything you need, but it is also super fancy, does much more than needed and while the code is also formatted to look fancy - it isn't easy to read and understand.
Here's the same approach as user360154's but much simpler:
function choose_from_menu() {
    local prompt="$1" outvar="$2"
    shift
    shift
    local options=("$@") cur=0 count=${#options[@]} index=0
    local esc=$(echo -en "\e") # cache ESC as test doesn't allow esc codes
    printf "$prompt\n"
    while true
    do
        # list all options (option list is zero-based)
        index=0
        for o in "${options[@]}"
        do
            if [ "$index" == "$cur" ]
            then echo -e " >\e[7m$o\e[0m" # mark & highlight the current option
            else echo "  $o"
            fi
            index=$(( $index + 1 ))
        done
        read -s -n3 key # wait for user to key in arrows or ENTER
        if [[ $key == $esc[A ]] # up arrow
        then cur=$(( $cur - 1 ))
            [ "$cur" -lt 0 ] && cur=0
        elif [[ $key == $esc[B ]] # down arrow
        then cur=$(( $cur + 1 ))
            [ "$cur" -ge $count ] && cur=$(( $count - 1 ))
        elif [[ $key == "" ]] # nothing, i.e the read delimiter - ENTER
        then break
        fi
        echo -en "\e[${count}A" # go up to the beginning to re-render
    done
    # export the selection to the requested output variable
    printf -v $outvar "${options[$cur]}"
}

Here is an example usage:

selections=(
"Selection A"
"Selection B"
"Selection C"
)

choose_from_menu "Please make a choice:" selected_choice "${selections[@]}"
echo "Selected choice: $selected_choice"

Which should look like this:

A: There is already the same question in serverfault answered. The solution there uses whiptail.

A: #!/bin/bash
# Bash Menu Script Example

PS3='Please enter your choice: '
options=("Option 1" "Option 2" "Option 3" "Quit")
select opt in "${options[@]}"
do
    case $opt in
        "Option 1")
            echo "you chose choice 1"
            ;;
        "Option 2")
            echo "you chose choice 2"
            ;;
        "Option 3")
            echo "you chose choice $REPLY which is $opt"
            ;;
        "Quit")
            break
            ;;
        *) echo "invalid option $REPLY";;
    esac
done

Add break statements wherever you need the select loop to exit. If a break is not performed, the select statement loops and the menu is re-displayed.
In the third option, I included variables that are set by the select statement to demonstrate that you have access to those values. If you choose it, it will output:
you chose choice 3 which is Option 3

You can see that $REPLY contains the string you entered at the prompt. It is used as an index into the array ${options[@]} as if the array were 1 based. The variable $opt contains the string from that index in the array.
Note that the choices could be a simple list directly in the select statement like this:
select opt in foo bar baz 'multi word choice'

but you can't put such a list in a scalar variable because of the spaces in one of the choices.
You can also use file globbing if you are choosing among files:
select file in *.tar.gz

A: You can use this simple script for creating options #!/bin/bash
echo "select the operation ************"
echo "  1)operation 1"
echo "  2)operation 2"
echo "  3)operation 3"
echo "  4)operation 4"
read n
case $n in
  1) echo "You chose Option 1";;
  2) echo "You chose Option 2";;
  3) echo "You chose Option 3";;
  4) echo "You chose Option 4";;
  *) echo "invalid option";;
esac

A: I have one more option that is a mixture of these answers but what makes it nice is that you only need to press one key and then the script continues thanks to the -n option of read. In this example, we are prompting to shutdown, reboot, or simply exit the script using ANS as our variable and the user only has to press E, R, or S. I also set the default to exit so if enter is pressed then the script will exit.
#!/bin/bash
read -n 1 -p "Would you like to exit, reboot, or shutdown? (E/r/s) " ans;

case $ans in
    r|R)
        sudo reboot;;
    s|S)
        sudo poweroff;;
    *)
        exit;;
esac

A: Using dialog, the command would look like this:
dialog --clear --backtitle "Backtitle here" --title "Title here" --menu "Choose one of the following options:" 15 40 4 \
1 "Option 1" \
2 "Option 2" \
3 "Option 3"

Putting it in a script:
#!/bin/bash

HEIGHT=15
WIDTH=40
CHOICE_HEIGHT=4
BACKTITLE="Backtitle here"
TITLE="Title here"
MENU="Choose one of the following options:"

OPTIONS=(1 "Option 1"
         2 "Option 2"
         3 "Option 3")

CHOICE=$(dialog --clear \
                --backtitle "$BACKTITLE" \
                --title "$TITLE" \
                --menu "$MENU" \
                $HEIGHT $WIDTH $CHOICE_HEIGHT \
                "${OPTIONS[@]}" \
                2>&1 >/dev/tty)

clear
case $CHOICE in
        1)
            echo "You chose Option 1"
            ;;
        2)
            echo "You chose Option 2"
            ;;
        3)
            echo "You chose Option 3"
            ;;
esac

A: #!/bin/sh
show_menu(){
    normal=`echo "\033[m"`
    menu=`echo "\033[36m"` #Blue
    number=`echo "\033[33m"` #yellow
    bgred=`echo "\033[41m"`
    fgred=`echo "\033[31m"`
    printf "\n${menu}*********************************************${normal}\n"
    printf "${menu}**${number} 1)${menu} Mount dropbox ${normal}\n"
    printf "${menu}**${number} 2)${menu} Mount USB 500 Gig Drive ${normal}\n"
    printf "${menu}**${number} 3)${menu} Restart Apache ${normal}\n"
    printf "${menu}**${number} 4)${menu} ssh Frost TomCat Server ${normal}\n"
    printf "${menu}**${number} 5)${menu} Some other commands${normal}\n"
    printf "${menu}*********************************************${normal}\n"
    printf "Please enter a menu option and enter or ${fgred}x to exit. ${normal}"
    read opt
}

option_picked(){
    msgcolor=`echo "\033[01;31m"` # bold red
    normal=`echo "\033[00;00m"` # normal white
    message=${@:-"${normal}Error: No message passed"}
    printf "${msgcolor}${message}${normal}\n"
}

clear
show_menu
while [ $opt != '' ]
    do
    if [ $opt = '' ]; then
      exit;
    else
      case $opt in
        1) clear;
            option_picked "Option 1 Picked";
            printf "sudo mount /dev/sdh1 /mnt/DropBox/; #The 3 terabyte";
            show_menu;
        ;;
        2) clear;
            option_picked "Option 2 Picked";
            printf "sudo mount /dev/sdi1 /mnt/usbDrive; #The 500 gig drive";
            show_menu;
        ;;
        3) clear;
            option_picked "Option 3 Picked";
            printf "sudo service apache2 restart";
            show_menu;
        ;;
        4) clear;
            option_picked "Option 4 Picked";
            printf "ssh lmesser@ -p 2010";
            show_menu;
        ;;
        x)exit;
        ;;
        \n)exit;
        ;;
        *)clear;
            option_picked "Pick an option from the menu";
            show_menu;
        ;;
      esac
    fi
done


text:
Q: How to import a variable from LUA to xml? I need a generic xml file for different model devices. The element  is variable depending on different models but everything else in xml is same for all models. The model name is defined in LUA file. Is there any way to import this model name from LUA to xml file?
Thanks.

A: You'll need to process that XML file to add that model name to it. You may be able to do it from the same Lua file where the model name is "defined" using these steps:

*

*read the XML file (local text = io.open("filename"):read('*a')),

*modify the file to include the model name; if you mark the location with something like MODELNAME, you can then replace with with the actual model using gsub: text:gsub('MODELNAME', modelname)

*write the updated content back: io.open("filename", "w"):write(text).


text:
Q: Why is the time reported by time() sometimes 1 second behind the seconds component of timespec_get() in C code? The following snippet of code:
struct timespec ts;
for (int x = 0; x < 100000000; x++) {
    timespec_get(&ts, TIME_UTC);
    long cTime = (long) time(NULL);
    if (cTime != ts.tv_sec && ts.tv_nsec < 3000000) {
        printf("cTime: %ld\n", cTime);
        printf("ts.tv_sec: %ld\n", ts.tv_sec);
        printf("ts.tv_nsec: %ld\n", ts.tv_nsec);
    }
}

produces this output:
...
cTime: 1579268059
ts.tv_sec: 1579268060
ts.tv_nsec: 2527419
cTime: 1579268059
ts.tv_sec: 1579268060
ts.tv_nsec: 2534036
cTime: 1579268059
ts.tv_sec: 1579268060
ts.tv_nsec: 2540359
cTime: 1579268059
ts.tv_sec: 1579268060
ts.tv_nsec: 2547039
...

Why the discrepancy between cTime and ts.tv_sec? Note that the problem does not occur if the conditional is changed to ts.tv_nsec >= 3000000. The problem relies on nanoseconds being smaller than 3000000.

A: The reason is, that you (implicitly) use different system clocks. timespec_get() uses the high resolution system-wide realtime clock, while time() uses the coarse realtime clock.
Try to use
clock_gettime(CLOCK_REALTIME_COARSE, &ts);

instead of your timespec_get(), then the difference should vanish.
Edit:
This can be seen in the Linux Kernel Source, vclock_gettime.c
Indeed the issue is a bit subtle to see here. The seconds-part of the structure members used by CLOCK_REALTIME_COARSE and CLOCK_REALTIME contain identical values, but the nanoseconds-part is different; with CLOCK_REALTIME it can be larger than 1000000000 (which is one second). In this case, it is fixed up on the call:
ts->tv_sec += __iter_div_u64_rem(ns, NSEC_PER_SEC, &ns);
ts->tv_nsec = ns;

This correction is neither performed with CLOCK_REALTIME_COARSE, nor with time(). This explains the difference between CLOCK_REALTIME and time().


text:
Q: Get availability group and listener of the current DB (dynamic SQL) I have hundreds of DB on an instance and I want to remove the DB from their AG (each DB is in a separate AG), remove the listener and then delete that AG. I have written the script below to automate this a bit:
DECLARE @name VARCHAR(50);
DECLARE @sql nvarchar(4000);
DECLARE db_cursor CURSOR FOR select name from sys.sysdatabases where name not in ('testing_db');

Open db_cursor
Fetch Next From db_cursor Into @name
WHILE @@FETCH_STATUS = 0
BEGIN
     select @sql =
     'ALTER AVAILABILITY GROUP [' + @name + '] REMOVE DATABASE [' + @name + '];' + char(10) +
     'ALTER AVAILABILITY GROUP [' + @name + '] REMOVE LISTENER ' + char(10) +
     'DROP AVAILABILITY GROUP [' + @name + '];' + char(10) + 'GO' + CHAR(10) + CHAR(10) + CHAR(10)

     print @sql;

     fetch Next From db_cursor Into @name
END

CLOSE db_cursor
DEALLOCATE db_cursor

This will give me something as the below for each DB in my instance:
ALTER AVAILABILITY GROUP [**DB1**] REMOVE DATABASE [DB1];
ALTER AVAILABILITY GROUP [**DB1**] REMOVE LISTENER N**<>**
DROP AVAILABILITY GROUP [**DB1**];
GO

I cannot find a way to get the availability group and its listener for each DB in each run (The stuff between ** ** needs to be replaced by the AG name/AG listener accordingly). I have searched how to get an AG name/listener for a DB but all of the solutions require a lot of joins which will complicate this query. What's the neatest way to do this?

A: You need to run queries agains the DMV to get the AG name.
Here's some code you could use as a base:
select DB_NAME(AG_DB.database_id) "DB", AG.name  "AG Name", li.dns_name "Listener"
from sys.dm_hadr_database_replica_states AG_DB
join sys.availability_groups AG on AG.group_id = AG_DB.group_id
join sys.availability_group_listeners li on li.group_id = AG.group_id

This will only returns databases that are in AG (vs a query in sys.databases which will return the system DB as well).
P.s. If you do not need the listener (which seems to be the case) then you do not need the 3rd table and it will keep the query pretty simple.


text:
Q: How to make POST requests to class-based Views in Django I have created different class-based views on Django. On the HTML i created some forms make a request with AJAX. My problem is that it gives me
Method Not Allowed (POST)
I don know if i'm doing it rigth, or if i need to modify something for it to work.
My view.py is something like this
class Landing(View):
    def get(self,request):
        if request.method == 'POST':
            if request.is_ajax():
                data = {"lat":20.586, "lon":-89.530}
                print request.POST.get('value')
                return JsonResponse(data)
    return render(request,'landing.html',{'foo':'bar'})

And i send the reques from Javascript
$(document).ready(function() {
  $('#productos').on('change', function(e) {
     //Call the POST
     e.preventDefault();
     var csrftoken = getCookie('csrftoken');
     var value = $('#productos').val();

     $.ajax({
        url: window.location.href,
        type: "POST",
        data: {
            csrfmiddlewaretoken : csrftoken,
            value : value
        },
        success : function(json) {
            console.log(json);
            drop(json);
        },
        error : function(xhr,errmsg,err){
            console.log(xhr.status+": "+xhr.responseText)
        }
     });
  });
});

I got some of the code from a web, but i really don't know how to use it, since they used it without class-based views.
So, What does need my code to accept the POST method?

A: The dispatch method of a class based view determines which function is called, so far you've written a get function, but no post function so just move the logic into a post function.
class Landing(View):
    def post(self,request):
        if request.is_ajax():
            data = {"lat":20.586, "lon":-89.530}
            print request.POST.get('value')
            return JsonResponse(data)

    def get(self, request):
         return render(request,'landing.html',{'foo':'bar'})


text:
Q: error ValueError: I/O can't write to a closed file I wrote this piece of code basically it creates a txt file with today date and start logging to it, i made a function to save the file send it somewhere (email) reopen the file to continue writing to it,
Problem : i can't reopen it from inside the function please take a look and suggest a solution thanks in advance
import os, time
import datetime, pytz

x = datetime.datetime.utcnow()
i = x + datetime.timedelta(hours=3)
y = i.strftime("%Y-%m-%d_%I:%M%P")
d = i.strftime("%Y-%m-%d")
filename = d + ".txt" #name the file with today date
print(y) # print date and time at script start

l = open(filename, "a") #create the file

print("""
 """ + y, file=l) #log today date to the file

def sendf():
    print("test1", file=l) #test write
    clsfile = l.close() #save file before sending
    print("file saved now sending")
    #code to send file to somewhere
    h = open(filename, "a") #open the file to write again
    h = l #if i open the file and assinged it to l directly  i get print("t>
          #UnboundLocalError: local variable 'l' referenced before assignme>

sendf() #function to send the file

print("write test", file = l) #test writing to the file

#error print("write test", file = l) #test writing to the file
#ValueError: I/O operation on closed file.

A: Use global to assign to a global from within a function.
def sendf():
    global l
    print("test1", file=l) #test write
    clsfile = l.close() #save file before sending
    print("file saved now sending")
    #code to send file to somewhere
    h = open(filename, "a") #open the file to write again
    l = h


text:
Q: Python two lists previous indexes comparison does not work I have two lists, a and b. I am trying to find a,b where for example b[-1] > a[-1] and b[0] < a[0]. So basically if you imagine that a and b list are lines on the chart then I am looking for crossings. I am not sure why, but the code I wrote shows only first crossing correctly, next one does not fill the condition.
Here is the code:
a = [19, 17, 12, 8, 7, 10, 13, 24, 36, 56, 68, 73, 78, 86, 88, 84, 80, 73]
b = [22, 19, 11, 5, 3, 7, 11, 21, 30, 54, 62, 71, 75, 84, 86, 90, 85, 77]

for i,j in zip(a,b):

    if a[a.index(i) - 1] < b[b.index(j) -1]:
        if a[a.index(i)] > b[b.index(j)]:
            print(a[a.index(i)],b[b.index(j)])

Output:
12 11
13 11

------------------
(program exited with code: 0)
Press return to continue

So 12 11 are correct because 17 < 19, but 13 11 are not correct because 10 > 7
Appreciate any suggestions.
Thanks

A: Problem is due to repeated element in list b
this is my solution without using index.
a = [19, 17, 12, 8, 7, 10, 13, 24, 36, 56, 68, 73, 78, 86, 88, 84, 80, 73]
b = [22, 19, 11, 5, 3, 7, 10, 21, 30, 54, 62, 71, 75, 84, 86, 90, 85, 77]

c = [[i,j] for i,j in zip(a,b)]
for i,j in enumerate(c):
    if c[i-1][1] > c[i-1][0] and c[i][1] < c[i][0]:
        print(*j)

Output:
12 11


text:
Q: Eloquent how I can parse postgresql's hstore? An eloquent model uses the following table and it is stored in a postgresql database:
name: table
id: PK SERIAL
values: HSTORE

And the model is named TableModel
namespace App;
use Illuminate\Database\Eloquent\Model;
class TableModel extends Model
{
   protected $table = 'table';
}

But once I retrieve the value value I get the following response using tinker session:
$model = Model::find('1');
$model->value;
""name"=>"Namae", "value"=>"55""

How I can retrieve either the name or the value from the value column.

A: Hstore is simply a format in a form of
"key" => "Value","key"=>"value"

As seen in https://www.postgresql.org/docs/11/hstore.html
And easily can be converted into json by replacing the => into : and enclosing the string into {} a sample code to do this is (continuing the tinker session you mention in your question):
$value = $model->value;
$value = str_replace('=>',':',$value);
$value = '{'.$value.'}';
$value = json_decode($value)

A: Because hstore format equal to php format you can use PHP eval function:
$hstore = '"name"=>"Namae", "value"=>"55"';

eval('$d=['.$hstore.'];');

printf("The value is %s \n", $d["value"]);

PHP online fiddle


text:
Q: How import fontello in react I'm following this tutorial to import fontello in my project.
But in step 5 I dont have fontello.css file.

So, in your App.js import fontello
import "./fontello/css/fontello.css"

As you can see in my project I dont have that file. So How Can I Import Fontello to my project??

A: Well it seems like the cli actually set all your file names in css starting with my-icon instead of fontello
To make you code work, you can import the css like
import "./fontello/css/my-icons.css"

and it should work the same
EDIT:
Another solution if for you to set the name field in config.json to fontello and then run fontello-cli install, this will lead to the css file names to be prefixed with the name fontello and you can import it like it is mentioned in the medium article