text:
Q: Where are PEM files stored for validating SSL certificates? I'm writing a SOAP client application on Ubuntu using OpenSSL and C++. I am having trouble getting my code to validate the server certificate even though I know has a valid certificate.
Just to make sure I would like to check that it's the case and apparently PEM files are used to list valid certificates.
Can anyone tell me where these files reside on my Ubuntu 12.04 installation? I have the ca-certificates package installed on my machine, so these files must be there somewhere?

A: Probably this would help you:
apt-get install apt-file
apt-file update
apt-file list ca-certificates

A: So if you have installed ca-certificates you can easily find out where the files are. Open a terminal and enter
> dpkg -L ca-certificates
/.
/etc
/etc/ssl
/etc/ssl/certs
/etc/ca-certificates
/etc/ca-certificates/update.d
/usr
/usr/sbin
/usr/sbin/update-ca-certificates
/usr/share
/usr/share/ca-certificates
/usr/share/ca-certificates/spi-inc.org
…

So you'll see that all certificates are in /usr/share/ca-certificates. However the default location for certificates is /etc/ssl/certs. You might find additional certificates there.

A: Try this
sudo find / |grep "\.pem"
This will list all the .pem files present on your system and their full path.


text:
Q: Elasticsearch how to sort with nested condition I have the following ES content, which is basically a list of videos with nested video ids for different users.
I need to sort the list based on the 'updated_at' date for a specific user (for example, 'B001').
{ "_index": "videos",
  "_source": {
    "id": 123456,
    "short_title": "First good title",
    "created_at": "2019-05-29T03:19:14",
    "user_list": [
      {
        "user": "A001",
        "video_id": "604214",
        "updated_at": "2019-05-29T03:26:48"
      },
      {
        "user": "B001",
        "video_id": "762001",
        "updated_at": "2019-05-29T06:27:56"
      },
      {
        "user": "C001",
        "video_id": "604218",
        "updated_at": "2019-05-29T06:27:57"
      }
    ]
  }
},
{ "_index": "videos",
  "_source": {
    "id": 127456,
    "short_title": "Second good title",
    "created_at": "2019-05-29T04:19:14",
    "user_list": [
      {
        "user": "B001",
        "video_id": "216001",
        "updated_at": "2019-05-29T06:26:58"
      },
      {
        "user": "A001",
        "video_id": "604218",
        "updated_at": "2019-05-29T06:25:38"
      },
      {
        "user": "C001",
        "video_id": "626001",
        "updated_at": "2019-05-29T06:25:42"
      }
    ]
  }
}

I have tried the following query:
GET videos/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "nested": {
            "path": "user_list",
            "filter": {
              "match": {
                "user_list.user": "B001"
              }
            }
          }
        }
      ]
    }
  },
  "from": 0,
  "size": 10,
  "sort": [
    {
      "user_list.updated_at": {
        "order": "asc",
        "nested_path": "user_list",
        "nested_filter": {
          "match": {
            "user_list.user": "B001"
          }
        }
      }
    }
  ]
}

But I cannot get the right order.
Expected order:
{ "_index": "videos",
  "_source": {
    "id": 127456,
    "short_title": "Second good title",
    "created_at": "2019-05-29T04:19:14",
    "user_list": [
      {
        "user": "B001",
        "video_id": "216001",
        "updated_at": "2019-05-29T06:26:58"
      },
      {
        "user": "A001",
        "video_id": "604218",
        "updated_at": "2019-05-29T06:25:38"
      },
      {
        "user": "C001",
        "video_id": "626001",
        "updated_at": "2019-05-29T06:25:42"
      }
    ]
  }
},
{ "_index": "videos",
  "_source": {
    "id": 123456,
    "short_title": "First good title",
    "created_at": "2019-05-29T03:19:14",
    "user_list": [
      {
        "user": "A001",
        "video_id": "604214",
        "updated_at": "2019-05-29T03:26:48"
      },
      {
        "user": "B001",
        "video_id": "762001",
        "updated_at": "2019-05-29T06:27:56"
      },
      {
        "user": "C001",
        "video_id": "604218",
        "updated_at": "2019-05-29T06:27:57"
      }
    ]
  }
}

Here, video with id "127456" comes first in the order because B001 user's "updated_at" is needed to be in ascending order.
What am I missing in the query?

A: Mapping
PUT videos/_mapping
{

  "properties" : {
      "user_list" : {
        "type" : "nested",
        "properties" : {
          "user" : {
            "type" : "text"
          },
          "video_id" : {
            "type" : "text"
          },
          "updated_at" : {
            "type" : "date"
          }
        }
      },
      "id" : {
        "type" : "integer"
      },
      "short_title" : {
        "type" : "text"
      },
      "created_at" : {
        "type" : "date"
      }
    }
}

Query
GET videos/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "nested": {
            "path": "user_list",
            "query": {
              "bool": {
                "filter": {
                  "match": {
                    "user_list.user": "B001"
                  }
                }
              }
            }
          }
        }
      ]
    }
  },
  "from": 0,
  "size": 10,
  "sort": [
    {
      "user_list.updated_at": {
        "order": "desc",
        "nested_path": "user_list",
        "nested_filter": {
          "match": {
            "user_list.user": "B001"
          }
        }
      }
    }
  ]
}

Result
{
        "_index" : "videos",
        "_type" : "_doc",
        "_id" : "E3cuVGsBJ4bANhADI-an",
        "_score" : null,
        "_source" : {
          "id" : 123456,
          "short_title" : "First good title",
          "created_at" : "2019-05-29T03:19:14",
          "user_list" : [
            {
              "user" : "A001",
              "video_id" : "604214",
              "updated_at" : "2019-05-29T03:26:48"
            },
            {
              "user" : "B001",
              "video_id" : "762001",
              "updated_at" : "2019-05-29T06:27:56"
            },
            {
              "user" : "C001",
              "video_id" : "604218",
              "updated_at" : "2019-05-29T06:27:57"
            }
          ]
        },
        "sort" : [
          1559111276000
        ]
      },
      {
        "_index" : "videos",
        "_type" : "_doc",
        "_id" : "FHcuVGsBJ4bANhADjua8",
        "_score" : null,
        "_source" : {
          "id" : 127456,
          "short_title" : "Second good title",
          "created_at" : "2019-05-29T04:19:14",
          "user_list" : [
            {
              "user" : "B001",
              "video_id" : "216001",
              "updated_at" : "2019-05-29T06:26:58"
            },
            {
              "user" : "A001",
              "video_id" : "604218",
              "updated_at" : "2019-05-29T06:25:38"
            },
            {
              "user" : "C001",
              "video_id" : "626001",
              "updated_at" : "2019-05-29T06:25:42"
            }
          ]
        },
        "sort" : [
          1559111218000
        ]
      }

I am using elastic search 7.0.
Query is same as yours and I am sorting in descending order
123456 is coming first as "user" : "B001","updated_at" : "2019-05-29T06:27:56"
is larger than "user" : "B001", "updated_at" : "2019-05-29T06:26:58"

redpajama_set_name: RedPajamaStackExchange


text:
Q: The requested URL /~paul/CodeIgniter/api/example/user/ was not found on this server I followed this tutorial online and I'm currently using High Sierra MacOS . I tried a simple restAPI using PHP and now I'm trying to implement it on a CodeIgniter3.x framework. The one I created can successfully POST and GET on POSTMAN but now that I tried following the tutorial I had this error on POSTMAN

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">

        <title>404 Not Found</title>

Not Found

The requested URL /~paul/CodeIgniter/api/example/user/ was not found on this server.

the URL I am using last time when I created my own API is like this
http://localhost/~paul/v1/login.php
I think there's a problem on the setup of my CodeIgniter on the High Sierra MacOS?
Could someone please help me out. Thank you
EDIT: If the information does not suffice please let me know.

EDIT: I tried the case sensitivity problem

EDIT: Added Information
Here's my .htaccess
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-s
RewriteRule ^(.*)$ index.php?x=$1 [QSA,NC,L]

RewriteCond %{REQUEST_FILENAME} -d
RewriteCond %{REQUEST_FILENAME} !-s
RewriteRule ^(.*)$ index.php [QSA,NC,L]

RewriteCond %{REQUEST_FILENAME} -d
RewriteCond %{REQUEST_FILENAME} -s
RewriteRule ^(.*)$ index.php [QSA,NC,L]

RewriteCond %{REQUEST_FILENAME} -d
RewriteCond %{REQUEST_FILENAME} -s
RewriteRule ^(.*)$ index.php/$1 [QSA,NC,L]

and my api.php
<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');

//include Rest Controller library
require APPPATH . '/libraries/REST_Controller.php';

class Example extends REST_Controller {

public function __construct() {
    parent::__construct();

    //load user model
    $this->load->model('user');
}

public function user_get($id = 0) {
    //returns all rows if the id parameter doesn't exist,
    //otherwise single row will be returned
    $users = $this->user->getRows($id);

    //check if the user data exists
    if(!empty($users)){
        //set the response and exit
        $this->response($users, REST_Controller::HTTP_OK);
    }else{
        //set the response and exit
        $this->response([
            'status' => FALSE,
            'message' => 'No user were found.'
        ], REST_Controller::HTTP_NOT_FOUND);
    }
}

public function user_post() {
    $userData = array();
    $userData['first_name'] = $this->post('first_name');
    $userData['last_name'] = $this->post('last_name');
    $userData['email'] = $this->post('email');
    $userData['phone'] = $this->post('phone');
    if(!empty($userData['first_name']) && !empty($userData['last_name']) && !empty($userData['email']) && !empty($userData['phone'])){
        //insert user data
        $insert = $this->user->insert($userData);

        //check if the user data inserted
        if($insert){
            //set the response and exit
            $this->response([
                'status' => TRUE,
                'message' => 'User has been added successfully.'
            ], REST_Controller::HTTP_OK);
        }else{
            //set the response and exit
            $this->response("Some problems occurred, please try again.", REST_Controller::HTTP_BAD_REQUEST);
        }
    }else{
        //set the response and exit
        $this->response("Provide complete user information to create.", REST_Controller::HTTP_BAD_REQUEST);
    }
}

public function user_put() {
    $userData = array();
    $id = $this->put('id');
    $userData['first_name'] = $this->put('first_name');
    $userData['last_name'] = $this->put('last_name');
    $userData['email'] = $this->put('email');
    $userData['phone'] = $this->put('phone');
    if(!empty($id) && !empty($userData['first_name']) && !empty($userData['last_name']) && !empty($userData['email']) && !empty($userData['phone'])){
        //update user data
        $update = $this->user->update($userData, $id);

        //check if the user data updated
        if($update){
            //set the response and exit
            $this->response([
                'status' => TRUE,
                'message' => 'User has been updated successfully.'
            ], REST_Controller::HTTP_OK);
        }else{
            //set the response and exit
            $this->response("Some problems occurred, please try again.", REST_Controller::HTTP_BAD_REQUEST);
        }
    }else{
        //set the response and exit
        $this->response("Provide complete user information to update.", REST_Controller::HTTP_BAD_REQUEST);
    }
}

public function user_delete($id){
    //check whether post id is not empty
    if($id){
        //delete post
        $delete = $this->user->delete($id);

        if($delete){
            //set the response and exit
            $this->response([
                'status' => TRUE,
                'message' => 'User has been removed successfully.'
            ], REST_Controller::HTTP_OK);
        }else{
            //set the response and exit
            $this->response("Some problems occurred, please try again.", REST_Controller::HTTP_BAD_REQUEST);
        }
    }else{
        //set the response and exit
        $this->response([
            'status' => FALSE,
            'message' => 'No user were found.'
        ], REST_Controller::HTTP_NOT_FOUND);
    }
}
}

