text:
Q: Ruby on Rails: ActiveRecord::ConnectionNotEstablished I'm trying to enable mySQL for my Ruby on Rails application. I generated a model for Project in Rails, used bundle exec rake db:migrate, and it added all fields required to myapp_dev database (mySQL). But when I go to localhost:3000/projects, I get this error:
ActiveRecord::ConnectionNotEstablished

activerecord (3.2.0) lib/active_record/connection_adapters/abstract/connection_pool.rb:374:in `retrieve_connection'
activerecord (3.2.0) lib/active_record/connection_adapters/abstract/connection_specification.rb:168:in `retrieve_connection'
activerecord (3.2.0) lib/active_record/connection_adapters/abstract/connection_specification.rb:142:in `connection'
activerecord (3.2.0) lib/active_record/query_cache.rb:67:in `rescue in call'
activerecord (3.2.0) lib/active_record/query_cache.rb:61:in `call'
activerecord (3.2.0) lib/active_record/connection_adapters/abstract/connection_pool.rb:443:in `call'
actionpack (3.2.0) lib/action_dispatch/middleware/callbacks.rb:28:in `block in call'
activesupport (3.2.0) lib/active_support/callbacks.rb:405:in `_run__93413930__call__216979767__callbacks'
activesupport (3.2.0) lib/active_support/callbacks.rb:405:in `__run_callback'
activesupport (3.2.0) lib/active_support/callbacks.rb:385:in `_run_call_callbacks'
activesupport (3.2.0) lib/active_support/callbacks.rb:81:in `run_callbacks'
actionpack (3.2.0) lib/action_dispatch/middleware/callbacks.rb:27:in `call'
actionpack (3.2.0) lib/action_dispatch/middleware/reloader.rb:65:in `call'
actionpack (3.2.0) lib/action_dispatch/middleware/remote_ip.rb:31:in `call'
actionpack (3.2.0) lib/action_dispatch/middleware/debug_exceptions.rb:16:in `call'
actionpack (3.2.0) lib/action_dispatch/middleware/show_exceptions.rb:56:in `call'
railties (3.2.0) lib/rails/rack/logger.rb:26:in `call_app'
railties (3.2.0) lib/rails/rack/logger.rb:16:in `call'
actionpack (3.2.0) lib/action_dispatch/middleware/request_id.rb:22:in `call'
rack (1.4.1) lib/rack/methodoverride.rb:21:in `call'
rack (1.4.1) lib/rack/runtime.rb:17:in `call'
activesupport (3.2.0) lib/active_support/cache/strategy/local_cache.rb:72:in `call'
rack (1.4.1) lib/rack/lock.rb:15:in `call'
actionpack (3.2.0) lib/action_dispatch/middleware/static.rb:53:in `call'
railties (3.2.0) lib/rails/engine.rb:479:in `call'
railties (3.2.0) lib/rails/application.rb:220:in `call'
rack (1.4.1) lib/rack/content_length.rb:14:in `call'
railties (3.2.0) lib/rails/rack/log_tailer.rb:14:in `call'
rack (1.4.1) lib/rack/handler/webrick.rb:59:in `service'
/usr/share/ruby-rvm/rubies/ruby-1.9.3-p0/lib/ruby/1.9.1/webrick/httpserver.rb:138:in `service'
/usr/share/ruby-rvm/rubies/ruby-1.9.3-p0/lib/ruby/1.9.1/webrick/httpserver.rb:94:in `run'
/usr/share/ruby-rvm/rubies/ruby-1.9.3-p0/lib/ruby/1.9.1/webrick/server.rb:191:in `block in start_thread'

What is the problem here?
Here is my database.yml
development:
  adapter: mysql
  encoding: utf8
  database: myapp_dev
  username: root
  password: root
  host: localhost

A: Seems like, your MySql db connection is not working, try to login to your my sql server with following command
mysql -uroot -proot myapp_dev

Make sure this works, if this works your app also should be able to access the DB, If you get any error, posting the error here will get someone to help you
cheers

A: Try putting 'dev' section on the top of database.yml:
dev:
  adapter: mysql
  encoding: utf8
  database: myapp_dev
  username: root
  password: root
  host: localhost

and leave 'development' section as it is.


text:
Q: How can I join a table to return all rows right and in addition a null row? I have two tables, one with a list of parts, and another with a list of attributes. What I'm trying to achieve is to list all parts with their attributes, and also the base row itself a la:
Part   Attribute
----------------
Cake   Batman
Cake   Princess
Cake   Spiderman
Cake   NULL

QUERY
----------------
SELECT p.Name, pa.Name
FROM PartsTbl p
LEFT JOIN PartAttrib pa ON p.Name= pa.BaseName
WHERE p.Name = 'Cake'

Currently, this only returns everything except the last row. How can I produce the last row as part of the same query, instead of by running a second query?
UPDATE ---------------
Table Structure
PartsTbl - Name
PartAttrib - BaseName (To PartsTbl.Name), Name

A: A simple Union is your friend :o)
SELECT p.Name, pa.Name
FROM PartsTbl p
LEFT JOIN PartAttrib pa ON p.Name= pa.BaseName
WHERE p.Name = 'Cake'
UNION
SELECT Name, NULL
FROM PartsTbl
WHERE Name = 'Cake'

redpajama_set_name: RedPajamaStackExchange


text:
Q: JAVA FX Modify TableView Column So I have a TableView setup in my app that lists the current system users for the app itself. The TableView has 4 columns, UserId, UserName, CreatedDate, and Active
The getActive() method returns an integer of 1 or 0 respectively if the user is active or inactive.
My table column currently outputs the values of 1 or 0 for each user. I would like to however format that column as showing Yes or No instead of 1 or 0.
Is it possible to bind the returned value of the column to a String like that?
Here is what I am using to set the column data in my initialize method:
activeCol.setCellValueFactory(new PropertyValueFactory<>("active"));

A: So I managed to find a way to do what I needed to. Not entirely sure this is the best method so I am open to additional suggestions.
activeCol.setCellValueFactory((CellDataFeatures<User, String> u) -> {
    String userActive = String.valueOf(u.getValue().getActive());
    userActive= (!userActive.equals("0")) ? "Yes" : "No";
    return new ReadOnlyStringWrapper(userActive);
});


text:
Q: Citation appears as question mark, bibliography has title but is blank I'm using the harvard package with BibTeX and not sure why it's coming up with question mark in pdf. Due to citation not working, reference is blank. Seen many people saying run BibTeX then LaTeX twice but this doesn't work at all. bib file should be fine as it's come straight from a journal site.
My code is probably wrong..here's what I've got:
\documentclass{article}
\usepackage{mathtools}
\usepackage[top=3cm, bottom=3cm, left=4cm, right=2cm]{geometry}
\usepackage{bibentry}
\usepackage{bibtexlogo}
\usepackage{harvard}
\bibliographystyle{dcu}
\usepackage{cite}

\begin{document}

mortar's properties.\cite{2003427682262} make reference...
etc. etc.

\bibliographystyle{dcu}
\bibliography{lanas}

\end{document}

A: Here are a few things to try:

*

*Run (pdf)LaTeX, then BibTeX, then pdfLaTeX twice.

*What happens if you run natbib instead of Harvard?

*Paste the citation key, don't retype (though probably not an issue in your case - you probably do anyway if that's the real key.

*I'm sure you've already check file name, folder etc. - do it again anyway!


text:
Q: I dont know how to pull out image ID from echoed data So let me explain from the start :
     <?

$images_query = "SELECT * FROM `tag` ";
    $images = mysqli_query($conn, $images_query); ?>

              <a title="<?php echo $row['name'];?>" class="fancybox" href="<?php echo $row['name'];?>" alt="" > <img title="1st title" style="margin-top:12px;" src="<?php echo $row['name'];?>" alt="" >

                  <div class="col-md-4" data-href="http://etronhosting.com/brain/<? echo $test;?>">

   <form method="post">
             <input type="submit" value="add" name="fav"/>
             </form>
                 <?
                 if(isset($_POST['fav'])){
                 $sq = "INSERT INTO `favourites`  (`name`)
                          SELECT `name` from `tag`";
                 $insert=mysqli_query($conn,$sq );}?>

                 <div class="fb-share-button col-md-4" data-href="http://etronhosting.com/brain/<? echo $row['name'];?>" data-layout="button_count">

So from the first div,it echoes out name from table tag-So it Displays every image iv stored into tag table.
In div tag with "fb share" class is as u guess facebook share button.
But the problem is in the form.Basicly what i am trying to do is add a "Add to favourites button" where when user clicks on it,it copies pucture name (path) to the favourites table.And probobly session id with it.Then on the favourites.php i could echo out every image with current sesson_id.
Iv tryed many things,but mostly they insert only the name of the first picture and thats it.
Does anyone have idea how to make this work ? Or is ther e any other better method to make "add to favourites" ?


text:
Q: Comparar una variable con una consulta SQLite3 Quiero hacer un log in y comparar si existe el usuario, pero al momento de hacer la consulta me devuelve el valor como una tupla y marca error aunque si exista el usuario. dejo la foto de la base de datos de la que quiero hacer la consulta
import sqlite3

mail = "ivan@gmail.com"
pwd = "Hola123"

#CONEXION
class Base_datos():

    def buscar(self):
        conexion = sqlite3.connect("tattoRecognizer.db")
        cursor = conexion.cursor()

        cursor.execute("SELECT Correo FROM Usuario")
        for linea in cursor:
            if mail == linea:
                resultado = 1
                break

            else:
                resultado = 0

        return resultado

#instancia
query = Base_datos()
resultado = query.buscar()
print(f"El resultado de la funcion es: {resultado}")

A: Explicación
Cuando haces una consulta sql, y iteras sobre el cursor, lo que devuelve es un iterador que va devolviendo tuplas (inclusive si solo estás consultando una sola columna).
Cuando iteras sobre esa lista, vas obteniendo tuplas de un solo item.
Ejemplo:
Teniendo esta tabla

columna1
columna2

a
1

b
2

c
3

Y haciendo
SELECT columna2 FROM tabla

Irás obteniendo estas tuplas:
(1,)
(2,)
(3,)

Y si comparas una tupla con algo que no es una tupla (como una cadena) siempre dará False: 1 == (1,)
Solución siguiendo tu código
Desempaqueta la tupla. Esto podés hacerlo, por ejemplo, usando el desempaquetado
import sqlite3

mail = "ivan@gmail.com"
pwd = "Hola123"

#CONEXION
class Base_datos():

    def buscar(self):
        conexion = sqlite3.connect("tattoRecognizer.db")
        cursor = conexion.cursor()

        cursor.execute("SELECT Correo FROM Usuario")
        for (linea,) in cursor:
            if mail == linea:
                resultado = 1
                break

            else:
                resultado = 0

        return resultado

#instancia
query = Base_datos()
resultado = query.buscar()
print(f"El resultado de la funcion es: {resultado}")

La Mejor Solución
En realidad, lo que estás haciendo, debería hacerse desde la base de datos.
Tu enfoque de que el cliente revise todos los registros tiene desventajas:

*

*Se carga todos los datos en memoria.

*Es mucho más lento.

*No estoy seguro de esto ultimo. Pero lo mencionaré igual. Le estás dando al cliente todos los datos de todos los usuarios. Sospecho que si accedes a la lista en memoria con algún programa, tendrá acceso a todos los usuarios de la base de datos.

Entonces, lo mejor es que uses la función exists, la clausula where y pasar parametros a la consulta.
# los signos de pregunta y la tupla pasada de segundo argumento
# a execute, son los parametros
cursor.execute("SELECT EXISTS(SELECT Null FROM usuario WHERE Correo=? AND password=?", (mail, pwd))