?>

Exactly the same as this tutorial

A: You have case sensitivity problem. In the error, it asked for CodeIgniter while your actual directory is named codeigniter.

A: This has been solved finally!! . What I did was
from this URL /~paul/CodeIgniter/api/example/user/ I changed it to this /~paul/codeigniter/index.php/api/example/user/
and added some stuff on api/example.php from restserver
require APPPATH . '/libraries/REST_Controller.php';
require APPPATH . '/libraries/Format.php';

use Restserver\Libraries\REST_Controller;

and now It works!


text:
Q: App doesn't appear in Launchpad I use Avidemux, which is a great lightweight app for simple video edits. I recently upgraded to version 2.8.0, and around the same time upgraded MacOS to Monterey 12.1. Suddenly, Avidemux is no longer appearing in Launchpad!
Here it is in the Applications folder:

But a search in Launchpad turns up nothing:

There doesn't appear to be anything wrong with the app - it launches from the Finder and works fine. So why doesn't it appear in Launchpad? And how can I fix it? It's pretty annoying to not be able to open it the way I open every other app.

A: As said in the comments simply launch this in Terminal
defaults write com.apple.dock ResetLaunchPad -bool true; killall Dock


text:
Q: Could not find the GDAL library (connection with Hana) I am using Python 3.8.5 version and the Django 3.2.4. I already install GDAL library from the official website with the version 3.3.0. with a pip install.
There are 4 databases presents at the origin in Django but I have to use the Hana one which is notpython. I have only found 2 topics relative to that on GitHub but they are both very old (4 years and 8 years ago).
I have tried everything to solve that problem but nothing seems to work. I already have the following message when I try to make migrations :
"django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (tried "gdal302", "gdal301", "gdal300", "gdal204", "gdal203", "gdal202", "gdal201", "gdal20"). Is GDAL installed? If it is, try setting GDAL_LIBRARY_PATH in your settings."
Someone has an idea to solve that problem ?

A: django don't use gdal python binding. It only require the share library libgdal.so, so you need to have libgdal.so installed somewhere on your system.
Next if gdal is not installed in system directory (ie installed with your distribution package manager), django most of the time is not able to find it, even if the path is in your LD_LIBRARY_PATH.
You have to configure it explicitly in the django settings, as well as geos which is also required:
# django settings of your project
GEOS_LIBRARY_PATH = "/custom/install/prefix/lib/libgeos_c.so"
GDAL_LIBRARY_PATH = "/custom/install/prefix/lib/libgdal.so"

Take a look at https://docs.djangoproject.com/fr/3.2/ref/contrib/gis/install/geolibs/


text:
Q: Elegant methods for caching search results from RESTful service? I have a RESTful web service which I access from the browser using JavaScript. As an example, say that this web service returns a list of all the Message resources assigned to me when I send a GET request to /messages/me. For performance reasons, I'd like to cache this response so that I don't have to re-fetch it every time I visit my Manage Messages web page. The cached response would expire after 5 minutes.
If a Message resource is created "behind my back", say by the system admin, it's possible that I won't know about it for up to 5 minutes, until the cached search response expires and is re-fetched. This is acceptable, because it creates no confusion for me.
However if I create a new Message resource which I know should be part of the search response, it becomes confusing when it doesn't appear on my Manage Messages page immediately. In general, when I knowingly create/delete/update a resource that invalidates a cached search response, I need that cached response to be expired/flushed immediately.
The core problem which I can't figure out:
I see no simple way of connecting the task of creating/deleting/updating a resource with the task of expiring the appropriate cached responses. In this example it seems simple, I could manually expire the cached search response whenever I create/delete/update a(ny) Message resource. But in a more complex system, keeping track of which search responses to expire under what circumstances will get clumsy quickly.

A: To quote Phil Karlton: "There are only two hard problems in Computer Science: cache invalidation and naming things."
If you are using a comprehensive data access layer, that would be the place to handle cache invalidation (although it's still not easy). You'd just tie in some cache invalidation logic to your logic for saving a Message so it clears the search cache for the assignee of the message.

A: Use E-Tag and If-None-Match headers to ensure that the client is always accessing the most up-to-date information.
The down-side to this is you will always make a call to the server to find out if anything had changed. The entire message will not be re-transmitted if nothing changed, and the server will/should simply respond back with a 304 Not Modified response in that case. If the content had changed, then the new message(s) will be transmitted as a response.
If the server is responsive (10-50 ms), then most users with a decent latency (50-500ms) should see no noticeable difference.
This increases the load on the server as it will have to verify for each request whether the received E-Tag matches with the current E-Tag for that resource. Clients never assume that a resource is valid/stale/expired, they always ping the server and find out.

A: The browser cache should automatically invalidate the cache when you do a POST to the same URI that you did a GET from.  See this article, particularly the section on POST invalidation.

A: The simplest solution would be using a sever-side cache (like EhCache, for example) :)
You will have less problems with consistency (as you wouldn't need to push changes to your JavaScript) and expiration.


text:
Q: How do I sum CSV-values in to cells? I am both new here on stackexchange and fairly new to TeX.
I have tried searching for similar questions but found none.
I am working on a document where I need to pppulate a table from a csv file. The data should not be populated as is, but the number of values corresponding to each cell in the table (explained below). I have attached a picture showing the end result I want and a MWE showing the table (I don't know how to color the cells and get the labels "Konsekvens" and "Sannolikhet" in the right place without mixing up the formatting of the cells) and some example data that should result in the table in the picture.
For example for each 4,4 in the data set the upper right cell should increase, resulting in a 7 in that cell since there are 7 4,4.
The data is just example data so the table might differ slightly from the image.
A minor problem is that I can not get m{2cm} to work in stead of p{2cm} as shown here.
I have tried datatool but my only thought there was to use variables but using 16 variables feels like a complicated solution and I hope it can be done in a better way, and that's why I'm asking for help here.

\documentclass{article}

\usepackage{filecontents}
\usepackage{multirow}
\usepackage{graphicx}

\begin{filecontents*}{mycsvdata.csv}
Sannolikhet,Konsekvens
4,4
4,4
4,4
4,4
4,4
4,4
4,4
4,3
4,2
4,2
2,4
2,4
2,4
2,4
2,2
1,4
1,4
1,4
1,4
1,4
1,3
1,3
1,2
1,1
\end{filecontents*}

\begin{document}
\begin{tabular}{c|p{2cm}|p{2cm}|p{2cm}|p{2cm}|p{2cm}|}
\cline{2-6}
   \multirow{5}{*}{\rotatebox{90}{Konsekvens}}
                     & Mycket allvarlig&~&~&~&~ \\[0.5cm]\cline{2-6}
        & Allvarlig&~&~&~&~ \\[0.5cm]\cline{2-6}
        & Måttlig&~&~&~&~ \\[0.5cm]\cline{2-6}
        & Försumbar&~&~&~&~ \\[0.5cm]\cline{2-6}
   \multicolumn{1}{l}{}&~&Osannolik&Möjlig&Sannolikt&Mycket sannolikt \\\cline{3-6}
     \multicolumn{6}{r}{Sannolikhet}
\end{tabular}

\end{document}

A: I´m not totally satisfied with the solution, but I have a working code now. I thought I might as well share it so someone else can make use of it.
I still want "Sannolikhet" to be centered over the four last columns but when I do that I get vertical lines where they are not supposed to be. I also want "Konsekvens" to be vertically centered over the four top rows.
The result:

The code:
\documentclass{article}

\usepackage{filecontents}
\usepackage{multirow}
\usepackage{graphicx}
\usepackage[table]{xcolor}
\usepackage{hhline}
\usepackage{datatool}
\usepackage{array}

\begin{filecontents*}{mycsvdata.csv}
Sannolikhet;Konsekvens
4;4
4;4
4;4
4;4
4;4
4;4
4;4
4;3
4;2
4;2
2;4
2;4
2;4
2;4
2;2
1;4
1;4
1;4
1;4
1;4
1;3
1;3
1;2
1;1
\end{filecontents*}

\newcolumntype{M}[1]{>{\centering\arraybackslash}m{#1}}

\definecolor{orangex}{RGB}{255,205,55}
\definecolor{greenx}{RGB}{146,208,80}

\newcounter{AA}
\newcounter{AB}
\newcounter{AC}
\newcounter{AD}
\newcounter{BA}
\newcounter{BB}
\newcounter{BC}
\newcounter{BD}
\newcounter{CA}
\newcounter{CB}
\newcounter{CC}
\newcounter{CD}
\newcounter{DA}
\newcounter{DB}
\newcounter{DC}
\newcounter{DD}

\DTLsetseparator{;}

\begin{document}

\DTLloaddb{riskvarde}{mycsvdata.csv}
\DTLforeach*{riskvarde}{\Sannolikhet=Sannolikhet,\Konsekvens=Konsekvens}{
\ifthenelse{\DTLiseq{\Sannolikhet \Konsekvens}{11}}{\stepcounter{AA}}{}
\ifthenelse{\DTLiseq{\Sannolikhet \Konsekvens}{12}}{\stepcounter{AB}}{}
\ifthenelse{\DTLiseq{\Sannolikhet \Konsekvens}{13}}{\stepcounter{AC}}{}
\ifthenelse{\DTLiseq{\Sannolikhet \Konsekvens}{14}}{\stepcounter{AD}}{}
\ifthenelse{\DTLiseq{\Sannolikhet \Konsekvens}{21}}{\stepcounter{BA}}{}
\ifthenelse{\DTLiseq{\Sannolikhet \Konsekvens}{22}}{\stepcounter{BB}}{}
\ifthenelse{\DTLiseq{\Sannolikhet \Konsekvens}{23}}{\stepcounter{BC}}{}
\ifthenelse{\DTLiseq{\Sannolikhet \Konsekvens}{24}}{\stepcounter{BD}}{}
\ifthenelse{\DTLiseq{\Sannolikhet \Konsekvens}{31}}{\stepcounter{CA}}{}
\ifthenelse{\DTLiseq{\Sannolikhet \Konsekvens}{32}}{\stepcounter{CB}}{}
\ifthenelse{\DTLiseq{\Sannolikhet \Konsekvens}{33}}{\stepcounter{CC}}{}
\ifthenelse{\DTLiseq{\Sannolikhet \Konsekvens}{34}}{\stepcounter{CD}}{}
\ifthenelse{\DTLiseq{\Sannolikhet \Konsekvens}{41}}{\stepcounter{DA}}{}
\ifthenelse{\DTLiseq{\Sannolikhet \Konsekvens}{42}}{\stepcounter{DB}}{}
\ifthenelse{\DTLiseq{\Sannolikhet \Konsekvens}{43}}{\stepcounter{DC}}{}
\ifthenelse{\DTLiseq{\Sannolikhet \Konsekvens}{44}}{\stepcounter{DD}}{}
}

\begin{tabular}{c|M{2cm}|M{2cm}|M{2cm}|M{2cm}|M{2cm}|}

\hhline{~|*{5}-}
   \multirow{5}{*}{\rotatebox{90}{Konsekvens}}
                     & Mycket allvarlig&\cellcolor{yellow!75}\ifthenelse{\theAD>0}{\theAD}{}&\cellcolor{orangex}\ifthenelse{\theBD>0}{\theBD}{}&\cellcolor{red!50}\ifthenelse{\theCD>0}{\theCD}{}&\cellcolor{red!50}\ifthenelse{\theDD>0}{\theDD}{} \\\hhline{~|*{5}-}
        & Allvarlig\newline&\cellcolor{greenx}\ifthenelse{\theAC>0}{\theAC}{}&\cellcolor{yellow!75}\ifthenelse{\theBC>0}{\theBC}{}&\cellcolor{orangex}\ifthenelse{\theCC>0}{\theCC}{}&\cellcolor{red!50}\ifthenelse{\theDC>0}{\theDC}{} \\\hhline{~|*{5}-}
        & Måttlig\newline&\cellcolor{greenx}\ifthenelse{\theAB>0}{\theAB}{}&\cellcolor{greenx}\ifthenelse{\theBB>0}{\theBB}{}&\cellcolor{yellow!75}\ifthenelse{\theCB>0}{\theCB}{}&\cellcolor{orangex}\ifthenelse{\theDB>0}{\theDB}{} \\\hhline{~|*{5}-}
        & Försumbar\newline&\cellcolor{greenx}\ifthenelse{\theAA>0}{\theAA}{}&\cellcolor{greenx}\ifthenelse{\theBA>0}{\theBA}{}&\cellcolor{greenx}\ifthenelse{\theCA>0}{\theCA}{}&\cellcolor{yellow!75}\ifthenelse{\theDA>0}{\theDA}{} \\\hhline{~|*{5}-}
        \multicolumn{1}{l}{}&~&Osannolik&Möjlig&Sannolikt&Mycket sannolikt \\ \hhline{~|~|*{4}-}
        \multicolumn{6}{r}{Sannolikhet}
\end{tabular}

\end{document}

A: If you don't mind a little bit of exotic Lua programming...

\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage{colortbl}
\usepackage{multirow}
\usepackage{graphicx}
\usepackage{array}
\usepackage{luacode}
\usepackage{hhline}
\usepackage{xcolor}

\begin{document}

\newcolumntype{M}[1]{>{\centering\arraybackslash}m{#1}}

\begin{luacode*}

local table_str = [[
\begin{tabular}{c|M{2cm}|M{2cm}|M{2cm}|M{2cm}|M{2cm}|}
\hhline{~|*{5}-}
   \multirow{5}{*}{\rotatebox{90}{Konsekvens}}
                     & Mycket allvarlig&@&@&@&@ \\[0.5cm]\hhline{~|*{5}-}
        & Allvarlig&@&@&@&@ \\[0.5cm]\hhline{~|*{5}-}
        & Måttlig&@&@&@&@ \\[0.5cm]\hhline{~|*{5}-}
        & Försumbar&@&@&@&@ \\[0.5cm]\hhline{~|*{5}-}
   \multicolumn{1}{l}{}&~&Osannolik&Möjlig&Sannolikt&Mycket sannolikt \\\hhline{~|~|*{4}-}
     \multicolumn{6}{r}{Sannolikhet}
\end{tabular}
]]

local result_table = {}
for i=1,4 do
    result_table[i] = {}
    for j=1,4 do
        result_table[i][j] = 0
    end
end

local line_num = 0
for line in io.lines('mycsvdata.csv') do
    if line_num ~= 0 then
        local stripped_line = string.gsub(line, '%s', '')
        local comma_pos = string.find(line, ',')
        if comma_pos ~= nil then
            local left = tonumber(stripped_line:sub(1, comma_pos - 1))
            local right = tonumber(stripped_line:sub(comma_pos + 1))
            result_table[left][right] = result_table[left][right] + 1
        end
    end
    line_num = line_num + 1
end

for i=0,15 do
    local y = 4 - math.floor(i / 4)
    local x = i % 4 + 1
    local cell_num = result_table[x][y]
    local cell_str = tostring(cell_num)
    if cell_num == 0 then
        cell_str = ''
    end
    if y+x <= 4 then
        cell_str = [[{\cellcolor{green!50}}]] .. cell_str
    elseif x+y <= 5 then
        cell_str = [[\cellcolor{yellow!50}]] .. cell_str
    elseif x+y <= 6 then
        cell_str = [[\cellcolor{orange!50}]] .. cell_str
    else
        cell_str = [[\cellcolor{red!50}]] .. cell_str
    end

    local new_str, sub_count = string.gsub(table_str, '@', cell_str, 1)
    table_str = new_str
end

local out_str, _ = string.gsub(table_str, '\n', '')
tex.print(out_str)

\end{luacode*}

\end{document}


text:
Q: How can I localize the value of CFBundleDisplayName in the Info.plist file? When I look inside the Info.plist file in Xcode, the Property List Editor shows me an value that looks like an variable:
${PRODUCT_NAME}

How / where can I set up localized names for my app?

A: You can create a localized file named InfoPlist.strings, containing the name of your application:
CFBundleDisplayName = "Name of the App";

(Just like Localizable.strings)


text:
Q: Optimizing this Block of html code to React code using functional components and props Can someone help me in optimizing this code block to React code using functional components with props?
As you can see this is the HTML code.

I was trying to write something like this but that is not giving output as expected.
Can someone help me, please?
This is my React Code.
const Category1 = () => {
    return (
        <ImageGallery />
    );
}

const imagesInfo = [
    { index: '1', imagePath: 'category/category1/1.jpg' },
    { index: '2', imagePath: 'category/category1/2.jpg' },
    { index: '3', imagePath: 'category/category1/3.jpg' },
    { index: '4', imagePath: 'category/category1/4.jpg' },
    { index: '5', imagePath: 'category/category1/5.jpg' },
    { index: '6', imagePath: 'category/category1/6.jpg' },
    { index: '7', imagePath: 'category/category1/7.jpg' },
    { index: '8', imagePath: 'category/category1/8.jpg' },
    { index: '9', imagePath: 'category/category1/9.jpg' },
    { index: '10', imagePath: 'category/category1/10.jpg' },
    { index: '11', imagePath: 'category/category1/11.jpg' },
    { index: '12', imagePath: 'category/category1/12.jpg' },
    { index: '13', imagePath: 'category/category1/13.jpg' },
    { index: '14', imagePath: 'category/category1/14.jpg' },
    { index: '15', imagePath: 'category/category1/15.jpg' },
    { index: '16', imagePath: 'category/category1/16.jpg' },
];

const ImageGallery = () => {
    return (

            {imagesInfo.map(object => (
                <ImagesRow
                    key={object.index}
                    imagePath={object.imagePath} />
            ))}

    );
}

const ImagesRow = (props) => {
    return (

            <ImagesColumn {...props} />

    );
}

const ImagesColumn = (props) => {
    return (

    )
}

export default Category1;

Thanks in Advance for any help


text:
Q: Xamarin Android Login by using Password MainActivity have Button "Password" When first time application is open then MainActivity should be open and user set Password using Password Activity that open by clicking Password button, Next time whenever application is open user ask to enter Password to enter in Main Activity. Kindly tell me how to perform this task. i'm new to Xamarin. here is code of Password Activity and Login Activity.i am using sqlite to save password. Thanks in advance.
Password Activity:
namespace App1
{
    [Activity(Label = "Password")]
    public class Password : Activity
    {
        DataBase db;

        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.Password);
            db = new DataBase();
            Button btnSave = FindViewById<Button>(Resource.Id.btnSave);
            btnSave.Click += BtnSave_Click;
        }

        private void BtnSave_Click(object sender, EventArgs e)
        {
            PasswordSave();
        }

        public void PasswordSave()
        {
            var txtPassword1 = FindViewById<EditText>(Resource.Id.txtPassword1);
            var txtPassword2 = FindViewById<EditText>(Resource.Id.txtPassword2);
            string Pass1 = txtPassword1.Text.ToString();
            string pass2 = txtPassword2.Text.ToString();

            if (Pass1 == "" && pass2 == "")
            {
                Toast.MakeText(this, "Empty Fields", ToastLength.Short).Show();
            }
            else
            {
                if (Pass1 == pass2)
                {

                    Person person = new Person()
                    {
                        password = Pass1,
                    };
                    db.insertIntoTable(person);
                    Toast.MakeText(this, "Password Saved", ToastLength.Short).Show();
                }
                else
                {
                    Toast.MakeText(this, "Please Enter the Same Password",
                        ToastLength.Short).Show();
                }
            }
        }
    }
}

Login Activity Code:
namespace App1
{
    [Activity(Label = "Login")]
    public class Login : Activity
    {
        Person p;

        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.Login);

            Button btnLogin = (Button)FindViewById(Resource.Id.btnLogin);
            // Create your application here
            btnLogin.Click += BtnLogin_Click;
        }

        private void BtnLogin_Click(object sender, EventArgs e)
        {
            var pass = FindViewById<EditText>(Resource.Id.txtPassword);
            string npass = pass.ToString();
            p = new Person();
            string mypass = p.password;
            if (npass == mypass)
            {
                Toast.MakeText(this, "Password Matched", ToastLength.Long).Show();
                StartActivity(typeof(MainActivity));
            }
            else
            {
                Toast.MakeText(this, "Password not Matched", ToastLength.Long).Show();
            }
        }
    }
}


text:
Q: How to place transparent color over image using ::after? Problem: container has 200px width, image can have dynamic width (100px, 120px, whatever)
img::after does not work at all.
https://jsfiddle.net/8j1r0nmk/3/

.wrapper {
  position: relative;
  width: 200px;
  border: 1px solid black;
}
.img-responsive {
  display: block;
  max-width: 100%;
  height: 100%;
}
.img-wrap::after {
  display: block;
  position: absolute;
  content: ' ';
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  background-color: rgba(40, 40, 60, 0.1);
}

I can not set width for .img-wrap because it breaks image width.
What are my options?

A: You can apply the following CSS to img-wrap
.img-wrap {
  display: inline-block;
  position: relative;
  vertical-align: bottom;
}

I've changed the colour in the demo below to show the :after more clearly.

.wrapper {
  position: relative;
  width: 200px;
  border: 1px solid black;
}

.img-wrap {
  display: inline-block;
  position: relative;
  vertical-align: bottom;
}

.img-responsive {
  display: block;
  max-width: 100%;
  height: 100%;
}

.img-wrap::after {
  display: block;
  position: absolute;
  content: ' ';
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  background-color: rgba(255, 0, 0, 0.2);
}

A: You can achieve a similar result without using psuedoelements: the idea is to apply a SVG filter on the image itself (defined either on the page itself or as an external URL), so there's no need to make assumptions on the existant markup or about the parent containers

Codepen demo

Markup
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" id="overlayfilter">
  <defs>
      <filter id="overlay">
        <feColorMatrix
          type="matrix"
          values=".4  0  0  0  0
                   0 .4  0  0  0
                   0  0 .6  0  0
                   0  0  0 .6  0 ">

        </feColorMatrix>
    </filter>
  </defs>
</svg>

CSS
[id="overlayfilter"]  { display: block; height: 0; }

.img-responsive {
  display: block;
  max-width: 100%;
  height: 100%;
  filter: url(#overlay);
}

.img-responsive:hover {
  filter: none;
}

The color of the filter is defined in this way
<filter id="linear">
  <feColorMatrix
      type="matrix"
      values="R 0 0 0 0
              0 G 0 0 0
              0 0 B 0 0
              0 0 0 A 0 "/>
  </feColorMatrix>
</filter>

(source)
So you may be able to adapt the overlay colour to your needs. Filters defined by url() are currently implemented on all modern browsers (excluding Edge).

A: For the ::after css3 code I am sure that you have to have a ::before status included as well so that the file reads what should come before the after element. (Please don't quote me on this as I am not 100% sure however when I have worked with these I have also included an ::before)
When using the ::after content: url(/path/to/image.jpg); - The image is inserted at it's exact dimensions and cannot be resized. Since things like gradients are actually images, a pseudo element can be a gradient.


text:
Q: I am trying to bring back a row based on the minimum date, but not bring back the date field select customer_id, street_address, city, state, zip
from customer  where min(date);

A: if Teradata:
select customer_id, street_address, city, state, zip from customer
qualify row_number() over(partition customer_id order by date)=1

Other options:
select customer_id,street_address, city, state, zip from customer a
inner join (select customer_id, min(date) as min_date from customer group by customer_id) b
on a.customer_id=b.customer_id and a.date=b.min_date

A: Considering you are trying this in T-SQL. you can try using CTE (common table expression)
Example:
select 'a123' street_address, 'as' city,'ap' state, 123456 zip, cast(getdate()-10 as date) [day] into #temp
insert into #temp values('b12','ad','aw',345478,cast(getdate()-1 as date))
insert into #temp values('c243','a2','a3',3458,cast(getdate()-12 as date))
insert into #temp values('e3d','a2','af',8324,cast(getdate()-13 as date))
insert into #temp values('f46','a3','ag',337,cast(getdate()-13 as date))
insert into #temp values('g23','a4','ah',0374,cast(getdate()-1 as date))
insert into #temp values('h12','af','aj',946,cast(getdate()-17 as date))
insert into #temp values('634','ad','a8',345,cast(getdate()-17 as date))

select * from #temp

--Query to return min valued row
;with q as (select min(day) minday from #temp)
select street_address, city, state, zip from #temp t cross apply q where t.day=q.minday

Blog to read for CTE:
       https://www.red-gate.com/simple-talk/sql/t-sql-programming/sql-server-cte-basics/

A: On of the simplest solutions that will work in every rdbms is:
select customer_id, street_address, city, state, zip
from customer
where date in (select min(date) from customer)
;


text:
Q: difference between draggable and ondragstart while I was checking some code in a website I came with this question.
In the body tag it was written ondragstart="return false" and ondrop="return false", by looking at it, I understood that they prevented their website images and links from dragging and dropping. However, I have also done some research and found that this can also be achieved by directly writing draggable="false". I am confused with these attributes now. Can anyone explain them in a simple way? Kindly, Let me know if I did any mistakes in my question, I'll keep them in mind when asking other questions. Thanks in advance :)
<body ondragstart="return false;" ondrop="return false;">

This is the code that I have seen in the website. Take a look at it.

A: As far as I know, ondragstart and ondrop are events. Draggable is a property which can be set to 'true' at later stage in the code. Having implemented this feature in the events ensures that mouse drag cannot be set to true further in the code, unless those event are un-binded.


text:
Q: How to save Firefox Profile with Selenium and Python I want to save a Firefox Profile after being used by Selenium since I need its data (cookies,sessions,history) to remain in that profile, so I can access it later. I know how to load profile, but I don't know how to save it after use.
I already searched for this and unable to find any solution. I also refer this answer, but I couldn't understand what should I do.


text:
Q: How can I prevent my program from running if it is not ran in Administrative mode? XP and Windows 7 I have a C# Program that is supposed to be multi-OS compatible. It requires access to create a directory and get WMI Data, but that is only available if the program is ran as an Administrator. Otherwise, it fails.
Is there any command I can use to not run the program if it does not detect itself as being ran as an administrator? I tried adding a app.manifest and using "requireAdministrator", it prompts for login, but that appears to only work on Windows 7 and Vista, not XP.
Example:
 if (isAdmin==0)
 Console.WriteLine("Please run this as an administrator");
 exit;

A: Check if the User Is an Admin
public static bool IsAdministrator()
{
    WindowsIdentity windowsIdentity = WindowsIdentity.GetCurrent();
    WindowsPrincipal windowsPrincipal = new WindowsPrincipal(windowsIdentity);

    return windowsPrincipal.IsInRole(WindowsBuiltInRole.Administrator);
}

Restart the app if not an admin
public static bool RestartAsAdministrator(string filePath, string fileName, string errorCaption)
{
    Process process = null;
    ProcessStartInfo processStartInfo = new ProcessStartInfo();
    processStartInfo.FileName = Path.Combine(filePath, fileName);

    if (Environment.OSVersion.Version.Major >= 5) //5 is XP and 6 is Vista and 7
        processStartInfo.Verb = "runas";

    processStartInfo.Arguments = "";
    processStartInfo.WindowStyle = ProcessWindowStyle.Normal;
    processStartInfo.UseShellExecute = true;

    try
    {
        process = Process.Start(processStartInfo);
    }

    catch (Exception)
    {
        MessageBox.Show("Couldn't start as admin.\nPlease try manually by Right Clicking on " + Path.GetFileNameWithoutExtension(fileName) + " and selecting \"Run as administrator\"",
                            errorCaption + " Error", MessageBoxButton.OK, MessageBoxImage.Error);

        return false;
    }

    finally
    {
        if (process != null)
            process.Dispose();
    }

    return true;
}

Application Manifest File (Used to automatically Run as Admin)
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />

A: You can use this function to check if the current user (that starts your application) has administrator rights.
using System.Security.Principal;
...
bool IsAnAdministrator ()
{
   WindowsIdentity  identity = WindowsIdentity.GetCurrent();
   WindowsPrincipal principal = new WindowsPrincipal (identity);
   return principal.IsInRole(WindowsBuiltInRole.Administrator);
}

If you call this method and it returns false you can show a message and/or close your application.


text:
Q: Laravel-scout : ElasticSearch with Translatable Entities (astrotomic/laravel-translatable) I'm trying to use "babenkoivan/scout-elasticsearch-driver" with "astrotomic/laravel-translatable", but i don't understand how I could index the translated words.
My Model looks like :
namespace App\Models;

use Astrotomic\Translatable\Translatable;
use App\Models\Search\ShowIndexConfigurator;
use ScoutElastic\Searchable;
...

class Show extends BaseModel
{
    ...
    use Translatable;
    use Searchable;

    protected $indexConfigurator = ShowIndexConfigurator::class;

    protected $searchRules = [
        //
    ];

    protected $mapping = [
        'properties' => [
            // How to index localized translations ???
            'title' => [
                'type' => 'string'
            ],
        ]
    ];

   ....

   public $translatedAttributes = [
      ...,
      'title'
      ...
   ];

Best regards

A: I found a solution with the override of the method
public function toSearchableArray() with something like:
public function toSearchableArray(): array
    {
        $document = [];
        if ($this->published) {
            $document = [
                //...
            ];
            foreach ($this->translations()->get() as $translation)
            {
                if (!$translation->active) {
                    continue;
                }

                $locale = $translation->locale;
                $document['title_' . $locale] = $translation->title;
                $document['url_' . $locale] = $this->getLink($locale);
                $document['sub_title_' . $locale] = $translation->sub_title;
                $document['keywords_' . $locale] = "";
            }
        }

        return $document;
    }

The purpose of $mapping=[] is only to define the structure of data. Something like that is expected:
    protected $mapping = [
        'properties' => [
            'title_en' => [
                'type' => 'string'
            ],
            'title_fr' => [
                'type' => 'string'
            ],
            ...
        ]
    ];


text:
Q: gsutil bashrc file path setting Actually I have just installed gsutil by following the instructions here.
But now when I am typing gsutil at command prompt I am getting following:
No command was given.
Choose one of -b, -d, -e, or -r to do something.
Try `/usr/bin/gsutil --help' for more information.

What can be my mistake or am I supposed to do something else?
Is it due to that I have not set correct path in my .bashrc file? Following path is set by me in .bashrc file:
export PATH=${PATH}:$usr/bin/gsutil

and firstly I had set it to:
export PATH=${PATH}:$HOME/vishal/Downloads/gsutil/gsutil

A: As noted at https://stackoverflow.com/questions/7989741/how-to-configure-gsutil, the "No command was given" message is returned by the program gsutil in the Ubuntu package gsutil. That is not the Google Cloud Storage utility, but an older program to "configure and manage GrandStream BudgeTone 100 VOIP and GS2000 phones." This is mentioned in a prominent "Warning" in a red box on the Google help page that you link to.
Although you could probably fix this problem by configuring your PATH correctly (so that the Google gsutil is found before the gsutil from the Ubuntu package), if you don't have a "BudgeTone" phone, you can also simply uninstall the Ubuntu package gsutil.

A: The program gsutil needs some more arguments to run. So gsutil alone will not produce anything helpfuk, except the output you pasted.  So i.e. to upload your PNG photos issue the command
gsutil cp *.png gs://my_pngs

Just have a look at the gsutil Reference Guide. This document explains how you should use gsutil.
But also your definition of the $PATH seems not correct. You wrote:
export PATH=${PATH}:$usr/bin/gsutil

Have you really set a variable $usr? I assume you want to use the directory /usr. If this is your intention you should substitute the $ and write a / instead. The second questions that comes into mind is: Is /usr/bin/gsutil a directory? I assume this is your executable file. So your definition will not work anyway. If you try to enter echo $PATH you will see that /usr/bin is already defined as part of your path. So gsutil will be called like any other program and there is no need setting the PATH variable.

A: Rather than downloading and installing from the Internet I strongly recommend to use the package management inbuilt to Ubuntu.
This makes sure that applications are tested to run on your distribution version, and it also makes sure that applications are installed in the appropriate place in the file system. It also lets you easily remove the application in case you don't need it any more.
To do so search for an application in the Ubuntu Software Center.
Below is a link to install gsutil on your system via the Ubuntu package management:

Alternatively you may click here on the shopping bag right to gsutil
Only rarely you may have to add a ppa as a software source from where you know you can install an application that is not available otherwise.
Only as a last resort we may also install application from their source code or from an installation program that may be offered (e.g. in case of closed source software). Such software may then not be tested to run without issues.


text:
Q: Open terminal on startup and run command Very simple question, I'm new to Linux
I have a command run on startup (Elementary OS) command is:
/home/zachary/Documents/Server108/Server108.sh

When I turn my laptop on the command runs in the background, and this is great, but I can't issue a "Stop" command because the terminal never opens. So, my question is this;
How do I force the terminal to open, run the script and then stay open?
Do I need to add a line to the .sh file, or add arguments to the startup command?

A: If you are using older GNOME you can add to startup something like this:

gnome-terminal --command "/path/myscript.sh"

Just edit your startup with gnome-session-properties GUI. It should be in System -> Properties menu or Applications –> Other –> Advanced Settings or press Alt+F2 and input it there. But apparently it was deprecated and it will not work on GNOME 3...
You can try adding into your folder ~/.config/autostart a file, let's say myscript.desktop with following content:
[Desktop Entry]
Type=Application
Exec=gnome-terminal --command "/path/myscript.sh"
Hidden=false
X-GNOME-Autostart-enabled=true
Name=Startup Script
Comment=

Above content is actually from my own system, created by mate-session-properties GUI and it works. Only updated it for GNOME. It actually might work on other environments, you'll just need to play with some details. Adding Terminal=true with Exec=/path/myscript.sh also works and with it you don't need to know the command to start your terminal.
On MATE it's easier, because it's still got that GUI. Commands are called mate-terminal and mate-session-properties. Here's how it looks on my MATE:

I'm not familiar with Elementary OS and you didn't say which desktop environment you are using (might be Pantheon which I've never worked on), but it should not be that different.
You might need to figure out command to start your terminal and try running my-terminal --help or visit it's manpages to find proper parameter (or just try that much simpler Terminal=true solution).
And if for some reason Terminal=true doesn't work and you can't determine your terminal's commands, install XTerm:

sudo apt-get install xterm

Its command is xterm -e "/path/myscript.sh.


text:
Q: Why does _splitpath_s() take custom sized string buffer for returning drive letter? A small detail caught my eye while reading documentation of _splitpath_s(). It takes path of a disk item (e.g.; C:\Temp\MyFile.exe) in its 1st parameter, and then splits it into drive, directory, folder and extension names. However, the strange thing is, it asks for length of the string buffer that will hold name of the drive in return in its 3rd parameter.
As far as I know, a drive letter can be nothing but a two-letter string; a letter followed by a semicolon, like A:, B:, C:, etc. Therefore, it must always be a two-character string under all cases. But if so, just why does _splitpath_s() ask for length of drive letter? Is there any case which drive letter can be in a different format? What problem would had occurred at worst, if it didn't ask for its length and just assumed it to be 2?
errno_t _splitpath_s(
   const char * path,
   char * drive,
   size_t driveNumberOfElements,
   char * dir,
   size_t dirNumberOfElements,
   char * fname,
   size_t nameNumberOfElements,
   char * ext,
   size_t extNumberOfElements
);

A: The point of the _s functions is to be paranoid about buffer overflows.  All buffers therefore should be associated with a size.
Your proposal to use a two-character string would mean that either the colon would be omitted (which from a usage perspective would be annoying) or would mean that the string is not NUL-terminated, which probably is unexpected (especially since it would be inconsistent with all of the other output parameters, which are NUL-terminated) and which then could lead to other security vulnerabilities.
Even if you amended your proposal to use a fixed-size buffer of three characters instead of two, in C, declaring array parameters to functions doesn't really do anything; the compiler will not enforce that an argument is an array of the correct size.  That is, a function like:
 void foo(int array[3]);

is not actually any different from:
 void foo(int* array);

If _splitpath_s did not take a driveNumberOfElements parameter, it would be easier for callers to accidentally pass buffers that are too small.  While it's true that callers can still do that in its current form, the presence of the explicit driveNumberOfElements parameter should make callers pay some attention to this.
Finally, in theory, drives someday might not be restricted to single characters, so a version of _splitpath_s that takes a driveNumberOfElements parameter is a bit more future-proof. (In practice, however, such a change would break lots of existing code.)


text:
Q: Use PHP's mail() to do a blind copy e-mail? I read that

All custom headers (like From, Cc, Bcc and Date) are supported

from PHP mail() reference, but how do I actually implement this in my code? i.e. I don't want any recipient to see the other e-mails... ever.
Something like:
<?php
$to = "someguy@somesite.com, another@abc.com, someother@def.com";
$subject = "test message";
$msg = "this is a test";
$headers = "Bcc"; // <-- this?

if (mail($to, $subject, $msg, $headers))
    echo "message sent";
else
    echo "uh oh";
?>

A: Look at the examples on the page.
Here's one...
$headers .= 'To: Mary <mary@example.com>, Kelly <kelly@example.com>' . "\r\n";
$headers .= 'From: Birthday Reminder <birthday@example.com>' . "\r\n";
$headers .= 'Cc: birthdayarchive@example.com' . "\r\n";
$headers .= 'Bcc: birthdaycheck@example.com' . "\r\n";

So you just add comma separated email addresses after Bcc: in the header.
Here's one with a loop that will add addresses from the array $recip to BCC:
$headers.="Bcc: ";
while($count < $count_recip){
    $headers.=$recip[$count].", ";
    $count ++;
}

A: Add the address to the envelope (i.e. the list of recipients), but not the message (i.e. the headers).


text:
Q: Customize Elisp plist indentation I don't like how plists are indented in Elisp.
;; current   desired   Python (for comparison)
;; '(a 1     '(a 1     {'a': 1,
;;     b 2     b 2      'b': 2,
;;     c 3)    c 3)     'c': 3}

Tried on M-x emacs-version 24.3.1, ran emacs -Q, typed the plist and pressed C-x h C-M-\.
This indentation makes sense when it isn't a list:
(mapcar (lambda (x) (x + 1))
        '(1 2 3 4))

How do I change formatting settings so that only plists (or, if that's impossible, all quoted lists) have the desired rectangular indentation, but indentation of everything else stays the same? I need this stored locally in an .el file, so that when I edit this file, it is indented as desired, but this behavior doesn't end up anywhere else.

A: You can fix this (in my opinion) bug by overriding lisp-indent-function. The original source of the hack was this Github Gist, which was referenced with some more explanation from this Emacs Stack Exchange answer.
However, I was very uncomfortable overriding a core function like this. For one, it's very opaque—how is a reader supposed to tell what is changed? And worse—what if the official definition of lisp-indent-function changed in the future? How would I know that I needed to update my hack?
As a response, I created the library el-patch, which is specifically designed to address this problem. After installing the package, you can override lisp-indent-function as follows:
(el-patch-defun lisp-indent-function (indent-point state)
  "This function is the normal value of the variable `lisp-indent-function'.
The function `calculate-lisp-indent' calls this to determine
if the arguments of a Lisp function call should be indented specially.

INDENT-POINT is the position at which the line being indented begins.
Point is located at the point to indent under (for default indentation);
STATE is the `parse-partial-sexp' state for that position.

If the current line is in a call to a Lisp function that has a non-nil
property `lisp-indent-function' (or the deprecated `lisp-indent-hook'),
it specifies how to indent.  The property value can be:

* `defun', meaning indent `defun'-style
  (this is also the case if there is no property and the function
  has a name that begins with \"def\", and three or more arguments);

* an integer N, meaning indent the first N arguments specially
  (like ordinary function arguments), and then indent any further
  arguments like a body;

* a function to call that returns the indentation (or nil).
  `lisp-indent-function' calls this function with the same two arguments
  that it itself received.

This function returns either the indentation to use, or nil if the
Lisp function does not specify a special indentation."
  (el-patch-let (($cond (and (elt state 2)
                             (el-patch-wrap 1 1
                               (or (not (looking-at "\\sw\\|\\s_"))
                                   (looking-at ":")))))
                 ($then (progn
                          (if (not (> (save-excursion (forward-line 1) (point))
                                      calculate-lisp-indent-last-sexp))
                              (progn (goto-char calculate-lisp-indent-last-sexp)
                                     (beginning-of-line)
                                     (parse-partial-sexp (point)
                                                         calculate-lisp-indent-last-sexp 0 t)))
                          ;; Indent under the list or under the first sexp on the same
                          ;; line as calculate-lisp-indent-last-sexp.  Note that first
                          ;; thing on that line has to be complete sexp since we are
                          ;; inside the innermost containing sexp.
                          (backward-prefix-chars)
                          (current-column)))
                 ($else (let ((function (buffer-substring (point)
                                                          (progn (forward-sexp 1) (point))))
                              method)
                          (setq method (or (function-get (intern-soft function)
                                                         'lisp-indent-function)
                                           (get (intern-soft function) 'lisp-indent-hook)))
                          (cond ((or (eq method 'defun)
                                     (and (null method)
                                          (> (length function) 3)
                                          (string-match "\\`def" function)))
                                 (lisp-indent-defform state indent-point))
                                ((integerp method)
                                 (lisp-indent-specform method state
                                                       indent-point normal-indent))
                                (method
                                 (funcall method indent-point state))))))
    (let ((normal-indent (current-column))
          (el-patch-add
            (orig-point (point))))
      (goto-char (1+ (elt state 1)))
      (parse-partial-sexp (point) calculate-lisp-indent-last-sexp 0 t)
      (el-patch-swap
        (if $cond
            ;; car of form doesn't seem to be a symbol
            $then
          $else)
        (cond
         ;; car of form doesn't seem to be a symbol, or is a keyword
         ($cond $then)
         ((and (save-excursion
                 (goto-char indent-point)
                 (skip-syntax-forward " ")
                 (not (looking-at ":")))
               (save-excursion
                 (goto-char orig-point)
                 (looking-at ":")))
          (save-excursion
            (goto-char (+ 2 (elt state 1)))
            (current-column)))
         (t $else))))))