Esta consulta devuelve siempre una sola fila y una sola columna. Si existe al menos un registro con el correo y la constraseña pasadas, el unico valor que hay será True. De lo contrario False.
Como es una sola fila, nos alcanza con obtener dicha fila con cursor.fetchone(). Y como siempre será una sola columna, la desempaquetamos:
(is_valid_user,) = cursor.fetchone()

Codigo Completo
import sqlite3

mail = "ivan@gmail.com"
pwd = "Hola123"

#CONEXION
class Base_datos():

    def buscar(self):
        conexion = sqlite3.connect("tattoRecognizer.db")
        cursor = conexion.cursor()

        cursor.execute("SELECT EXISTS(SELECT Null FROM usuario WHERE Correo=? AND password=?", (mail, pwd))
        (resultado,) = cursor.fetchone()

        return resultado

#instancia
query = Base_datos()
resultado = query.buscar()
print(f"El resultado de la funcion es: {resultado}")

A: El problema que tienes es que línea es una tupla con todas las columnas que pediste en el SELECT. No importa que sea 1 o muchas columnas, siempre será una tupla. Entonces comparar tupla vs cadena siempre dará False. Para resolver eso, solo basta con:
if mail == linea[0]:

Pero hay más problemas, que pueden ser tomados como "basados en opiniones", pero los expondré para que los tengas en cuenta.
(2) No estás dejando que la base de datos haga su trabajo, por lo tanto ese for está de más.
(3) La conexión a la base de datos la manejas de forma local en un método, esto no tiene mucho sentido si estás trabajando con clases.
import sqlite3

#CONEXION
class Base_datos():
    def __init__(self):
        pass

    def get_db_cursor(self):
        conexion = sqlite3.connect("tattoRecognizer.db")
        return conexion.cursor()

    def buscar(self, email, clave):
        cursor = self.get_db_cursor()
        query = "SELECT Correo, Contra FROM Usuario WHERE Correo=?"
        #                         ^--- Nombre de columna de la clave
        res = cursor.execute(query, (email,))
        fila = res.fetchone()
        if fila and fila[1] == clave:
            resultado = 1 # Usuario y contraseña correctos
        else:
            resultado = 0 # Usuario y/o contraseña incorrectos
        return resultado

mail = "ivan@gmail.com"
pwd = "Hola123"
#instancia
query = Base_datos()
resultado = query.buscar(mail, pwd)
print(f"El resultado de la funcion es: {resultado}")


text:
Q: HtmlUnit stays logged in after removing "JSESSIONID" cookie I'm setting up remember-me authentication for my Spring Boot application an want to write a HtmlUnit test.
The problem is that deleting the "JSESSIONID" cookie does not seem to log out the webClient.
The test using remember-me authentication works fine but the test in which there should be no authentication and thus a redirect to the login page does not work (the last assertion fails).
@Test
void NoRememberMeLogin() throws IOException {
    HtmlPage loginPage = webClient.getPage(baseURL + "login");
    HtmlForm loginForm = loginPage.getFormByName("loginForm");
    HtmlInput username = loginForm.getInputByName("username");
    HtmlInput password = loginForm.getInputByName("password");
    HtmlCheckBoxInput rememberMe = loginForm.getInputByName("remember-me");

    username.setValueAttribute("user");
    password.setValueAttribute("password");
    rememberMe.setChecked(false);

    // login
    HtmlElement submit = loginForm.getOneHtmlElementByAttribute("input", "type", "submit");
    HtmlPage afterLogin = submit.click();
    // login successful?
    assertThat(afterLogin.getUrl().toString(), is(baseURL + "securedPage"));

    // checkl cookies
    Cookie sessionCookie = webClient.getCookieManager().getCookie("JSESSIONID");
    Cookie rememberMeCookie = webClient.getCookieManager().getCookie("remember-me");
    assertNotNull(sessionCookie);
    assertNull(rememberMeCookie);

    // delete the Session cookie
    webClient.getCookieManager().removeCookie(sessionCookie);
    sessionCookie = webClient.getCookieManager().getCookie("JSESSIONID");
    // session cookie really is deleted
    assertNull(sessionCookie);

    // refresh tha page (works in browser)
    afterLogin.refresh();
    // check that we were redirected to login page (not working)
    assertThat(afterLogin.getUrl().toString(), is(baseURL + "login"));
}

Hope you can help me, thanks!


text:
Q: heroku laravel Error: tunneling socket could not be established, cause=connect ECONNREFUSED 127 .0.0.1:8080 C:\Users\ghunaim>heroku login
heroku: Enter your login credentials
Email: moahemdghunaim7030@gmail.com
Password:
Error: tunneling socket could not be established, cause=connect ECONNREFUSED 127
.0.0.1:8080
    at ClientRequest.onError (C:/Program Files/heroku/client/node_modules/tunnel
-agent/index.js:177:17)

A: Remove a http_proxy in environment variables.
delete this:


text:
Q: Similar looking XSLT transforms not working Input XML
<Web-inf>

    <A1>Val1</A1>
    <A1>Val1</A1>
    <A1>Val1</A1>

    <A1>Val2</A1>
    <A1>Val2</A1>
    <A1>Val2</A1>

   <B1>Hi</B1>

   <B1>Bye</B1>

  <C>DummyC</C>

  <D>DummyD</D>

</Web-inf>

I want to add  tag if it doesn't already exist with <B1> value as "Morning" and "Evening". If it exists i don't do anything. I have written following transform but the strange issue is that only the LATER one works and FIRST one is ignored completely. As a result only <B1>Evening</B1> is only inserted along with  tags. Is that a known issue? If yes, how to correct it?
<xsl:output method="xml" indent="yes" />

<xsl:template match="node()|@*">
    <xsl:copy>
        <xsl:apply-templates select="node()|@*"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="Web-inf[not(B[B1='Morning'])]/B[last()]">
    <xsl:copy-of select="*" />

         <B1>Morning</B1>

</xsl:template>

<xsl:template match="Web-inf[not(B[B1='Evening'])]/B[last()]">
    <xsl:copy-of select="*" />

         <B1>Evening</B1>

</xsl:template>

I want the O/P XML to be as below
Output.xml
<Web-inf>

    <A1>Val1</A1>
    <A1>Val1</A1>
    <A1>Val1</A1>

    <A1>Val2</A1>
    <A1>Val2</A1>
    <A1>Val2</A1>

   <B1>Hi</B1>

   <B1>Bye</B1>

   <B1>Morning</B1>

   <B1>Evening</B1>

  <C>DummyC</C>

  <D>DummyD</D>

</Web-inf>

A: For you given input XML, both templates for B[last()] will be matched. When two templates match an element with equal priority, this is considered an error. The XSLT processor will either flag the error, or ignore all but the last matching template.
In this case, it might simply be better to have single template matching B[last()] and have the other conditions as xsl:if statements in the template.
Try this XSLT
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:output method="xml" indent="yes" />

    <xsl:template match="node()|@*">
        <xsl:copy>
            <xsl:apply-templates select="node()|@*"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="Web-inf/B[last()]">
        <xsl:copy-of select="*" />
        <xsl:if test="not(../B[B1='Morning'])">

             <B1>Morning</B1>

        </xsl:if>
        <xsl:if test="not(../B[B1='Evening'])">

             <B1>Evening</B1>

        </xsl:if>
    </xsl:template>
</xsl:stylesheet>


text:
Q: React Axios Post Callback Trouble I am having major difficulties getting a callback using axios.post, to send a mail using nodeMailer. You see, the email gets sent, but it literally prints no console log at all.
This is my code:
 handleSubmit = async(e) => {
        e.preventDefault();

        const { email, fullname, number, subject, message } = this.state;

            await axios.post('/api/form', {
                email,
                fullname,
                number,
                subject,
                message
              })
              .then((info)=> {
                this.setState({email: '', fullName: '', subject: '', message: ''});
                Alert.success('Success.', {
                    position: 'top-right',
                    effect: 'jelly',
                    timeout: 4000
                });
                console.log(response);
              })
              .catch((e)=> {
                console.log(error);
              });
    }

And this is the other code in the server (index.js):
const express = require('express');
const bodyParser = require('body-parser');
const nodemailer = require('nodemailer');
const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use((request, response, next) => {
    response.header("Access-Control-Allow-Origin", "*");
    response.header("Access-Control-Allow-Headers", "Content-Type");
    next();
  });

if (process.env.NODE_ENV === 'production') {
    app.use(express.static('client/build'));

    const path = require('path');
    app.get('*', (req, res) => {
      res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'));
    });
  }

app.post('/api/form', (req, res) => {

    let transporter = nodemailer.createTransport({
        host: 'host',
        port: 465,
        secure: true, // true for 465, false for other ports
        auth: {
            user: '', // generated ethereal user
            pass: '' // generated ethereal password
        }
    });

    let mailOptions = {
        from: '"New message "<>', // sender address
        to: 'me', // list of receivers
        subject: 'New message', // Subject line
        html: 'Content here' // plain text body// html body
    };

    transporter.sendMail(mailOptions, (error, info) => {
        if (error) {
            return console.log(error);
        }
        console.log('Message sent: %s', info.messageId);
        // Preview only available when sending through an Ethereal account
        console.log('Preview URL: %s', nodemailer.getTestMessageUrl(info));

        // Message sent: <b658f8ca-6296-ccf4-8306-87d57a0b4321@example.com>
        // Preview URL: https://ethereal.email/message/WaQKMgKddxQDoou...
    });

});

const PORT = process.env.PORT || 3001;

app.listen(PORT, () => {
    console.log('Server running on port 3001.')
})

What seems to be the problem here? I have tried using 'axios.get' and 'axios.request', and this does at least output an error.

A: I use a Promise in order to wait for the response from the transporter and send it to the front end and be parsed by axios
const sendMail = () => new Promise((resolve, reject) => {
  transporter.sendMail(mailOptions, (error, info) => {
    if (error) {
      reject(error);
    } else {
      resolve(info);
    }
  });
})
.....other code.....
const status = await sendMail();
res.json({status})

LE

Based on your code this is how the /api/form route should look like
app.post('/api/form', async (req, res) => {

  const transporter = nodemailer.createTransport({
    host: 'host',
    port: 465,
    secure: true, // true for 465, false for other ports
    auth: {
      user: '', // generated ethereal user
      pass: '' // generated ethereal password
    },
  });

  const mailOptions = {
    from: '"New message "<>', // sender address
    to: 'me', // list of receivers
    subject: 'New message', // Subject line
    html: 'Content here' // plain text body// html body
  };

  const sendMail = () => new Promise((resolve, reject) => {
    transporter.sendMail(mailOptions, (error, info) => {
      if (error) {
        reject(error.message);
      } else {
        resolve(`Message sent: ${info.messageId}`);
      }
    });
  });

  const status = await sendMail();
  res.json({ status });

});


text:
Q: Error converting string to dict using json Im trying to read the serial port (using arduino) and then convert the input to a dictionary, I have generated the string in the arduino code so that it matches what I could find what it should look like according to other threads.
receive_string = ser.readline().decode('utf-8', 'replace')
print(receive_string)

Gives: {'value_left': 10, 'target_left': 20, 'u_left': 10.30, 'value_right': 11, 'target_right': 21, 'u_right': 11.30}
However when I try to convert it to a dict using json.loads:
data = json.loads(receive_string)

I get the error:
Traceback (most recent call last):
  File "send_and_rcv_int.py", line 36, in <module>
    data = json.loads(receive_string)
  File "/Users/jakobvinkas/opt/anaconda3/lib/python3.8/json/__init__.py", line 357, in loads
    return _default_decoder.decode(s)
  File "/Users/jakobvinkas/opt/anaconda3/lib/python3.8/json/decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/Users/jakobvinkas/opt/anaconda3/lib/python3.8/json/decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