A: Found it:
(setq lisp-indent-function 'common-lisp-indent-function)

Here's a sample file:
(setq x  '(a 1
           b 2
           c 3))

;;; Local Variables:
;;; lisp-indent-function: common-lisp-indent-function
;;; End:

I'll just dump my whole indentation config here:
(setq lisp-indent-function 'common-lisp-indent-function)
(put 'cl-flet 'common-lisp-indent-function
     (get 'flet 'common-lisp-indent-function))
(put 'cl-labels 'common-lisp-indent-function
     (get 'labels 'common-lisp-indent-function))
(put 'if 'common-lisp-indent-function 2)
(put 'dotimes-protect 'common-lisp-indent-function
     (get 'when 'common-lisp-indent-function))

A: Here is another less heavyweight solution, based on emacsql-fix-vector-indentation. An advice around calculate-lisp-indent is sufficient.
This only works for plists that use keywords as keys, but that covers a majority of plists. To make this work on quoted lists instead, you could change the looking-at regexp to detect the ' or "`", but that will not cover, say, a nested list.
This can further be packaged up into a minor mode if there is a need to turn it off.
(defun my/inside-plist? ()
  "Is point situated inside a plist?

We determine a plist to be a list that starts with a keyword."
  (let ((start (point)))
    (save-excursion
      (beginning-of-defun)
      (let ((sexp (nth 1 (parse-partial-sexp (point) start))))
        (when sexp
          (setf (point) sexp)
          (looking-at (rx "(" (* (syntax whitespace)) ":")))))))
(define-advice calculate-lisp-indent (:around (func &rest args)
                                      plist)
  (if (save-excursion
        (beginning-of-line)
        (my/inside-plist?))
      (let ((lisp-indent-offset 1))
        (apply func args))
    (apply func args)))


text:
Q: C# System.DirectoryServices.AccountManagement Unknown error (0x80005000) UserPrincipal.IsMemberOf() Similar to the problem in the following MSDN thread: http://social.msdn.microsoft.com/Forums/en-MY/csharplanguage/thread/4c9fea6c-1d0a-4733-a8ac-e3b78d10e999
I am trying to verify whether or not a given user is a member of a group, and our existing functional solutions are too slow (13-16 seconds) and I'm trying to speed it up. I currently have:
public bool IsMemberAD(string userName, string groupName)
{
    var pc = new System.DirectoryServices.AccountManagement.PrincipalContext(System.DirectoryServices.AccountManagement.ContextType.Domain);
    var user = System.DirectoryServices.AccountManagement.UserPrincipal.FindByIdentity(pc, System.DirectoryServices.AccountManagement.IdentityType.SamAccountName,
                                                 userName.ToLower());
    var group = System.DirectoryServices.AccountManagement.GroupPrincipal.FindByIdentity(pc, groupName);

    if (group == null || user == null) return false;

    return user.IsMemberOf(group);
}

What makes this interesting is that it only returns an error when the user is not in the group directly, but rather a member of a group that is within the target group.
For example:
Steve and Sam are two users, and GroupParent and GroupChild are two groups. Steve and GroupChild are members of GroupParent. Sam is a member of GroupChild. If I call this function on (Steve, GroupParent), it returns true. If I call it on (Sam, GroupParent), I get an error. If I call it on ("fdkjskghkf", GroupParent) it returns false.
I linked an article above with similar issues, but his solution did not work for me, I still got the same error. Ideas?

A: Thanks to Jon Theriault here the following code fixed this problem for me.
string strName = System.Security.Principal.WindowsIdentity.GetCurrent().Name; // "MW\\dalem"
// This is here because of a .Net error that gets 0x80005000 on "isUser = user.IsMemberOf(groupU);"
string domainName = strName.Split('\\')[0];
var pc = new PrincipalContext(ContextType.Domain, domainName);

A: I remember when I wrote similar code I did run into some strange issues.  I'm not sure exactly why your call is failing but you can turn your problem around and do something like:
return group.GetMembers(true).Contains(user);

A: Can you try somethig like this :
public bool IsMemberAD(string userName, string groupName)
{
  PrincipalContext context = new PrincipalContext(ContextType.Domain, "WM2008R2ENT:389", "dc=dom,dc=fr", "jpb", "pwd");

  /* Retreive the user principal
   */
  UserPrincipal user = UserPrincipal.FindByIdentity(context, userName);
  if (user == null) return false;

  /* Retreive the group principal
   */
  GroupPrincipal targetGroup = GroupPrincipal.FindByIdentity(context, groupName);
  if (targetGroup == null) return false;

  /* Look for all the groups a user belongs to
   */
  PrincipalSearchResult<Principal> allGroups = user.GetAuthorizationGroups();

  var grp = (from g in allGroups
             where g.Sid == targetGroup.Sid
             select g).FirstOrDefault();

  return (!(grp == null));
}

A: If anyone is interested. Using DirectorySearcher with the following filter is approx 60% faster.
string filter = string.Format("(&(distinguishedName={1})(memberof:1.2.840.113556.1.4.1941:={0}))", dnOfUser, dnOfGroup);
The filter will traverse upwards and not just the parent of the user.

A: GetAuthorizationGroups() does not find nested groups.
To really got all groups a given user is member of included nested groups try this:
using System.Security.Principal

private List<string> GetGroups(string userName)
{
    List<string> result = new List<string>();
    WindowsIdentity wi = new WindowsIdentity(userName);

    foreach (IdentityReference group in wi.Groups)
    {
        try
        {
            result.Add(group.Translate(typeof(NTAccount)).ToString());
        }
        catch (Exception ex) { }
    }

    result.Sort();
    return result;
}

Use Try/Catch because I had some exceptions in a very large AD (half a million objects) with 2 out of 200 groups because my some SIDs (Translate does SID -> Name conversion) were no longer available.
In our huge AD is only takes < 1 second.


text:
Q: which linux to use for embedded-linux-qt 4 development? I want to start development using qt-embedded on my embedded device project. Can you tell me which linux should I use on my computer for development. Well, It should have VMWARE-tools support ( Fedora Core 11 does not have it ).
Thanks, Sunny.

A: I got a whole dedicated website for this issue (crosscompile.org) ;-)
Anyway, we use ubuntu and at http://www.crosscompile.org/static/pages/crosstool.html you can see the toolchain building process
Hope it helps you.


text:
Q: ArcMap to MySQL using Modelbuilder Is it possible to run a model in ArcMap 10.3 and export directly to a MySQL table? Preferably avoiding ArcSDE as well.

A: You can connect to MySQL using OLE DB connection and then use the connection in your model. If you can, it might be easier to write a tiny Python script that you could invoke as part of the model. In the Python script, you would have a more fine-grained control over the table creation as you can use the SQL.
No ArcSDE will be involved whatsoever because ArcGIS doesn't support having MySQL as an enterprise geodatabase.


text:
Q: How to remove index.php in codeigniter with https://www. in the url? <IfModule mod_rewrite.c>
Options +FollowSymLinks
RewriteEngine On

RewriteCond $1 !^(index\.php|resources|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]

RewriteRule ^(.*)\.[\d]{10}\.(css|js)$ $1.$2 [L]
RewriteRule ^search$ webapp/search/

</IfModule>

This code is not working in with https can any help or any solution.
"https://www.royez.com/category/ethnic-wear/kurtas-and-kurtis-97.html" is not working
https://www.royez.com/index.php/category/ethnic-wear/kurtas-and-kurtis-97.html
working.

A: I found the solution of this question. The problem was that when I was redirecting the website to https the curl function stopped working.Now I rewrite the curl post function and problem is solved now.
Thank you all