What am I missing?
I have tried to not decode the readline() and to use " instaed of ' but nothing works.
———————— edit ————————
What worked was sort of an ugly fix:
receive_string = ser.readline().decode('utf-8', 'replace')
    try:
        data = json.loads(receive_string)
        print(data)
    except:
        data = {}

The problem was that the first ser.readline() return nothing for some reason, causing the error.

A: receive_string is type string so you need to convert string to dict. Try this :
import json
import ast
out="{'value_left': 10, 'target_left': 20, 'u_left': 10.30, 'value_right': 11, 'target_right': 21, 'u_right': 11.30}" # given dict string
res = ast.literal_eval(out) # converting dict string to dict
print(json.dumps(res)) # converting dict to json

If this does not work then check : How convert a JSON string to Dictionary in Python?

A: Try to use eval() instead of json.loads()
data = eval(receive_string)


text:
Q: C# Close processes minimized to tray in a graceful way? I have an application that has can display a window using a Form. The form is only shown if the application is run using a -debug flag, otherwise it is only shown in tray.
var form = new Form();
if(DebugMode)
    form.Show();

The application listens to CloseMainWindow() when run in debug mode, as the form is shown.
How can I make the application also listen to CloseMainWindow() without showing it? I don't want the user to be able to interact with the form if not in debug mode.
I've tried several approaches, like displaying the window but setting the size to 0. This shows a small form, i.e. not hidden.
if (!DebugMode)
{
    form.Show();
    form.Size = new Size(0, 0);
}

Also showing it, and then hiding it does not work:
if (!DebugMode)
{
    form.Show();
    form.Hide();
}

Showing it, but started minimized and not shown in taskbar does not work either:
if (!DebugMode)
{
    form.Show();
    form.WindowState = FormWindowState.Minimized;
    form.ShowInTaskbar = false;
}

Am I missing something really obvious here, or is it not possible to close processes minimized to tray in a graceful way?

A: If i've understood the problem correctly, you want to completely hide the form when not in debug mode (i.e. the window is not seen anywhere but in the task manager) and when someone kills the process via task manager, you want to execute some code for clean-up or just get notified.
Basing my solution on this assumption, the following code should work
 public static bool DebugMode = false;

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            var form = new Form1();
            form.Load += (s, e) =>
                             {
                                 if (!DebugMode)
                                 {
                                     form.Opacity = 0;
                                     form.ShowInTaskbar = false;
                                 }
                             };

            form.FormClosing += (s, e) =>
                                    {
                                        // Breakpoint hits
                                    };

            Application.Run(form);
        }

A: I'm not sure you can do it through Process.CloseMainWindow(). Processes with no visible main window, I seem to recall, have MainWindowHandle set to IntPtr.Zero.
You need some kind of workaround. My advice is to keep track manually of the MainWindow Handles yourself:
static void Main()
{
     ...
     MainWindow mainWindow = new MainWindow();
     [HandleRepository] = mainWindow.Handle;
     Application.Run(mainWindow);
}

Then when you want to close the process, do it with a workaround:
public void EndProcess()
{
     Form mainWindow= (MainWindow)Form.FromHandle([HandleRepository]);
     mainWindow.Close();
}

Might not be the most elegant solution but it should work (haven't tested it)


text:
Q: Docker postgres image: no pg_hba.conf entry for host I have a Docker image for DB (postgres is installed) and I try to run it but I get the following:

db             | 2018-11-27 08:29:28.849 UTC [2808] FATAL:  no
  pg_hba.conf entry for host "172.x.x.x", user "postgres", database
  "postgres", SSL off

I tried the following:

*

*To change the IP and put my current machine's ip

*When setting up Postgres: echo -e "host all all 0.0.0.0/0 trust" I put that

None of those work.

A: I ran into the same problem getting my application container to talk to my postgres container. I fixed this with three steps:

*

*define the network ip address range for the docker network

# +----------------------+
# |  docker-compose.yml  |
# +----------------------+
networks:
  my_docker_network:
    driver: bridge
    ipam:
      config:
        - subnet: 10.5.0.0/16

*whitelist the same network ip address range in the postgres pg_hba.conf file

# +---------------+
# |  pg_hba.conf  |
# +---------------+
# TYPE  DATABASE        USER            ADDRESS                 METHOD
# IPv4 local connections:
host    all             all             127.0.0.1/32            trust
host    all             all             10.5.0.0/16             trust

I used trust to avoid authentication hassles, but you could specify md5, cert, or any other valid authentication method.

*allow postgres to listen to external hosts in the postgresql.conf file

# +-------------------+
# |  postgresql.conf  |
# +-------------------+
# - Connection Settings -
listen_addresses = '*'          # what IP address(es) to listen on;


text:
Q: Import from a cdn.js module I'm a beginner in javascript and so i don't have a lot of knowledges about good practisies and possibilities.
The problem
I want to use this pdf library to edit some pdf files. But i can't manage to import the library without nodejs or something else.
What i tried
In my html file i have the scripts imports statements :
<script src="https://cdn.jsdelivr.net/npm/pdf-lib/dist/pdf-lib.js"></script>
<script type="module" src="./assets/js/Client.js"></script>

The second line is the import of my script in which i want to use the pdf library.
In my script "Client.js" i have the following code lines:
import { PDFDocument } from 'pdf-lib'

mypdf = window.PDFDocument.load(file)

File is an imported file thank to an event.dataTransfer.
I'm currently using the live server extension of visual studio code as environment.
When i load my page on the browser at

http://127.0.0.1:5500/Client.html

I get the error :

Uncaught TypeError: Failed to resolve module specifier "pdf-lib". Relative references must start with either "/", "./", or "../".

I understand the error but it's not "a relative reference" in my case and i don't know what to do with this...
I made some researches of how to get it works with cdn js but every solutions i found aren't working


text:
Q: JavaScript: Uncaught SyntaxError: missing ) after argument list When I try to pass a string as an argument in the following function, I get the Uncaught SyntaxError: missing ) after argument list error. It works fine when passing integers though. I am confused because I read a string must be passed as the argument, and not an integer.
HTML:
r.title = "The large item"
counter = <integer>

<% @items.each do |r| %>

Title: <%= r.title %>

Price: <%= r.price %>

Description: <%= r.description %>

  <p style="color:blue;" class="room_<%= counter %>" onclick='addItemToCart(<%= r.title %>, <%= counter %>)'>Select Item

<% end %>

When I pass r.id in place of r.title, the code works.
JavaScript:

A: I think you're missing quotes around the string. Try this:
<p style="color:blue;" class="room_<%= counter %>"
   onclick='addItemToCart("<%= r.title %>", <%= counter %>)'>Select Item

EDIT
To understand the issue, try looking at the HTML it outputs. I imagine you'll see something like this:

Select Item

Hopefully, the missing quotes are obvious from that output.

A: I agree with @smarx, but I think this is a typical sample of mixing HTML, Javascript and Ruby snippet together, which should always be avoided.
The better way is to at least separate Ruby snippet from Javascript.
ERB
<p style="color:blue;" class="room_<%= counter %>"
  data-title="<%= r.title %>"
  data-counter="<%= counter %>"
  onclick='addItemToCart(this)'>Select Item

Javascript
function addItemToCart(element) {
  var title = element.dataset.title;
  var counter = element.dataset.counter;
  // ...
}

You can see that I added two data-* attributes to the HTML, and read them in the Javascript. This seems a little verbose, but it's less spaghetti, and it clearly separates the code running on server (Ruby) from the code running on browsers (Javascript).
P.S. If you're using jQuery, I would strongly recommend NOT to use onclick attribute, because it requires you to define global functions. Use $(...).click(fn) or $(...).on('click', fn) instead, because it allows anonymous non-global functions.

A: With php and js, I had the same error:

Uncaught SyntaxError: missing ) after argument list

1. Replace null values with empty string
In php, I had to add  ?? '' after each value of a variable, the first time that variable is used in the code:
var new_value = $("#update").find(  'input[name="'+
                                    x['x_name']+
                                    '_x_value"]').val() ?? '';
if(x['x_value'] ?? '' != new_value) {
    ...

In javascript, you would replace null with "" like
(value === null) ? "" : value

2. User rights
Also check your user rights if you use a back-end with permissions. My user had only read rights. Screenshots from DBeaver:

That can lead to an empty response from the sql db in my case. Not in your case, but it may help someone else.
3. Check for too many brackets
I also got this error when I had a double closing } bracket where only one was needed.
4. Official guide for the error
If that does not fix it, have a look at the "Learn More" link in the error message: SyntaxError: missing ) after argument list might help.


text:
Q: Calculate rolling 180 days average We have a table with columns TXN_DATE and NO_OF_TXNS. Below is sample data:
TXN_DATE           NO_OF_TXNS
25-AUG-19             0
26-AUG-19             1000
27-AUG-19             1500
28-AUG-19             1800
29-AUG-19             1100
30-AUG-19             1400

We want to calculate the rolling average of transactions for last 180 days (excluding weekends). If it is 1st day, average will be equal to number of transactions on that day and if it is 2nd day it will be equal to (n1+n2)/2 and 3rd day then it will be equal to (n1+n2+n3)/3 and so on.
Any help will be highly appreciated.

A: You can use an analytic function with a RANGE window. You can also use TXN_DATE - TRUNC( TXN_DATE, 'IW' ) to find the number of days of the week since the start of the ISO week (which always start on Monday) and means that your query is not tied to a specific language or session parameters (which each user can change within their session and change the language to TO_CHAR does not give the expected output for days of the week).
SELECT TXN_DATE,
       AVG( NO_OF_TXNS ) OVER (
         ORDER BY TXN_DATE
         RANGE BETWEEN 180 PRECEDING
               AND     0   PRECEDING
       ) AS avg_no_of_txns
FROM   table_name
WHERE  NOT ( TXN_DATE - TRUNC( TXN_DATE, 'IW' ) BETWEEN 5 AND 7 );

If you want to restrict it to the last 180 days worth of data then you need to find the averages and then filter afterwards:
SELECT *
FROM   (
  SELECT TXN_DATE,
         AVG( NO_OF_TXNS ) OVER (
           ORDER BY TXN_DATE
           RANGE BETWEEN 180 PRECEDING
                 AND     0   PRECEDING
         ) AS avg_no_of_txns
  FROM   table_name
  WHERE  NOT ( TXN_DATE - TRUNC( TXN_DATE, 'IW' ) BETWEEN 5 AND 7 )
)
WHERE TXN_DATE >= TRUNC( SYSDATE ) - INTERVAL '180' DAY(3);

db<>fiddle

A: You may try this. First you need to filter out the weekends from the list, since in your question you want to find the record of last 180 days excluding weekends. To get the days name of date we use TO_CHAR, and for making sure that it will read as language english we'll add 'NLS_DATE_LANGUAGE=English'.
Once you have your list then you can simply filter your 180 records for calculation. For this you may have several methods like top, row_number, limit etc. I am using row_number. So final sample code will be like this.
with record ( SLNO, TXN_DATE, NO_OF_TXNS ) AS
(
     SELECT ROW_NUMBER() OVER (ORDER BY TXN_DATE DESC) AS SLNO,
            TXN_DATE,
            NO_OF_TXNS
     FROM   TABLE
     WHERE  TO_CHAR(TXN_DATE,'DY', 'NLS_DATE_LANGUAGE=English') NOT IN ('SAT', 'SUN')
)
select TXN_DATE,
       NO_OF_TXNS,
       (select avg(t.NO_OF_TXNS) from record t where t.TXN_DATE<=t1.TXN_DATE
and t.SLNO<180) as Sum
from record t1

Thanks to @WernfriedDomscheit for improvement.

A: You can use analytical function and I would avoid using row preeciding operator as it will not give exact result in case entry is missing for one or more days so it is better to use WHERE clause for fetching last 180 days.
SELECT TXN_DATE,
       AVG(NO_OF_TXNS) OVER (ORDER BY TXN_DATE) AS ROLLING_AVERAGE
  FROM YOUR_TABLE
 WHERE TO_CHAR(TXN_DATE,'DY') NOT IN ('SAT','SUN')
   AND TRUNC(TXN_DATE) >= TRUNC(SYSDATE) - 180

Cheers!!


text:
Q: MySQL - Show only most recent Status of Product Having a brain fart here... I am pulling proper data, however one of my columns isn't pulling the most accurate recent information.
I am pulling two tables together to get information from 'client_educational' and 'client_personal'. The goal here is to get a list of all people who have taken a certain course more than 6 months ago, and show their most recent status: paid, exp-cert (expired certification), pd-cert (paid and certified), void, etc etc
client_no    name    email           phone      recent_order_date    status

500000       Joe     joe@mail.com    555-5555   2017-01-02           Paid
500001       Mary    mary@mail.com   555-5555   2017-02-02           exp-cert
500002       Jane    jane@mail.com   555-5555   2017-04-02           pd-cert
500003       Jack    jack@mail.com   555-5555   2017-05-02           void
500004       John    john@mail.com   555-5555   2018-01-02           pd-cert

My query:
SELECT
client_personal.client_no,client_personal.name,client_personal.email,client_personal.phone, max(order_date) as recent_order_date, client_educational.status
FROM client_personal
join client_educational client_educational on client_personal.client_no = client_educational.client_no
WHERE product IN ('Product1', 'Product2', 'Product3', 'Product4', 'Product5', 'Product6')
group by client_no
having recent_order_date < DATE_SUB(CURDATE(),INTERVAL 6 Month);

My output is good, however it is not displaying the most recent "status". The goal is to just the most recent "status" for the product listed above. The product above is one product, just different name variations in their system.
Is there a way to do this??

A: If I understand correctly, you want people whose most recent of these courses is more than 6 months ago and then you want their most recent overall status.
You can do this using a MySQL group_concat()/substring_index() hack:
select cp.client_no, cp.name, cp.email, cp.phone,
       max(case when ce.product in ('Product1', 'Product2', 'Product3', 'Product4', 'Product5', 'Product6') then recent_order_date end) as max_date,
       substring_index(group_concat(ce.status order by date desc), ',', 1) as most_recent_status
from client_personal cp join
     client_educational ce
     on cp.client_no = ce.client_no
group by client_no
having max_date < DATE_SUB(CURDATE(), INTERVAL 6 Month);


text:
Q: How to track down a Blue Screen of Death triggered by an (usermode) application We have a .Net application consisting of mixed managed and unmanaged code.  We have a number of reports of users getting BSOD while using our application.  These blue screens happen on different versions of Windows.  Mostly XP but one user claims it happens on Windows 7.  Some users see it happening when doing one thing, other see it happening when doing something completely different.  Of course, we cannot reproduce the problem.
Needless to say, I'm stumped.  A user mode application shouldn't be able to blue screen the OS so we are running into a bug in a common kernel space application, perhaps buggy antivirus software?
Does anyone have any tips on how to track something like this down?  We don't have access to a computer where this is happening so we wouldn't be able to hook up a kernel debugger or anything like that.

A: https://serverfault.com/questions/238/how-to-diagnose-a-windows-blue-screen

A: About the only thing you can do is convince users to send you data:

*

*Crash dumps.  Post a walkthru on your website showing how to enable full/mini dumps and where to find them.  Here's a KB article with the gory details -- probably want to simplify this with screenshots & so on.

*Installed software.  Best to find a tool that collects this info for them; humans aren't especially reliable or thorough.  WinAudit looks good.

*Installed hardware & drivers.  (ditto)

A: Can you get a copy of the crash/mini dump?
If so you can use WinDbg and SOS to figure out where the code is at when it blows up.
Tess Fernandez has a good blog on managed debugging with low level tools.


text:
Q: How to easily clean repeat rows in a dataframe in R? I am working with the spotifyR package, and pulling artist information for Taylor Swift. I am trying to compare all of her albums, but some albums are listed multiple times in the dataframe.
I have tried the distinct() function, but that does not remove all the repeats for some reason. I have also tried going into the data frame and finding the repeat rows that I can delete with ts <- ts[-c(31:60), ]. However, when I try to delete the next set of repeat rows, it is offset by a certain number of rows. For example: ts <- ts[-c(108:124), ] does not delete rows 108 - 124. It deletes 125 - 141.
How can I easily delete the repeat rows (with a for loop maybe? not sure how to approach) or make sure that when I am manually deleting rows, it does not get offset like it currently is?


text:
Q: CSS not loading when I call a div to print I have a div that I would like to print, but when I call it, the CSS doesn't apply. I got the JS from here. It's supposed to print just the table, which it does, but It doesn't apply the styles for the table, and it ends up unformatted.
Expected result

Actual result

My code

function printDiv(divName) {
  var printContents = document.getElementById(divName).innerHTML;
  var originalContents = document.body.innerHTML;

  document.body.innerHTML = printContents;

  window.print();

  document.body.innerHTML = originalContents;
}
.table-container {
  display: grid;
  grid-template-columns: auto;
  justify-content: center;
}

table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
  background-color: white;
  color: black;
  border: 2px solid black;
}

td,
th {
  border: 1px solid black;
  padding: 10px 20px;
}

th {
  font-size: 20px;
}

td {
  font-size: 15px;
}

tr:nth-child(even) {
  background-color: #dddddd;
}

.total1 {
  border: none;
}

.pc-border-title {
  text-align: center;
}

.intro-heading {
  font-size: 25px;
  text-align: center;
  color: #ffffff;
}

.pcbuilder-link {
  color: #cecece;
}

.pcbuilder-link:hover {
  color: #adadad;
}

.table-heading {
  font-size: 50px;
  text-align: center;
  color: #000000;
  margin-bottom: 10px;
  margin-top: 0px;
  border: 2px solid #000000;
}

#printableArea {
  padding: 10px;
  background-color: #ffffff;
  border-radius: 10px;
}

.table-container {
  display: grid;
  grid-template-columns: auto;
  justify-content: center;
}

table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
  background-color: white;
  color: black;
  border: 2px solid black;
}

td,
th {
  border: 1px solid black;
  padding: 10px 20px;
}

th {
  font-size: 20px;
}

td {
  font-size: 15px;
}

tr:nth-child(even) {
  background-color: #dddddd;
}

.total1 {
  border: none;
}

.pc-border-title {
  text-align: center;
}

.intro-heading {
  font-size: 25px;
  text-align: center;
  color: #ffffff;
}

.pcbuilder-link {
  color: #cecece;
}

.pcbuilder-link:hover {
  color: #adadad;
}

.table-heading {
  font-size: 50px;
  text-align: center;
  color: #000000;
  margin-bottom: 10px;
  margin-top: 0px;
  border: 2px solid #000000;
}

#printableArea {
  padding: 10px;
  background-color: #ffffff;
  border-radius: 10px;
}

My PC Setup

      Part
      Name
      Price
      Notes

      Processor
      AMD Ryzen 9 7950X

        747

        32-Thread
16-Core
4.5GHz

      Motherboard
      GIGABYTE X670E AORme Master

        542.84
      Socket: AM5

RAM Slots: 4
Chipset: AMD X670E

      CPU Cooler
      Cooler Master Hyper 212 EVO V2

        90
      Side Panel: Tempered Glass, Steel
Cabinet Type: ATX Full Tower

        Case
        NZXT H510 - CA-H510B-B1

          1,584.90
        Memory: 24GB

Chipset: GeForce RTX 3090 Ti
Interface: PCIe 4.0 x16

        Graphics card
        Nvidia RTX 3090 TI Founders Edition

          51.44
        Fan Speed: 650RPM-1800RPM

Noise Level: 8-27dBA

        RAM
        G.Skill Trident Z5 RGB Series 32GB 2 x 16GB (x2)

          564.42
        RAM Size: 64GB

RAM Type: DDR5

        Storage (SSD)
        Samsung EVO 970 1TB

          167.99
        Capacity: 1 TB

Type: SSD
Cache Memory: 1024 MB

        Storage (HDD)
        Seagate BarraCuda 2TB

          53.49
        Capacity: 2 TB

Type: HDD
RPM: 7200 RPM
Interface: SATA 6 Gb/s
Cache Memory: 256 MB

        Case Cooler
        ARCTIC P12

          5.73
        Fan RPM: 1800 RPM

Airflow: 56.3 CFM
Noise Level: N/A

        Power Supply
        Thermaltake Smart 430W

          98.95
        Power: 430W

Efficiency: 80+

        Monitor
        Acer SB220Q Bi 21.5

          170
        Screen Size: 21.5"

Response Time: 4ms
Resolution: 1920 x 1080
Refresh Rate: 75 Hz

        Total

          4,077

<input type="button" onclick="printDiv('printableArea')" value="Print your setup" />

How can I fix this? Thanks