text:
Q: How can I make sub-columns width expand to their parent width? I have my example here:
http://jsfiddle.net/bfYFq/
Column1 through Column3 divs use up 100% of their parent containers space evenly.  I want the sub columns (sub1, sub2 and sub3) to do the same instead of just being the length of their text.  How can I accomplish this?

A: Try this:
http://jsfiddle.net/bfYFq/2/
Note second selector.


text:
Q: How can I create two segues for a single button in a view controller? I have a root view controller - which is a simple page presented to the user. In this page, there is a UIBarButton that goes to the user profile page.
When the user is in its profile, he/she'll have a back button that will allow him/her to go back to the root view controller.
However, the root view controller is different for admins and clients (there is one standard view controller for admins and one standard view controller for clients).
How can I create two segues that are triggered by the 'Back' profile button? I mean, depending on who is currently logged in (an admin or a client), I would like to go back to their respective pages.
The client cannot go back to the admin's page and neither vice versa.
Is there any way to create these two segues? Or even another/better way? I have tried to do that using storyboard, but when I create the second segue, it deletes the first one linked to the button.

A: You cannot do that but there is other way for that, create two segue bwtween SenderViewController and DestinatrionViewController. After that set action for your button and perform the segue according to your requirements.
@IBAction func buttonAction(_ sender: UIButton) {
    if condition {
        self.performSegue(withIdentifier: "identifier1", sender: nil)
    }
    else {
        self.performSegue(withIdentifier: "identifier2", sender: nil)
    }
}

A: Going off of Nirav D's answer, use an if...else with the condition that they are an admin or client.  But don't control+drag from the button itself, control+drag from the ViewController as seen in the images below.

A: you should handle it in your code.
@IBAction func backClick() {
    if isAdmin /* check condition here  */ {
      // admin work
    } else {
      // normal user work here
    }
}

Then let create segue from storyboard and give it an identifier.
If you want perform segue, let use
performSegue(withIdentifier: "identifier", sender: nil)

if you want go back.
dismissViewControllerAnimated(true, completion: nil)

Hope it help.


text:
Q: Get subtype of Generic List in Dart How can I get the subtype of a List which is a generic type in Dart?
For example:
T is List< String > => String

T is List< SomeObject > => SomeObject

I have researched for this questions but I just found some workarounds.
Any suggestions on this problem?

A: There is no way to get the actual type argument of a list as a type at run-time.
Dart has no way to deconstruct the type List<X> to get to X if the class itself does not provide one.
If dart:mirrors is available, you might be able to use it to find the type as a Type object, which should be sufficient for this case, but mirrors are not available in Flutter.

A: To provide a more recent update for anyone still searching this:
From Dart 2.7 you can use an Extension Method to achieve this:
// extensions/list.dart

extension Typing<T> on List<T> {
    /// Provide access to the generic type at runtime.
    Type get genericType => T;
}

https://dart.dev/guides/language/extension-methods#implementing-generic-extensions
You then use it by importing it and using it like any other List function:
import './extensions/list.dart';

List<String> myList = ['some', 'strings'];

print('Your List type is ${myList.genericType}!');

This works with the caveat that it returns the declared type T so if this is a superclass of the type at runtime, you still only get whatever type the List was declared with in the first place.

A: You can use the following function to get the type parameter of a List:
Type typeOfElementsInList<T>(List<T> e) => T;
main() {
  print(typeOfElementsInList([]));        // dynamic
  print(typeOfElementsInList(<int>[]));   // int
  print(typeOfElementsInList(['test']));  // String
}


text:
Q: General function for suppressing output into bash -- spaced filenames I would like to write bash function to suppress output into command line in bash.
I have included a following into the $HOME/.bashrc
# suspend output to the terminal
noout(){
        $* &>/dev/null &
}

And as an example I have created alias for evince:
alias evince='noout evince'

This works just fine for files without spaces in the file names. However if I launch something like:
evince Jack\ London\ -\ The\ Star\ Rover.pdf

Bash splits the file names into several bits and evince opens several empty windows.
Thanks for any help to make it working.

A: Try this:
noout() {
    "$@" >/dev/null 2>&1 &
}

I'm not sure why you want to do it in the background, but that's your choice.  The relevant aspect of my answer is the quotes and the use of $@ instead of $*.  See also what does "$@" mean in a shell script.


text:
Q: Calculating Variance of sample variance How do you find the variance of sample variance, without using moment generating functions but using the fact that variance of a chi squared distribution with n degrees of freedom, is equal to 2n?
Sample variance is defined as $$S^2=\frac1{n-1}\sum_{i=1}^n\left(X_i-\overline{X}\right)^2.$$

A: Use Fisher's Lemma: $\frac{(n-1)s^2}{\sigma^2} \sim \chi^2_{n-1}$
So $\mathbb{D} \left( \frac{(n-1)s^2}{\sigma^2} \right) = \mathbb{D} \chi^2_{n-1} = 2(n-1)$
$\frac{(n-1)^2 \mathbb{D}(s^2)}{\sigma^4} = 2(n-1) \Rightarrow \boxed{\mathbb{D}(s^2) = \frac{2\sigma^4}{n-1}}$