A: I faced similar problem while printing table using similar javascript function.  You have to provide all css to the print window as well. I am pasting my code here.  You will have to modify that to suit your requirements.
    function PrintElem(elem)
    {
        var orgPrint = document.getElementById(elem).innerHTML;
        document.querySelectorAll(".no-print").forEach(el => el.remove()); // removes some elements from the table that are not to be pronted
        var toPrint = document.getElementById(elem).innerHTML;
        var mywindow = window.open('', 'PRINT', 'height=400,width=600');

        mywindow.document.write('<title>My Title</title>');
        mywindow.document.write('');

        mywindow.document.write('');
        mywindow.document.write('

');
        mywindow.document.write(toPrint);
        mywindow.document.write('');

        mywindow.document.close(); // necessary for IE >= 10
        mywindow.focus(); // necessary for IE >= 10*/

        mywindow.print();
        mywindow.close();

        document.getElementById(elem).innerHTML = orgPrint; // restores the table as is

        return true;
    }


text:
Q: How to find commits by a specific user in Git? Our project uses Git as the version control system and recently I needed to review someone's commits. How can I see a list of commits made by a specific user?

A: Try this:
git log --author=<name or email>

or pass the same option to gitk, or if already in gitk, go to view > new view, and fill in the appropriate field. The name doesn't have to be exact; it's matched as a regex (a substring, in the trivial case) against the author field.

A: git log --author=<pattern> will show the commit log filtered for a particular author. (--committer can be used for committer if the distinction is necessary).
http://git-scm.com/docs/git-log


text:
Q: Indesign 2020 ScriptUI add text frame I have a problem with a script for Indesign 2020.
I am not a programmer and don't know javascript (I just created some simple script).
I want to create a simple panel with a button that add a textframe, but doesn't seems to work.
Here's the code
    var document = app.activeDocument;
    document.viewPreferences.horizontalMeasurementUnits = MeasurementUnits.MILLIMETERS;
    document.viewPreferences.verticalMeasurementUnits = MeasurementUnits.MILLIMETERS;
    app.viewPreferences.rulerOrigin = RulerOrigin.SPREAD_ORIGIN;
    app.activeDocument.viewPreferences.rulerOrigin = RulerOrigin.SPREAD_ORIGIN;
    app.activeDocument.zeroPoint = [0,0];
    var Labelpanel = new Window("dialog");
    Labelpanel.text = "Printer";
    Labelpanel.orientation = "column";
    Labelpanel.alignChildren = ["center","top"];
    Labelpanel.spacing = 10;
    Labelpanel.margins = 16;
    var Button1 = Labelpanel.add("button", undefined, undefined, {name: "Button 1"});
    Button1.text = "Magenta 1";
    Button1.onClick =  function() {
        var Label = document.pages[0].textFrames.add();
        Label.properties = {
            geometricBounds : [ 25,284.5,15,226.5 ],
            contents : "1234_Mag1"
            }
        Label.paragraphs[0].appliedFont = app.fonts.item("Arial");
        Label.paragraphs[0].pointSize = "30";
        Label.paragraphs[0].justification = Justification.RIGHT_ALIGN;
        Labelpanel.close();
        }
    Labelpanel.show();

The code in the button normally works, but in ScriptUI it does nothing.
Can someone tell me what am I doing wrong?

A: In your case the script will work (I'm not sure about your goal, though) if you add this line:
#targetengine session

at the start of the code.
And change "dialog" with "palette" here:
var Labelpanel = new Window("palette");

The problem is a dialog window can't change a document until the dialog will be closed.
Not like a palette that has access to documents always.
Your script can be rewritten in order to use a dialog window instead of palette. But it will need to change more than just two lines.
Update
Here is the example how it can be done with a dialog window:
// set the dialog window
var labelDialog = new Window("dialog");
labelDialog.text = "Printer";
labelDialog.orientation = "column";
labelDialog.alignChildren = ["center","top"];
labelDialog.spacing = 10;
labelDialog.margins = 16;

// set a variable that we will convey to the main function
var contents = '';

// a couple buttons
var button1 = labelDialog.add("button", undefined, undefined, {name: "Button 1"});
button1.text = "Magenta 1";
var button2 = labelDialog.add("button", undefined, undefined, {name: "Button 2"});
button2.text = "Magenta 2";

// if click --> change the variable an close the dialog
button1.onClick = function() {contents = '1234_Mag1'; labelDialog.close()};
button2.onClick = function() {contents = '5678_Mag2'; labelDialog.close()};

labelDialog.show(); // show the dialog

// if the variable is not empty --> run the main function
if (contents != '') main(contents);

// the main function, get the variable and does the work
function main(contents) {

    app.viewPreferences.rulerOrigin = RulerOrigin.SPREAD_ORIGIN;
    app.activeDocument.viewPreferences.rulerOrigin = RulerOrigin.SPREAD_ORIGIN;
    app.activeDocument.zeroPoint = [0,0];

    var document = app.activeDocument;
    document.viewPreferences.horizontalMeasurementUnits = MeasurementUnits.MILLIMETERS;
    document.viewPreferences.verticalMeasurementUnits = MeasurementUnits.MILLIMETERS;

    var label = document.pages[0].textFrames.add();
    label.properties = {
        geometricBounds: [ 25,284.5,15,226.5 ],
        contents: contents // <-- our variable goes here
    }
    label.paragraphs[0].appliedFont = app.fonts.item("Arial");
    label.paragraphs[0].pointSize = "30";
    label.paragraphs[0].justification = Justification.RIGHT_ALIGN;

}

I've made two buttons. I suspect it would be your next question: "How to add more buttons?"
The main point: A dialog window should be closed before you try to change a document. A palette should not. This 'subtle difference' changes the algorithm significantly.


text:
Q: executing nested 'while' loops within promises I am trying to create some nested 'while' loops within my promises. I start to run into trouble in my innerFunc when I am executing log.asyncCall().then(...) my IDE is telling me that right away, the arrow function will jump straight to the .then() containing return innerFunc() without even going into the if statement. I think the race conditions are not executing in the order I want them to.
Summary of what I am trying to achieve:
According to outerFunc I want to perform innerFunc this 3 times.
What innerFunc does call .asyncCall() over and over again as long as log is NOT null. If innerFunc cannot produce log, exit the 'while' loop.
I'm also having trouble finding a good way to debug promises. I am currently using the debug feature with WebStorm.
var i = 0
const outerFunc = () => {
  return new Promise(resolve => {
    if (i < 3) {
      i++
      const innerFunc = () => {
        return new Promise(resolve => {
          return log.asyncCall().then(lg => {
            if (lg) {
              // some logic
            } else {
              resolve()
            }
          }).then(() => {
            // continue iterating innerFunc()
            return innerFunc();
          });
        })
      };
      // first iteration innerFunc()
      return innerFunc().then(() => {
        // once innerFunc() is complete, reiterate outerFunc()
        return outerFunc();
      });
    } else {
      resolve();
    }
  });
}

A: You are using a Promise anti-pattern, since you're wrapping a promise in another promise.
I would strongly advise taking innerFunc out of the inner scope, and rewriting it thus:
const doLogging = () => {
    return log.asyncCall().then(result => {
        if (result) {
            // do stuff
            ...
            return doLogging();
        }
    });
}

There's no need for an else branch - the inner arrow function will implicitly return undefined which will then be wrapped by .then into a Promise.
You then want to run this count times:
const repeatPromise = (f, count) => {
    if (count > 0) {
        return f().then(() => repeatPromise(f, count - 1));
    } else {
        return Promise.resolve();
    }
}

const outerFunc = () => repeatPromise(doLogging, 3);

In this function the else branch is necessary to ensure that the final result is always a Promise.
(NB: as written the repeatPromise function won't work properly if the passed function doesn't return a Promise)


text:
Q: ¿como puedo poner un temporizador en ensamblador x86? Hola alguien que me ayude y me diga que interrupción puedo usar en ensamblador que haga lo mismo que hace la función sleep de c++, por favor.

A: fue investigar , y encontre una funccion de la interupcion 15h   , que hace esperar por una cantidad de microsegundos ,que es para escojer, hasta la instruccion que viene   .
la funccion es la 86h  , como um microsegundo es 1/1 000 000 de un segundo , es preciso mas espacio para armazenar un segundo son necessarios registros cx y dx ,  la cantidad en microsegundos debe ser anotada de la seguente forma :

escribi un pequeño programa para probar la func 86h -->
model small   ; pequeño
.stack 100  ; 100 bytes para stack
.data
a db 'a'
b db 'b'
c  db 'c'
d  db 'd'

  e  db 'e'

    f  db 'f'

      g  db 'g'

         h  db 'h'

            i  db 'i'

               j  db 'j'

                  k  db 'k'

                     l  db 'l'

                     dollar  db '$'   ;final de la cadena

.code
inicio:
mov ax,@data
mov ds,ax     ;conectar el ds con segmento de la cadena
lea si, a  ;direccion del inicio de la cadena de caracteres para imprimir en el si

loop_msg:   ;imprimir un caracter de la cadena , esperar un segundo , imprimir proximo , hasta llegar al dollar
cmp [si],'$'   ; caracter de dollar ?
je exit  ;salir si es

mov al,[si]
mov ah,0eh  ; funcion del bios para imprimir un caracter
int 10h  ; interupcion bios
mov ah,86h  ; la func que hace esperar
mov cx,000Fh  ; en este caso un millon de micro segundos
mov dx,4240h
int 15h
inc   si    ;incrementar la posicion y imprimir la letra que viene
jmp loop_msg
exit:
mov ax,4c00h
int 21h      ;volver al DOS
end inicio
Te agradesco por crear este articulo , al contrario yo no saberia como hacer el efecto animacion grafica en la pantalla y aprovechar el timer   <3   =D


text:
Q: App crashes in Branch.io debug mode I installed Branch.io sdk in application but it keeps crashing once I enter debug mode.
Here is initialization:
public void onCreate() {
    ...
    Branch.getAutoInstance(this)
    ...
}

I successfully enter debug mode using 4 fingers like it is said in Branch.io documentation. However in a while (10-15sec) it starts posting a lot of post request to Branch.io resulting in app crash.
Here is post request sent when I enter debug mode:
Post value = {
"device_fingerprint_id": "xxxxx",
"device_name": "Nexus 7",
"os": "Android",
"os_version": 21,
"model": "Nexus 7",
"is_simulator": false,
"session_id": "186013940411551370",
"identity_id": "185720730762103937",
"sdk": "android1.9.0",
"retryNumber": 0,
"branch_key": "xxxxxxxx"
}

The response:
    returned {}
    ======= Connected to Branch Remote Debugger =======

After a while it starts firing events that results in app restart or even crash
Post value = {
"device_fingerprint_id": "xxxx",
"session_id": "186013940411551370",
"identity_id": "185720730762103937",
"log": "BranchSDK\tposting to https:\/\/api.branch.io\/v1\/debug\/log",
"sdk": "android1.9.0",
"retryNumber": 0,
"branch_key": "xxxxxxx"
}

A: This could be for a variety of reasons. Branch recently discovered that if a request was sent and the response was malformed, it could expose an NPE. More information here: https://github.com/BranchMetrics/Android-Deferred-Deep-Linking-SDK/pull/155
You could potentially download from source, or wait till a new version is released (within the next few days). You could also try emailing support@branch.io.


text:
Q: Closed Form Solution for Optimization Problem over the Space of Rigid Transforms Is there a closed form solution to this constrained optimization problem:
\begin{equation}
\min_{R \in SO(3),\, \mathbf t \in \mathbb R^3} = \sum_{i = 1}^N \| M_i(R \mathbf p_i + \mathbf t) \|^2,
\end{equation}
where $M_i$ are given $3 \times 3$ matrices and $\mathbf p_i \in \mathbb R^3$ are given vectors.
To put it in words, I am interested in the rigid transform, given by a $3 \times 3$ rotation matrix $R$ and a translation vector $\mathbf t \in \mathbb R^3$, which minimize the above expression.
It is also fine to minimize the norms, instead of the squared norms, if it makes it any easier.

A: This is a bit too long for a comment, so I'll add this as an `answer'; you can decide for yourself whether this does anything towards answering your question. I should reiterate that I am by no means an expert in this area (so do call me out if you think I've made a mistake), but I think the steps here are:

*

*Find the derivative of the function $f: \mathbb{R}^{4\times 4}\to \mathbb{R}\;,\; A\mapsto \sum_i\left|\left( \begin{array}{cc} M_i & 0 \\ 0 & 1 \end{array}\right) A \left( \begin{array}{c} p_i \\ 1 \end{array}\right)\right|^2$. I think this is given by
$$
Df(A)B = 2\sum_i \left(
\left( \begin{array}{cc} M_i & 0 \\ 0 & 1 \end{array}\right) A \left( \begin{array}{c} p_i \\ 1 \end{array}\right), \left( \begin{array}{cc} M_i & 0 \\ 0 & 1 \end{array}\right) B \left( \begin{array}{c} p_i \\ 1 \end{array}\right)
\right)
$$
for $A,B\in \mathbb{R}^{4\times 4}$, where $(.,.)$ is the usual dot product on $\mathbb{R}^4$.

*Identify the tangent spaces $(T_AX)_{A\in X}$ of the manifold $X$ over which we're optimising. In our case, $X = SE(3)$, and (I think):
$$
T_AX = \left\{ A \left( \begin{array}{cc} \widehat{\omega} & \tau \\ 0 & 0  \end{array}\right) : \omega, \tau \in \mathbb{R}^3\right\}\;\;\mbox{with}\;\; \widehat{\omega} = \left(
\begin{array}{ccc}
0 & -\omega_3 & \omega_2
\\
\omega_3 & 0 & -\omega_1
\\
-\omega_2 & \omega_1 & 0
\end{array}
\right).
$$

*Observe (or believe, or neither) that if $A\in X$ is a maximum or minimum of $f$ then $Df(A)[T_AX]=\{0\}$. Letting $df_A$ be the restriction of $Df(A)$ to $T_AX$, this is the same as having $df_A = 0$ at extrema (I mention this just because derivatives being zero at extrema is a familiar idea from single variable calculus).

*Combine items 1., 2. and 3. to see that, at an extremum $A$ of $f$ on $X$, one must have
$$
0=\sum_i \left(
\left( \begin{array}{cc} M_i & 0 \\ 0 & 1 \end{array}\right) A \left( \begin{array}{c} p_i \\ 1 \end{array}\right), \left( \begin{array}{cc} M_i & 0 \\ 0 & 1 \end{array}\right) A \left( \begin{array}{c} (\omega \times p_i) +\tau \\ 0 \end{array}\right)
\right)
$$
for all $\omega, \tau \in \mathbb{R}^3$, where $\times$ is the usual cross product in $\mathbb{R}^3$.

*Substitute $A=\left( \begin{array}{cc} R & t \\ 0 & 1 \end{array}\right)$ to get an equation satisfied by $R$ and $t$ at extrema. Unless I've bodged the algebra, I think this ends up being
$$
\sum_i M_i^TM_i (Rp_i +t ) = 0
$$

*Given the special form of your $M_i (= \widehat{u_i}^2)$, we have $M_i^TM_i = -M_i$, so this is just the same as
$$
\sum_i M_i(Rp_i + t) = 0
$$
at any minimising/maximising $R$ and $t$. This condition is necessary but not sufficient (again, assuming there isn't a mistake in my algebra). There may be cases where this condition restricts your choice of $R$ and $t$ to just one, but I don't think this is the usual case. It seems like there may even be no minimising $R$ and $t$ for some choices of $p_i$ and $u_i$ if the calculations above are correct ($SE(3)$ isn't compact, so this isn't too much of a red flag).

Do you have a reason to believe that your minimum can always be attained?
If you do decide to go down the numerical route, you might want to look at the paper Minimization on the Lie Group SO(3) and Related Manifolds of Taylor and Kreigman; in my experience, using local exponential parameterisations of your manifold is almost always better than coordinate-free methods (accumulation of numerical errors can mean your matrices stop being in the group you want after a few million SLERPs). What experience I have in this area comes from the direction of minimum-volume bounding box computation; if you're able to give a bit more background to your problem, I might be able to suggest some more bespoke references (obviously don't reveal anything which could be considered 'commercially sensitive').


text:
Q: ColdFusion 2021 - How to handle SAML/SSO with multiple applications on same server We have a server with about a dozen small applications each in their own subfolder of the server (//URL/app1, //URL/app2, etc).
I've got the basic SSO authentication round trip working. I set up my account with my IDP and have the response set to go to a common landing page (ACS URL). Since the landing page is currently shared with all the apps, it is in a separate folder distinct from the apps (//URL/sso/acsLandingPage.cfm)
I'm now working on my first app. I can detect the user is not logged in so I do a initSAMLAuthRequest(idp, sp, relayState: "CALLING_PAGE_URL") and that goes out, authenticates, then returns to the landing page.
But how do I redirect back to my target application and tell it the user is authenticated?
If I just do a <cflocation url="CALLING_PAGE_URL" /> the original app doesn't know about the SAML request.
Is there a function that I can call in the original app that will tell if the current browser/user has an open session?
Do I need to set up separate SP for each application so rather than one common landing page each app would have its own landing page so it can set session variables to pass back to the main application? (the IDP treats our apps as "one server", I can get separate keys if that is the best way to deal with this).
My current working idea for the ACS landing page is to parse the relayState URL to find out which application started the init request and then do something like this:
ACSLandingPage.cfm
<cfset response = processSAMLResponse(idp, sp) />
<cfif find(response.relaystate, 'app1')>
   <cfapplication name="app1" sessionmanagement="true" />
<cfelseif find(response.relaystate, 'app2')>
   <cfapplication name="app2" sessionmanagement="true" />
</cfif>

<cfset session.authenticated_username = response.nameid />
<cflocation url="#response.relaystate#" />

Not terribly ideal, but I think it might work.
I was hoping I was just overlooking something simple and really appreciate any help I can get.
Edit:
My above idea of using <cfapplication in the ACSLandingPage is not working because the <cfapplication keeps trying to assign it to a new session so that when I redirect back to the original app, it thinks it is in a different session so does not have access to the original session.authenticated-username.

A: Ok, here's how I ended up solving this problem. Probably not the "correct" solution, but it works for me.
The full code solution would be way too long and complicated and rely on too many local calls that would not make sense, so I'm trying to get this down to just some code snippets that will make sense to show how my solution works.
In each application, the Application.cfc looks a bit like this. Each app has a name set to the path of the Application.cfc. We do this because we often will run "training instances" of the codebase on the same server that point to an alternate DB schema so users can play around without corrupting production data.
component {
    this.name               = hash(getCurrentTemplatePath());
    ...

In the application's onRequestStart function it has something a bit like this:
    cfparam(session.is_authenticated, false);
    cfparam(session.auth_username, '');
    cfparam(application._auth_struct, {});  // will be important later

    // part 1
    // there will be code in this block later in the description

    // part 2
    if (NOT session.is_authenticated OR session.auth_username EQ '') {
        var returnURL = '#getPageContext().getRequest().getScheme()#://#cgi.server_name#/#cgi.http_url#';   // points back to this calling page
        // start the call
        InitSAMLAuthRequest({
            'idp'       : 'IDP_NAME',
            'sp'        : 'SP_NAME',
            'relayState': returnURL
        });
    }

    // log them in
    if (session.is_authenticated AND session.auth_username NEQ '' AND NOT isUserLoggedIn()) {
        ... do cflogin stuff here ...
    }

    // throw problems if we are not logged in by this point
    if (NOT isUserLoggedIn()) {
        ... if we don't have a logged in user by this point do error handling and redirect them somewhere safe ...
    }

This initiates the SAML connection to our ID Provider. The provider does its stuff and returns the user to the file 'https://myserver/sso/ProcessSAMLResponse.cfm'.
processSAMLResponse uses the returnURL set in relayState to determine which application initiated the request so it can get a path to the app's Application.cfc.
<cfset response = ProcessSAMLResponse(idpname:"IDP_NAME", spname:"SP_NAME") />
<cfset returnURL = response.RELAYSTATE />

<cfif findNoCase("/app1", returnURL)>
    <cfset appPath = "PHYSICAL_PATH_TO_APP1s_APPLICATION.CFC" />
<cfelseif findNoCase("/app2", returnURL)>
    <cfset appPath = "PHYSICAL_PATH_TO_APP2s_APPLICATION.CFC" />
<cfelseif findNoCase("/app3", returnURL)>
    <cfset appPath = "PHYSICAL_PATH_TO_APP3s_APPLICATION.CFC" />
...
</cfif>

<!--- initiate application --->
<cfapplication name="#hash(appPath)#" sessionmanagement="true"></cfapplication>

<!--- create a token (little more than a random string and a bit prettier than a UUID) --->
<cfset auth_token = hash(response.NAMEID & dateTimeFormat(now(), 'YYYYmmddHHnnssL'))/>

<cfset application._auth_struct[auth_token] = {
    "nameid": lcase(response.NAMEID),
    "expires": dateAdd('n', 5, now())
} />

<!--- append token (can also be done with a ?: if you are inclined) --->
<cfif NOT find("?", returnURL)>
    <cfset returnURL &= "?auth_token=" & encodeForURL(auth_token) />
<cfelse>
    <cfset returnURL &= "&auth_token=" & encodeForURL(auth_token) />
</cfif>

<!--- return to the calling page --->
<cflocation url="#returnURL#" addToken="No"/>

This throws it back to the application. So we go back into the application's onRequestStart to fill in that part 1 block from above:
    cfparam(session.is_authenticated, false);
    cfparam(session.auth_username, '');

    // part 1
    // look for an auth token
    if (NOT session.is_authenticated AND session.auth_username EQ '' AND structKeyExists(URL, 'auth_token')) {
        var auth_token = URL.auth_token;

        // see if it exists in our auth struct (and has all fields)
        if (    structKeyExists(application, "_auth_struct")
            AND structKeyExists(application._auth_struct, auth_token)
            AND isStruct(application._auth_struct[auth_token])
            AND structKeyExists(application._auth_struct[auth_token], 'nameid')
            AND structKeyExists(application._auth_struct[auth_token], 'expires')) {

            // only load if not expired
            if (application._auth_struct[auth_token].expires GT now()) {
                session.is_authenticated = true;
                session.auth_username = application._auth_struct[auth_token].nameid;
            }
            // remove token from struct to prevent replays
            structDelete(application._auth_struct, auth_token);

        } // token in auth struct?

        // remove expired tokens
        application._auth_struct = structFilter(application._auth_struct, function(key, value) {
            return value.expires GT now();
        });
    }   // auth_token?

    // part 2
    // .... from earlier

So that's how I solved the problem of multiple apps trying to use a single IDP/SP combination.
Important caveats:

*

*This is all done on an intranet server, so my security is much more lax than it would be on a public facing server. (in particular, using an application variable to store the auth-tokens could be vulnerable to a massive DDOS type attack that would flood new sessions and fill available memory).

*

*A subset of 1 - these apps get a few hundred users a day across all apps, if you have a site that gets thousands of hits a day, storing the tokens in application like I do may not be memory efficient enough for you.

*My IDP is very constrained. It would be much nicer if I could just create distinct SP settings for each app and have the return calls go directly back to the calling app.

*I skipped a few checks and error handling to keep the sample simple. You should do lots more tests on the values, especially to make sure the nameID is a valid user before the actual cflogin call.

*Before calling initSAMLAuthRequest, you may want to add a session counter to prevent an infinite loop of authentication calls if something goes wrong (learned that the hard way).


text:
Q: Python method object application What are the advantages of having a python method, like lower(), being applied to an appropriate object, s, via the dot notation (i.e., s.lower()) versus a method, like len(), being also applied appropriately receiving the object as an argument, e.g. len(s) ? If I want to create such a method / function, what are the critical points I should consider choosing the first or the second implementation? Thanks!

A: In my opinion, If the functionality should be part of an object behavior and it's related only to that object than implement it as a method at the class scope, for example, only str should have functions like lower.
When the function can be applied to a lot of class types like len can be applied on lists or on str than it should be a function.


text:
Q: Why does adding this extra condition to my query make it take considerably longer to execute This is the query I'm talking about:
SELECT COUNT
FROM Note N, DatePCC D
WHERE D.codClient = '2' AND

((D.CodPCC = N.CodPCC AND D.TipPCC = N.TipPCC) OR (D.CodPCC = N.CodPCCOA AND D.TipPCC = N.Relatie))

AND (N.user = 'Server' OR N.user = 'ADMIN' OR N.user = 'Simona' OR N.user =
'Viorel' OR N.user = 'Dan' OR N.user = 'Razvan') AND (N.TipNota = 'Telefon' OR N.TipNota =
'Messenger' OR N.TipNota = 'Telefon esuat' OR N.TipNota = 'Email' OR N.TipNota = 'Evaluare
curs' OR N.TipNota = 'Corespondenta' OR N.TipNota = 'Vizita') AND
(DATE(N.DataInregistrarii) >= '2000-01-01' AND DATE(N.DataInregistrarii) <= '2012-01-25')
AND 1

The problem come from the line i've singled out. When I use it as simply
(D.CodPCC = N.CodPCC AND D.TipPCC = N.TipPCC)

the query runs almost instantly but after I add the second part it locks up our database. I can't, for the life of me, figure out why it impacts the duration so much since it's simply another two comparisons among many other.
What the query does is select stuff from N X D Where either these two (CodPCC, TipPCC) from N coincide with CodPCC and TipPCC from D or (CodPCCOA, Relatie) from N coincide with the same two rows from D.
Any idea how those two simple comparisons are changing the query in such a huge way? or how I could change it to work properly?

A: The big difference is because you are changing a simple inner join into an expression that has to be evaluated on a cross join between the tables.
You shouldn't write your join that way in the first place, but use the join keyword:
select COUNT
from Note N
inner join DatePCC D on D.codClient = '2' and D.CodPCC = N.CodPCC and D.TipPCC = N.TipPC
where ...

To make the new query efficient, you should make two left joins against the same table. That way the database can use index for each join instead of making a cross join.
select COUNT
from Note N
left join DatePCC D on D.codClient = '2' and D.CodPCC = N.CodPCC and D.TipPCC = N.TipPC
left join DatePCC D2 on D2.codClinent = '2' and D.CodPCC = N.CodPCCOA AND D.TipPCC = N.Relatie
where ...

You can also try if an inner join is efficient with the two sets of conditions, but it's possible that the database can't optimise that into a good query.


text:
Q: How can I Pass a keyvault secrets into a Parameter? I'm currently working with some key vault secrets, and I'm trying to see if it is any way that we can pass some of the secrets into parameters inside of Azure pipelines. Does anyone has any idea of how to do this?

A: These are the steps to solve this issue:

*

*Add keyvault under the azure portal

*Inside of your pipeline, you should click in the following options Library > + Variable Group > Add a name > Choose the option called "Link secrets from an Azure Key vault as variables" > Choose azure subscription > Choose Key Vault name > Choose your secret.

*In the pipeline itself you will need to add the following code:
parameters:
- name: TokenDev
  displayName: Token
  type: string
  default: keyvault
  values:
    - keyvaultdev
    - kevaultprod
variables:
- name: privateToken
  value: ${{parameters.TokenDev}}

*To call the secret inside of the variable, you just need to do the following:

$(private) [whatever name you provide to the secret]

If you want to learn more about Parameters, I will recommend you to click in here.


text:
Q: Delete Post Authorize Laravel API I want delete a post with authorization but failed with error "message": false,
"errors": "This action is unauthorized."
destroy controller
public function destroy($id, Post $post)
{
    try {
        $this->authorize('delete', $post);
        $posts = Post::find($id);
        $posts->delete();
        return response()->json([
            'success' => true,
            'message' => 'Success'
        ]);
    } catch (\Exception $e) {
        return response()->json([
            'message' => false,
            'errors' => $e->getMessage()
        ]);
    }

}

policy
public function delete(User $user, Post $post)
{
    return $user->id == $post->user_id;
}

Postman

A: Ensure that the user is good connected. Which api do you used.? If sanctum or passport, you need to specified in your Header Request on Postman, attribute Authorization with the value Bearer your_token
That will create a request like you where connected as the user who owns the token.
You can also check the value by debbuging like this, and look at the response.
var_dump($post->user_id);
var_dump($user);
die();


text:
Q: using image in if statement how can i use image in if statement?
for example i want to check in click event of a picturebox that if a specific image(for example image1) is in it,then do some work.thanks in advance
update:
like this
the picturebox can be null or have an image in it,i want to check image1 is in it or not
    private void pictureBox34_Click(object sender, EventArgs e)
    {
        if (///picturebox34=image1)
        {
            f();
        }
    }

now when i compile this code i took error:cannot convert system.drawing.image to bool

A: If you have all the images loaded into memory then you could simply perform a reference comparison between the Image object assigned to the PictureBox and the other Image objects to determine which one is in the PictureBox.
Alternatively when you assign the Image to the PictureBox you can set the Tag property of the PictureBox to identify the Image and use the value of the Tag property for the test in your event handler. Of course in this case you only need the one Image in memory, but you will have to have some kind of identifying information, like the name of the image to assign to the Tag property.
Update: Based on your updated question, it seems you are happy to perform a refernce comparison. Which you can do as follows
private void pictureBox34_Click(object sender, EventArgs e)
{
    if (picturebox34.Image == image1)
    {
        f();
    }
}


text:
Q: Windows file shares dissapear erratically in Linux file browser My network consists of a router which acts as a dhcp server. Connected to one of its ethernet ports is a unmanaged switch which in turn has all my machines connected to it via ethernet.
On this network I have a central "file server" running Windows 7.
I created some shares on it and I can access them from any other Windows machine on my network without any problems. The shares are stable and always accessible.
The result is very different though when I try to connect from my Linux Mint or Ubuntu machines.
Sometimes I can access the shares and sometimes not without changing any configuration whatsoever. It literally just drops the connection to the shares at any time and then it's not visible in the file browser anymore.
When this happens I can still ping the "file server" and get a response without any issues as well as connect via rdp.
After restarting the samba services via the terminal as well as the Workstation service on the "file server" the result stays the same and there is still no visibility of the shares.
So it is definitely not the connection to the "file server" that is dropping but the connection to the Samba Server seems to be faulty/erratic.
I did some research and followed guide on guide on this and it all points to adding properties and settings to the smb.conf file which I tried to infinity without any success.
It seems to work again if I restart both the file server and the Linux machine but then after a while it disappears again.
I also turned off the firewall on both ends but that also did not resolve the issue.
What I can't understand is why this works and then breaks and then works again without me touching the keyboard?
How can I troubleshoot this to get to the root cause of the problem?


text:
Q: Spark job success but with ERROR CoarseGrainedExecutorBackend: Driver disassociated My spark version is 1.6.2 and runs on yarn.
The log of drive container reports SUCCEEDED as follows:
16/11/17 17:25:56 INFO ApplicationMaster: Final app status: SUCCEEDED, exitCode: 0
16/11/17 17:25:56 INFO ApplicationMaster: Unregistering ApplicationMaster with SUCCEEDED

However, The log of one executor container records an ERROR:
16/11/17 17:25:56 WARN CoarseGrainedExecutorBackend: An unknown (xxx-xxx-xxx-xxx:xxxx) driver disconnected.
16/11/17 17:25:56 ERROR CoarseGrainedExecutorBackend: Driver xxx-xxx-xxx-xxx:xxxx disassociated! Shutting down.

I think the job is succeeded because the output results are as expected.
But I want to know why the error was thrown and whether the job was really succeeded.
I find more info from the log of yarn NodeManager:
WARN org.apache.hadoop.yarn.server.nodemanager.DefaultContainerExecutor: Exception from container-launch with container ID: container_xxxxxxxxx and exit code: 1
ExitCodeException exitCode=1:
    at org.apache.hadoop.util.Shell.runCommand(Shell.java:545)
    at org.apache.hadoop.util.Shell.run(Shell.java:456)
    at org.apache.hadoop.util.Shell$ShellCommandExecutor.execute(Shell.java:722)
    at org.apache.hadoop.yarn.server.nodemanager.DefaultContainerExecutor.launchContainer(DefaultContainerExecutor.java:212)
    at org.apache.hadoop.yarn.server.nodemanager.containermanager.launcher.ContainerLaunch.call(ContainerLaunch.java:302)
    at org.apache.hadoop.yarn.server.nodemanager.containermanager.launcher.ContainerLaunch.call(ContainerLaunch.java:82)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

Someone encounter the same question?
Thanks.


text:
Q: How to drop [UTC] from a column table in KQL Trying to clean up some columns coming into Sentinel from syslog, and working on changing from UTC to local time.
Here is an example of what I have so far:
print dt=now()
| extend pacific_dt = datetime_utc_to_local(dt, 'US/Pacific')
| extend PacificTime = pacific_dt
| project-away dt

What I would expect is two columns, one named pacific_dt and another named PacificTime.  However, when the output is displayed, both column names are appended with [UTC].  Is there a way to remove the [UTC] text that's appended or a workaround to make a new column based on that data but not get the appended text in the column name?
Here's the example code and output.
Query & Output

A: As of today, all dates in KQL are stored as UTC.
datetime_utc_to_local() add an offset to the datetime, so it appears as a local time zone, however it is still a UTC date, just a different one.
If you now change your client display from UTC to local, you get an additional offset.

Please note the following:

*

*The current UTC value now equals to the previous PST value.

*The current PST value has double offset (-8h x 2)

Bottom line -
Work with UTC, and let the client do the conversion to a local time zone.


text:
Q: How can I add feature information from one json into geoJson using id/codarea as the identifier? The following steps show where you can download the files to reproduce this question. How can I add municipality information from one json object into the other using id/codarea as the identifier.
Requesting geojson
import folium
import os
import requests

url = 'https://servicodados.ibge.gov.br/api/v2/malhas/?resolucao=5&formato=application/vnd.geo+json&qualidade=4'

    meshes_mun = requests.get(url, headers=headers).json()

File structure snippet:
   {'type': 'Feature',
       'properties': {'codarea': '2303600',
        'centroide': [-36.722055140733, -6.158308569735204]},
       'geometry': {'type': 'Polygon',
        'coordinates': [[[-36.6532, -6.1118],
          [-36.6828, -6.1277],
          [-36.7005, -6.1453],
.....

In the following you can find string names and ids that I want to link with the meshes_mun above.
The names and ids I need to link with is the higher level: 'id': 2303600, 'nome': 'Catarina', so don't need to add the other features, but they could be added if it's ok.
# url to request information of all municipalities (contains the id number)
mun_url = 'https://servicodados.ibge.gov.br/api/v1/localidades/municipios'

cities_json = requests.get(mun_url, headers=headers).json()

File structure snippet:
{'id': 2303600,
  'nome': 'Catarina',
  'microrregiao': {'id': 23020,
   'nome': 'Sertão de Inhamuns',
   'mesorregiao': {'id': 2304,
    'nome': 'Sertões Cearenses',
    'UF': {'id': 23,
     'sigla': 'CE',
     'nome': 'Ceará',
     'regiao': {'id': 2, 'sigla': 'NE', 'nome': 'Nordeste'}}}}},

A:
How can I add feature information from one json into geoJson using id/codarea as the identifier?

Can be done something like this
import requests

url = "https://servicodados.ibge.gov.br/api/v2/malhas/?resolucao=5&formato=application/vnd.geo+json&qualidade=4"
meshes_mun = requests.get(url).json()

mun_url = "https://servicodados.ibge.gov.br/api/v1/localidades/municipios"
cities_json = requests.get(mun_url).json()

for mun in meshes_mun["features"]:
    codarea = int(mun["properties"]["codarea"])
    matched_city = [city for city in cities_json if city["id"] == codarea][0]
    mun["properties"]["nome"] = matched_city["nome"]


text:
Q: SP2010: Can I show in a column of my item the parent folder name? I am using sp2010. I have a document library. In this library we have many folders. Inside these folders we have items. When I see the list of items in a folder I would like to have a column with the parent folder name. Is this possible?

A: No OOTB way but You can add a column on the document library and populate it with the document parent folder name using Event handler ItemAdding / ItemAdded event.
Here is method how to create event handler.
http://msdn.microsoft.com/en-us/library/ee231563.aspx
http://sharepoint.madhurchadha.com/tag/itemadded-event-handler-in-sharepoint-2010/


text:
Q: How to get driver version by Hardware ID? I'm trying to get the all drivers version show in device manager by Hardware ID. And first I tried is to use Powershell to show the version list.
gwmi Win32_SystemDriver | select name,@{n="version";e={(gi $_.pathname).VersionInfo.FileVersion}}

but it seems not all the drivers in the computer and I still cannot know the HWID.
Then I tried the wmi win32_pnpsigneddriver. But it return only pnp driver.
I think the closest way is to use setupapi.h
SetupDiGetDeviceInterfaceDetail()

but after trying it always returns an error "No more data is available.".
could anyone gives me any example or correct way to find it?
Thanks a lot!


text:
Q: Is there an intelligent way to find the Lie algebra isomorphism $\mathfrak{sl}_2(\mathbb{C})\simeq\mathfrak{o}_3(\mathbb{C})$? The adjoint representation of $\mathfrak{sl}_2(\mathbb{C})$ under a natural basis, it is given by
$$\text{ad}: \mathfrak{sl}_2(\mathbb{C})\to\mathfrak{gl}_3(\mathbb{C})$$
$$\left(\begin{matrix}a&b\\c&-a\end{matrix}\right)\mapsto \left(\begin{matrix}0&-c&b\\-2b&2a&0\\2c&0&-2a\end{matrix}\right).$$
We see that this homomorphism of Lie algebras is injective and its image really looks like $\mathfrak{o}_3(\mathbb{C})$, except the $2$'s.
So I wonder if with a good choice of basis I can get an isomorphism between the Lie algebras $\mathfrak{o}_3(\mathbb{C})$ and $\mathfrak{sl}_2(\mathbb{C})$ (if they are isomorphic)... I've been trying some, but I did not succeed. Is there an intelligent way to see if such a good basis exists or not ?

A: $\newcommand\ad{\operatorname{ad}}$Let $\beta$ be the Killing form on $\mathfrak{sl}_2$, so that for $X$, $Y\in \mathfrak{sl}_2$ we have $$\beta(X,Y)=\operatorname{tr} \ad(X)\circ \ad(Y).$$ You can easily check that this is a non-degenerate symmetric bilinear form on $\mathfrak{sl}_2$. Moreover, the adjoint action of $\mathfrak{sl}_2$ on itself respects this, in the sense that $$\beta(\ad(X)(Y),Z)+\beta(Y,\ad(X)(Z))=0$$ for all $X$, $Y$, $Z\in sl_2$. If we let $\mathfrak{o}(\beta)\subseteq \mathfrak{gl}(sl_2)$ be the Lie algebra of endomorphisms of the vector space $\mathfrak{sl}_2$ which respect the bilinear form $\beta$, then this tells us that the image of $\ad:\mathfrak{sl}_2\to \mathfrak{gl}(\mathfrak{sl} 2)$ is contained in $\mathfrak{o}(\beta)$.
Now check that $\mathfrak{o}(\beta)\cong \mathfrak{o}_3$. Basically, this is because if $b$ and $b'$ are two bilinear forms on a vector space $V$, then $\mathfrak{o}(b)\cong\mathfrak{o}(b')$ whenever there is an isomorphism of quadratic spaces $(V,b)\cong(V,b')$. And all non-degenerate symmetric bilinear forms on a complex vector space are isomorphic.

A: Calculate the dimensions of both Lie algebras.  Once you've done that, see if you can find the image of the map by finding an extra relation satisfied by the matrix on the right not satisfied by an arbitrary element in $\mathfrak{o}_3$.


text:
Q: How to take only payment on another woocomerce website I want to redirect my buyers to my second website 'B' to make payment for my product on website 'A' and after successful payment on website 'B', it should automatically update the order status on website 'A' as the order is completed. I am using woo commerce plugin for my websites. Please any plugins, Add-ons, or custom code suggestions. please I need help
Site 'A'
function action_woocommerce_new_order( $order_id ) {

    //get all order details by $order_id
    //post your data to site B

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL,"http://yoursiteB.com/wp-json/api/v2/create_wc_order");
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS,
            "postvar1=value1&postvar2=value2");

    // In real life you should use something like:
    // curl_setopt($ch, CURLOPT_POSTFIELDS,
    //          http_build_query(array('postvar1' => 'value1')));

    // Receive server response ...
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $server_output = curl_exec($ch);

    curl_close ($ch);
};
add_action( 'woocommerce_payment_complete', 'action_woocommerce_new_order', 10, 1 );

Site 'B'

Class WC_Rest_API {
public function __construct() {
    add_action( 'rest_api_init', array( $this, 'init_rest_api') );
}

public function init_rest_api() {
    register_rest_route('api/v2', '/create_wc_order', array(
       'methods' => 'POST',
       'callback' => array($this,'create_wc_order'),
    ));

}
public function create_wc_order( $data ) {

        //$data  - all the details needs to be send from site A

        global $woocommerce;
        $user_id = $data['user_id'];
        $user = get_user_by( 'ID', $user_id);
        $phonenumer = get_user_meta( $user_id,'user_phoneno', true);

        if($user) {

            $address = array(
              'first_name' => $user->display_name,
              'last_name'  => $user->display_name,
              'email'      => $user->user_email,
              'phone'      => $phonenumer,
            );

            $order = wc_create_order();
            //get product details from rest api site A
            $order->add_product();
            $order->set_address( $address, 'billing' );

            $order->calculate_totals();
            $order = wc_get_order( $order->id );

            $response['status'] = 'success';
            $response['message'] = 'Order created on wordpress site B.';
            return new WP_REST_Response($response, 200);

      }

}

}
$rest_api = new WC_Rest_API();
this doesn't work as it create product on the second website.
I want to use the second website to make only payment if it can pull user data and order id only


text:
Q: Swift Code ending during variable set I have the following code, and for some reason when it gets to the line
let num = data[pagesLeft]
The code just stops, and I cant figure out why. It's not a fatal error or anything, it just ends like the code execution is complete. Any ideas why it would be doing that?
I have the data variable at the top level for access and when I print it, it looks right to me.
func passData (passData : [ScheduleObject]) {
    data = passData
    print(passData.count)
    print(data)
    updateTemplate()
}

func updateTemplate() {
    pagesLeft = data.count
    print(pagesLeft)
    let num = data[pagesLeft]

    let weekObj = num.weekObj
    weekObj.fetchInBackground()

    customerName.text! = num.customerName
    address.text! = num.customerAddress
    phoneNumber.text! = num.customerPhone
    openingWeek.text! = GlobalFunctions().stringFromDateShortStyle(weekObj.weekStart) + " " + GlobalFunctions().stringFromDateShortStyle(weekObj.weekEnd)
    if num.confirmedDate != nil {
        openingDate.text! = GlobalFunctions().stringFromDateShortStyle(num.confirmedDate!)
    } else {
        openingDate.text! = "NOT CONFIRMED"
    }
    if num.confirmedWith != nil {
        confirmedWith.text! = num.confirmedWith!
    } else {
        confirmedWith.text! = "NOT CONFIRMED"
    }
    typeOfWinterCover.text! = num.coverType
    itemLocation.text! = num.locEssentials
    if (num.bringChem) {
        bringChemicals.text! = "Yes"
    } else {
        bringChemicals.text! = "No"
    }
    if (num.takeTrash) {
        takeTrash.text = "Yes"
    } else {
        takeTrash.text = "No"
    }
    notes.text = num.notes!
    accountNumber.text! = num.accountNumber!

    if (firsRun) {
        createPdfFromView(theView, saveToDocumentsWithFileName: "POC")
        firsRun = false
    }

}

A: With let num = data[pagesLeft] where pagesLeft = data.count, you're automatically out of the index range of data.
The last index of an array x is always x.count - 1.


text:
Q: Kendo UI Grid local data source column sort by default Trying to set a default sort column on my kendo UI grid from a local datasource. I've read all over that I should be putting:
sort: { field: "price", dir: "desc" }

onto the data source. I've tried this and it still isn't working (see bottom of following example).
Here's my code in full, where am I going wrong?
$('#grid').kendoGrid({
                dataSource: [
                    {
                        date: "Feb 13 2014",
                        price: 5,
                    },
                    {
                        date: "Feb 15 2014",
                        price: 7,
                    },
                    {
                        date: "Feb 12 2014",
                        price: 6,
                    }
                ],
                height:500,
                sortable: true,
                pageable: false,
                columns: [
                    {
                        field: "date",
                        title: "Date"
                    },
                    {
                        field: "price",
                        title: "Price",
                    }
                ],
                sort: {field: "price", dir: "desc"}
            });

A: You are defining the sort line in the wrong place. You're putting it as one of the grid's properties, but it is (as you said) one of the datasource's property.
Put it as a child of the datasource property:
$('#grid').kendoGrid({
    dataSource: {
        data: [{
            date: "Feb 13 2014",
            price: 5,
        }, {
            date: "Feb 15 2014",
            price: 7,
        }, {
            date: "Feb 12 2014",
            price: 6,
        }],
        sort: {
            field: "price",
            dir: "desc"
        }
    },
    height: 500,
    sortable: true,
    pageable: false,
    columns: [{
        field: "date",
        title: "Date"
    }, {
        field: "price",
        title: "Price",
    }],
});

If it still doesn't work, I can provide a jsFiddle for you to work around with.

A: if you are using Telerik MVC Control which is finally rendered to Kendo UI
.DataSource(dataSource => dataSource
        .Ajax()
        .Sort(sort => sort.Add("City").Ascending()) // <-- initial sort expression
        .Read(read => read.Action("Index", "Home"))
    )


text:
Q: Random loss of javascript audio in Chrome I've been developing a browser based game using html5 and canvas objects it's going well so far. However i've run across a strange issue that I believe is related to chrome. Basically, the game can play fine for a period of time (this varies, typically a few minutes) then the audio just stops playing. If you then refresh the page or go on any other page with html5 audio tags then the sounds do not play either. If I take a look at the javascript console's network tab in chrome then i can see the audio objects haven't transferred and have a type and status of 'pending'. I've never got an error like this in firefox, only chrome.
My search online for similar situations only found one link that sound similar http://www.lordofultima.com/en/forum/showthread.php?tid=52813 with users complaining about loss of sound in chrome in this game (which is also done in javascript)
Any pointers? Feel free to ask if you need more info.

A: Just remove id3 tag of mp3 , it's strange but works , at least i hope


text:
Q: Why is there negative sign as well as positive sign with currents flowing into node for KCL I was studying single node-pair analysis and where i encountered this issue. I dont get why in the last line we have written -v1/100 and -v1/25 when current is flowing into the node but at the same time+o.2v1 when it is also entering the node.

A: Signs of current in a circuit are just conventions chosen at your convenience.
I can say a current of \$1A\$ flows from node A to B. I can also say that current of \$-1A\$ flows from node B to A. Both assumptions are correct. Magnitude and sign, both matter.
Consider following circuit-

simulate this circuit – Schematic created using CircuitLab
In both circuits I assume voltage between A and B, \$ V_{AB}= +V_1\$ which is equal to \$+10V\$
In the first circuit, I assumed: The direction of \$i_1\$ is "downwards" ie., from A to B.
Since \$i_1\$ enters node A and leaves node B, by ohm's law, $$i1 = V_{AB}/R_1= +V_1/R_1=+10/2=+5A$$
In the second circuit, I assumed: The direction of \$i_1\$ is "upwards" ie., from B to A.
Since \$i_1\$ enters node B and leaves node A, by ohm's law, $$i1 = V_{BA}/R_1= -V_1/R_1=-10/2=-5A$$
So which assumption and calculation was "correct"? Both are correct. Just sign of current changes if you assume its direction to be opposite.
Apply this concept to your circuit in the question-.
Author assumed the directions of currents at his convenience in the circuit. Then,
$$i_1=-v_1/25$$
$$i_4=-v_1/100$$
$$i_{10}=-v1/10$$
Author also assumes that all currents entering node B as positive, and all currents leaving node B as negative. Again, this is his choice, not a rule.
With this assumptions, apply KCL at node B-
$$i_2+i_4+-i_{B\to D}=0$$
$$(i_1+i_{10}+i_{C\to A})+i_4+-i_{B\to D}=0$$
$$\implies \frac{-v_1}{25}+\frac{-v_1}{10}+0.2v_1+\frac{-v_1}{100}+-2.5=0$$