text:
Q: Use value for dynamic xpath on xslt 1.0 my question/target is: How can I generate the content in firstPart?
(My compiler can't dynamic evaluate()-functions and is based on XSLT 1.0 (VB.NET). I only want to use board tools.)
The output should consist of 2 main parts. In the first part I want to iterate over the person and choose the one which was described in /root/choosePerson. The second part consist of all the persons, which are in /root/person.
Now it's getting difficult: In the output I should get an ID-Attribute, referring to the Person in firstPart. The secondPart has a slight other algorithm, which doesn't show the birthdate.
input.xml:
<root>
<person> <name>bart</name> <gender>m</gender> <birth>01.01.2016</birth> </person>
<person> <name>lisa</name> <gender>w</gender> <birth>01.01.2015</birth> </person>
<person> <name>homer</name> <gender>m</gender> <birth>01.01.2014</birth> </person>
<choosePerson>choose person: 1</choosePerson><!-- it really consist of string and a number -->
<root>

output.xml:
<MyNewRoot>
<firstPart>
<person id="1" gender="m"><name>bart</name> <birth>01.01.2016</birth> </person>
<firstPart>
<secondPart>
<person id="1" gender="m"> <name>bart</name>  </person>
<person id="2" gender="w"> <name>lisa</name>  </person>
<person id="3" gender="m"> <name>homer</name>  </person>
</secondPart>
<MyNewRoot>

What whould I do? I could start with the second part at first:
<xsl:template match="/">
<firstPart>

<firstPart>
<secondPart>
<xsl:apply-templates select="//root/person"/>
</secondPart>
</xsl:template>

<xsl:template match="//root/person"">
<!-- incomplete code (for the sake of clarity), but here I copy the values and create an id through the position() method -->
</xsl:template>

I know dynamic XPaths are not possible and there are also hybrid variants. But are dynamic Xpaths because of "choosePerson" necessary?

A: There is no need for any dynamic xpath here....
You could have the position passed in as a parameter to the template that matches person, along with the name of a child node you want to exlude
<xsl:template match="//root/person">
  <xsl:param name="position" select="position()" />
  <xsl:param name="excludeChild" />

So, for your first part, you would define a variable with the position of the person you wish to choose, and then apply the template to that person, passing in the variable as a parameter
<xsl:variable name="choose" select="substring-after(root/choosePerson, ': ')" />
<xsl:apply-templates select="root/person[position()=$choose]">
  <xsl:with-param name="position" select="$choose" />
</xsl:apply-templates>

For the second part, you can use the default position, but pass in the parameter to exclude the "birth" element
<xsl:apply-templates select="root/person">
  <xsl:with-param name="excludeChild" select="'birth'" />
</xsl:apply-templates>

Try this XSLT.
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:output indent="yes" />

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

  <xsl:template match="/">
    <firstPart>
      <xsl:variable name="choose" select="substring-after(root/choosePerson, ': ')" />
      <xsl:apply-templates select="root/person[position()=$choose]">
        <xsl:with-param name="position" select="$choose" />
      </xsl:apply-templates>
    </firstPart>
    <secondPart>
      <xsl:apply-templates select="root/person">
        <xsl:with-param name="excludeChild" select="'birth'" />
      </xsl:apply-templates>
    </secondPart>
  </xsl:template>

  <xsl:template match="//root/person">
    <xsl:param name="position" select="position()" />
    <xsl:param name="excludeChild" />
    <person id="{$position}" gender="{gender}">
      <xsl:apply-templates select="*[local-name() != $excludeChild]" />
    </person>
  </xsl:template>

  <xsl:template match="gender" />
</xsl:stylesheet>


text:
Q: Cual seria la expresión regular para que no muestre los archivos ocultos por el sistema PHP Al recorrer los directorios y mostrar todos los archivos .XML, tambien me muestra en salida los archivos ocultos por el sistema, que son la copia de los archivos XML, me gustaría opiniones de como evitar los archivos ocultos.
 $regex = new RegexIterator($iterator, **'/^.+\.xml$/i'**,
 RecursiveRegexIterator::GET_MATCH);

A: La implementación dependerá de tu hosting/máquina donde tengas el intérprete php.
En Linux/Unix cualquier fichero que empiece por punto . se considera un fichero oculto.
.hola.txt => Oculto
hola.txt  => Visible

Así pues, simplemente te bastaría con mirar si el primer caracter del string es un punto para saber si el fichero es oculto
substr($mi_string, 0, 1) == '.'
Sin embargo, en Windows se consideraría una propiedad o atributo del fichero. Deberías hacer una llamada al sistema para evaluar esta propiedad.
Aquí tienes un método que te serviría. Combina la llamada via exec y dentro lo que hay es código .bat
function is_hidden_file($fn) {

    $attr = trim(exec('FOR %A IN ("'.$fn.'") DO @ECHO %~aA'));

    if($attr[3] === 'h')
        return true;

    return false;
}

La función está sacada de este comentario de php.net

A: En tu caso, si estas utilizando symfony y utilizas el componente finder https://symfony.com/doc/current/components/finder.html, tienes el metodo:
ignoreDotFiles
Como ejemplo, podrias utilizar lo siguiente:
use Symfony\Component\Finder\Finder;

$finder = new Finder();
$finder->files()->in(__DIR__)->ignoreDotFiles(true);

NOTA:
la propia documentacion indica que los archivos "hidden" son los que considera aquellos con nombre iniciado en . Esto es asi en determinados S.O., pero en windows concretamente se utilizan atributos de archivo.
Tal como te indica @julio, quizas deberias utilizar un metodo como el anterior para asegurarte de los atributos en sistemas windows.


text:
Q: get a clean file copy from git In svn, sometimes I delete a local file then use 'svn update' to get a clean copy. How can I do it in git?
git pull/fetch didn't work. The only way I figured out is use diff which is incontinent. Thanks.
I'm using tortoiseGit.

A: Files are staged and committed differently in git and svn. The gist of the difference from git's perspective is that with git a file is versioned through a staging area called an index, from there it goes as part of a commit to the local graph of commits that your branch points to, and from there it is propagated to the remote graph of commits when you push the branch to the remote server.
While acknowledging that "latest" is somewhat misleading, to simplify a bit, there are four "latest" file versions: the one in the working tree, the one in the index, the one in the local branch and the one in the remote branch. And the local and the remote branch are not necessarily in sync.  So when you say that you want a clean copy of a file you have to refine the question first - and answer to yourself which of the four you are after.
Latest version from the index:
$ git checkout -- /path/to/file

Latest version from the local branch (will also discard the file in the index):
$ git checkout HEAD -- /path/to/file

Latest version from the remote branch (as current on the local machine, may be stale):
$ git checkout origin/master -- /path/to/file

Latest version from the remote branch (updated to the most recent, bar race conditions - not stale):
$ git fetch
$ git checkout origin/master -- /path/to/file

Latest version from the remote branch (both updated to most recent, and synchronised with the local branch):
$ git pull
$ git checkout master -- /path/to/file

A: Try using git checkout:
git checkout <filename>

Note that if you are in the middle of a merge or rebase, and want to resolve a conflict
you need to add --ours or --theirs to let git know which <filename> you want.
e.g.:
git checkout --ours <filename>

If you want a filename as it appeared elsewhere in the history (or as it appears on another branch)
git checkout <branch-name or SHA> -- <filename>

Note the -- separates git REF names from filenames.


text:
Q: Is there a way to stop LWC Local Development Server to auto refreshing when component file change? LWC Local Development Server auto refreshes page whenever any LWC component files change. Sometimes I change JS code but I'm not finished with it, I need to go back to console to refer the console logs/network requests but then I see the page got refreshed and I need to enter the test data all over again. I want to disable this behaviour and want to do the page refresh myself.
I checked the SFDX CLI Commands reference but, I guess, since Local Dev Server is in beta hence there is no mention of force:lightning:lwc:start command reference.
Appreciate if anyone could help with this. Thanks!

A: In VS Code, terminal pane right top side open bash and kill terminal will stop local development server


text:
Q: How to reliably calculate the memory address of an object I created my own memory manager by overloading the new and delete operators of my base class. The overloaded operators maintain a linked list of memory allocations and I also store the file and line number of the allocation. It works with multiple inheritance as well, since the delete operator always receives the correct memory address (i.e. the address I returned from 'new'). What is the best way for me to get the memory address of the object (i.e. the memory address of the first parent)?
I want to create methods that, at run-time, can return the allocation file and line number. With multiple inheritance the 'this' pointer might not point to the correct memory address (it is sometimes offset by 8 bytes). I understand why it is offset, but I'm looking for a way to reliable calculate the correct memory address originally returned by the new operator.

A: If the class hierarchy is polymorphic, you can use dynamic_cast<void*>(this) to obtain the address of the most derived object of which *this is a subobject.
See also this question.

If your class hierarchy is not polymorphic, you cannot know dynamically whether a given base object is most-derived, and if it is not, you cannot know what its most-derived object is.  However, in that case you also cannot destroy the object since you don't have access to the most-derived destructor, and so you will generally not have need to releasing the memory. It is true, however, that ou cannot look up an object's allocation trace if you cannot determine its most-derived object.

A: You cannot do it. Each C++ compiler is allowed to do whatever it wants with the storage you return from operator new. It can choose any sort of layout, and then the result of the new operation is some pointer into somewhere in the memory returned from the operator. The address of the most derived object is not the same as the value returned by the operator.
Since you haven't specified that you are using some particular version of some particular compiler, no one can give you an answer that depends on knowledge of the implementation-dependent specifics.


text:
Q: Retain Session Data in .NET Core I have configured an application to use sessions but I have a concern and I am not sure what else I might need to do.
When the user logs in, I set a Session variable and that works fine. If I choose to 'Remember Me' at login, close the browser and then reopen the website, it remembers the logged in user, but not the other session variable that I set.
The configuration and supporting code is as follows:
Startup.cs
//Configure Services
...
services.AddHttpContextAccessor();
services.AddDistributedMemoryCache();
services.AddSession(options =>
{
      options.IdleTimeout = TimeSpan.FromMinutes(60);
      options.Cookie.HttpOnly = true;
      options.Cookie.IsEssential = true;
 });
...

//Configure()
app.UseSession();

I set the session at login like this:
var result = await _signInManager.PasswordSignInAsync(Input.UserName, Input.Password, Input.RememberMe, lockoutOnFailure: false);
            if (result.Succeeded)
            {
                HttpContext.Session.SetInt32("SessionVariable", 20);
                return LocalRedirect(returnUrl);
            }

As stated before, this works fine. If I close the browser and reopen the app, the value is no longer available in the application.
Any guidance is appreciated.

A: Firstly I don't recommend what you're trying to do. The session cookie has its standard behavior (as by design) so you should follow it (I'm not so sure about the detailed reason because I'm not very good at security aspect).
I believe that you can find some alternative solution such as using local storage on the client or use persistent cookie explicitly.
However because it's possible, I would like to show the way you can achieve it. As long as you explicitly set the expiration time for it, it should still be OK (so instead of being cleared after the browsers closing, it will be cleared on a specific time).
Session has 2 parts to be stored:

*

*the session key is stored as a cookie value.

*the session data is stored as in-memory cache on the server side.

What you configure (e.g: IdleTimeout) is just for session data. The session key is set as a response cookie using a separate CookieOptions. This options is built from the SessionOptions.Cookie (a CookieBuilder) which is initialized with a default implementation in which the CookieOptions.Expires will be left as default(DateTimeOffset).
So to override it, you can provide your own implementation of CookieBuilder, like this:
public class ConfigurableExpirationCookieBuilder : CookieBuilder
{
    readonly CookieBuilder _defaultSessionCookieBuilder;
    public ConfigurableExpirationCookieBuilder(CookieBuilder defaultSessionCookieBuilder)
    {
        _defaultSessionCookieBuilder = defaultSessionCookieBuilder;
    }
    public override string Domain { get => _defaultSessionCookieBuilder.Domain; set => _defaultSessionCookieBuilder.Domain = value; }
    public override bool HttpOnly { get => _defaultSessionCookieBuilder.HttpOnly; set => _defaultSessionCookieBuilder.HttpOnly = value; }
    public override bool IsEssential { get => _defaultSessionCookieBuilder.IsEssential; set => _defaultSessionCookieBuilder.IsEssential = value; }
    public override TimeSpan? MaxAge { get => _defaultSessionCookieBuilder.MaxAge; set => _defaultSessionCookieBuilder.MaxAge = value; }
    public override string Name { get => _defaultSessionCookieBuilder.Name; set => _defaultSessionCookieBuilder.Name = value; }
    public override SameSiteMode SameSite { get => _defaultSessionCookieBuilder.SameSite; set => _defaultSessionCookieBuilder.SameSite = value; }
    public override string Path { get => _defaultSessionCookieBuilder.Path; set => _defaultSessionCookieBuilder.Path = value; }
    public override CookieSecurePolicy SecurePolicy { get => _defaultSessionCookieBuilder.SecurePolicy; set => _defaultSessionCookieBuilder.SecurePolicy = value; }
}

The default cookie builder is private and init all the default (standard) values in its constructor. So we override all the properties to keep those default values in the custom bookie builder. Of course the Expiration is not overridden, it can be set by your code freely. The default cookie builder lets it as null and protect against changing it like this:
public override TimeSpan? Expiration {
      get => null;
      set => throw new InvalidOperationException(nameof(Expiration) + " cannot be set for the cookie defined by " + nameof(SessionOptions));
}

Without Expiration being set, the built cookie will be treated as session cookie with standard behaviors.
Now you can configure that Cookie along with your IdleTimeout to achieve your desired behavior:
services.AddSession(options =>
{
   var sessionTimeout = TimeSpan.FromMinutes(60);
   options.Cookie = new ConfigurableExpirationCookieBuilder(options.Cookie);
   //for session key
   //NOTE: this is not a sliding timeout like set by IdleTimeout
   //the actual expire time will be this added with DateTimeOffset.Now
   //at the time the session is established.
   options.Cookie.Expiration = sessionTimeout;
   //for session data
   options.IdleTimeout = sessionTimeout;
   options.Cookie.HttpOnly = true;
   options.Cookie.IsEssential = true;
});

Finally, I would not recommend this, so please don't try to leave some comments like: if it's not recommended, just don't provide any solutions. I love technical aspects more than trying to follow rules & standards. When it's possible, we can show how it's possible instead of trying to hide it. And actually in some real scenarios, some things cannot always be kept sticking to some strict rule.


text: Q: Ошибки при компиляции: cc1plus.exe:-1: ошибка: out of memory allocating 65536 bytes Юзаю qt, при выборе компилятора в настройках проекта msvc - все успешно комплится без ошибок, если как компилятор выбираю mingw - компиляция завершается следующей ошибкой: cc1plus.exe:-1: ошибка: out of memory allocating 65536 bytes


text:
Q: How to get python API to access Smartsheet I am following the smartsheet API's python-sdk example to do some practice.
Below are my steps (using Python 3.4.4 on macOS 10.7.5):

*

*installed the SDK package from their GitHub repo

*installed pip using pip install smartsheet-python-sdk in my  terminal

*created a .py file and moved it into the SDK file

Issue
When I run it, I got following error message:
Traceback (most recent call last):
  File "/Users/canny_aiyaya/Desktop/smartsheet-python-sdk-master/smartsheet/charity.py", line 5, in <module>
    import smartsheet
  File "/Users/canny_aiyaya/Desktop/smartsheet-python-sdk-master/smartsheet/smartsheet.py", line 28, in <module>
    import requests
ImportError: No module named 'requests'

Code in the .py file
import smartsheet
ss_client = smartsheet.Smartsheet(access_token)
ss_client.errors_as_exceptions(True)

Analysis
I looked for some possible solutions, and try to install requests on my terminal using sudo pip3 install requests, but it shows:

No matching distribution found for requests

This is my first time trying to use API on Smartsheet, any supports/links/videos will very helpful.

A: There are a number of dependencies. You can run python setup.py install from the Smartsheet SDK directory to install them.


text:
Q: filter listView containing sms list with contacts I have a listView created using SimpleCursorAdapter.
lv = (ListView) findViewById(R.id.myList);
    lv.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_INSET);
    //Cursor c = this.getContentResolver().query(Uri.parse( "content://sms/conversations?simple=true"), null, null, null, "normalized_date desc" );
    final Uri inboxURI = Uri.parse("content://mms-sms/conversations/");
    final String[] reqCols = new String[] { "_id", "address", "body" };
    final String[] projection = new String[]{"*"};

    cr = getContentResolver();
    Cursor c = cr.query(inboxURI, projection, null, null, Telephony.Sms.Inbox.DEFAULT_SORT_ORDER);
    madapter = new simpleLayout(this, R.layout.list_row, c, new String[] { "body", "address" }, new int[] {R.id.text_msg, R.id.phone_number });
    lv.setAdapter(madapter);
    lv.setTextFilterEnabled(true);

I have also added filter to the listview
madapter.setFilterQueryProvider(new FilterQueryProvider() {
        public Cursor runQuery(CharSequence constraint) {
            return getContentResolver().query(inboxURI, reqCols, "address" + " LIKE '" + constraint + "%'", null, null);
        }
    });

before the listView only contained the address but now I have mapped them with real contact numbers so the filter is not working any more. How should I return the query so that it will work again


text:
Q: Function to generate two random numbers between 0 and 1 as a pair of [x y] Haven't used clojure in a while would appreciate some help
I tried doing
(defn num [] (rand-int 2) (rand-int 2))

A: (defn randints [] [(rand-int 2) (rand-int 2)])

if you meant random integers between 0 and 1.  Or
(defn randfloats [] [(rand) (rand)])

if you meant random floating point numbers between 0 and 1.


text:
Q: Availability of docstring from my own functions across different scripts in Spyder editor I'm coding in Spyder 5.0.5 for Python 3.8 and I tend to document my code.
If I write docstring for a function in a certain script, then, every time I use that function in that very same script, if I place the mouse in the function's name, I get a pop-up displaying all the info from the docstring. Same as it would happen with any function imported from any previously installed package.
However, if I import that very same function (the one I wrotte) into another script and place the mouse where I'm calling it, all I get is a pop-up displaying "No documentation available".
How can I make docstring from my own functions available across different scripts?


text:
Q: Split a line at the first special character Python So I have a line of text like this getting read into my program:
00001740 n 3 eintiteas aonán beith 003 @ 00001930 n 0000 ~ 00002137 n 0000 ~ 04424418 n 0000

And I want to split that in two at the first special character. Most of the time the line is split by the '@' symbol, but in some cases a different character comes up. ('~', '+', '#p', '#m', '%p', '=').
So far I have it working for the '@' character:
def split_pointer_part(self, line):
    self.before_at, self.after_at = line.partition('@')[::2]
    return self.before_at, self.after_at

How do I change this to work for the first one that shows up out of the list of special characters?

A: You can use a regular expression:
>>> import re
>>> line = "00001740 n 3 eintiteas aonán beith 003 @ 00001930 n 0000 ~ 00002137 n 0000 ~ 04424418 n 0000"
>>> re.split(r'(?:#p|#m|%p|[@~+=])', line, 1)
['00001740 n 3 eintiteas aon\xc3\xa1n beith 003 ', ' 00001930 n 0000 ~ 00002137 n 0000 ~ 04424418 n 0000']

A: Take a look at re.split. It works like the regular split but accepts a regular expression.
Example:
import re
string = "00001740 n 3 eintiteas aonán beith 003 @ 00001930 n 0000 ~ 00002137 n 0000 ~      04424418 n 0000"
print(re.split(r'\@|\~|\+|\#p|\#,|\%p|\=', string))

A: One approach is to check if any of the special character comes up. Lets store the first special character that came up in the variable specialChar. You can now call line.partition(specialChar).


text:
Q: Pod presets not working on minikube I'm trying to test out pod presets on minikube.  I run the following command to start minikube:

minikube start --vm-driver hyperv --hyperv-virtual-switch switch name --extra-config=apiserver.admission-control="NamespaceLifecycle,LimitRanger,ServiceAccount,PersistentVolumeLabel,DefaultStorageClass,DefaultTolerationSeconds,MutatingAdmissionWebhook,ValidatingAdmissionWebhook,ResourceQuota,PodPreset"

Once the cluster starts up, I run kubectl get podpreset, which gives me back the server doesn't have a resource type 'podpreset'.  I was under the impression that I just had to add PodPreset to admission control and then pod presets would work.  Does anyone have any suggestions?
Some additional info:
OS: Windows 10

minikube version: v0.28.0

kubectl version:

Client Version: version.Info{Major:"1", Minor:"10", GitVersion:"v1.10.3", GitCommit:"2bba0127d85d5a46ab4b778548be28623b32d0b0", GitTreeState:"clean", BuildDate:"2018-05-21T09:17:39Z", GoVersion:"go1.9.3", Compiler:"gc", Platform:"windows/amd64"}

Server Version: version.Info{Major:"1", Minor:"10", GitVersion:"v1.10.0", GitCommit:"fc32d2f3698e36b93322a3465f63a14e9f0eaead", GitTreeState:"clean", BuildDate:"2018-03-26T16:44:10Z", GoVersion:"go1.9.3", Compiler:"gc", Platform:"linux/amd64"}

A: Check how Minikube is starting its Kubeapiserver: see "Kubernetes PodPreset not working".
You need to check "Enable Pod Preset", especially:

You have enabled the API type settings.k8s.io/v1alpha1/podpreset.
  For example, this can be done by including settings.k8s.io/v1alpha1=true in the --runtime-config option for the API server.


text:
Q: How turn off airplane mode? I have a problem getting the WIFI to work in Ubuntu 20.04. In short i can not use WIFI, cause of airplane on. I can not turn off airplane mode. My laptop: Sony VAIO VGN-FW560F.
Output of: sudo rfkill unblock all and sudo rfkill list -
0: sony-wifi: Wireless LAN
    Soft blocked: no
    Hard blocked: yes
1: sony-bluetooth: Bluetooth
    Soft blocked: no
    Hard blocked: yes
2: phy0: Wireless LAN
    Soft blocked: no
    Hard blocked: yes

A: On page 12 of "Sony VGN-FW Series User Guide" (see:
https://www.sony.com/electronics/support/res/manuals/W001/W0011700M.pdf) it is clearly shown that the "WIRELESS switch [9]" is on the front side of the computer. Please, make sure it is ON, i.e. at right position.
 .
I know from experience that, as time passes, this switch may become loose and may not work properly.
Note also that there is no Fn (soft) keyboard combination to toggle WiFi as in other brand of computers.


text:
Q: Can't edit credentials Rails 5.2 When I open the file this way:
EDITOR="atom --wait" bin/rails credentials:edit

I get a brand new file that is assigned a new name (a number.credentials.yml) and reports "New credentials encrypted and saved," and I am not given the opportunity to edit the file.
Then I type:
bin/rails credentials:show

and I get the default aws: 123 etc....
 So I delete both the credentials.yml.enc and the master key and start over, with the same results. the new credentials.yml.enc is created with the default verbage, but I cannot edit it.
I am using ruby 2.5.3 and rails 5.2.2. Ubuntu 18.04 if that matters. I have followed all the recommendations given elsewhere on this exact topic, but nothing works for me.

A: With rails credentials:show, you cannot edit your credentials.yml. You have to use EDITOR="atom --wait" rails credentials:edit to edit your credentails.yml.
Delete your master.key than you need to run the command EDITOR="atom --wait" rails credentials:edit which it won't find the master.key and creates new one with crendetials.yml.enc. After that, add some stuffs and close that file with CTRL + W. Now you can see the result with rails credentials:show.

A: I was having the exact same issue. It appears the issue is the quotes surrounding the specified text editor. (Note: I am running MacOS, not Ubuntu):
Doesn't work as intended
EDITOR="vim" rails credentials:edit

New credentials encrypted and saved.

But I didn't want to create new credentials. I wanted to edit my existing credentials.yml.enc file.
Works as intended
EDITOR=vim rails credentials:edit

This does what I expect: opens up the credentials.yml.enc file in vim in an unencrypted format.

A: You need install vim for ubuntu, use this commmand:
sudo apt-get install vim
I had the same problem and solutioned with that. ;)