text:
Q: Unexpected results when using a std::priority_queue of struct pointers I'm sure that the code is pretty self-explicative, so I go straight to the point. Please ask for more details if the code is unclear.
Foo.h
=====

#include <iostream>

class Foo
{
public:
    virtual ~Foo(){};
    Foo();
    Foo(const int b);
    bool operator<(const Foo&) const;
    friend std::ostream& operator<<(std::ostream&, const Foo&);

    int b;
};

Foo.cpp
=======

#include "Foo.h"

Foo::Foo()
{
}

Foo::Foo(const int b)
{
    this->b = b;
}

bool Foo::operator<(const Foo& other) const
{
    return b < other.b;
}

std::ostream& operator<<(std::ostream& os, const Foo& f)
{
    os << '{' << f.b << '}';
    return os;
}

Bar.h
=====

#include <vector>
#include <queue>
#include "Foo.h"

class Bar
{
    struct FooPp
    {
        Foo f;
        int a;

        FooPp(const Foo&);
        bool operator<(const FooPp&) const;
        friend std::ostream& operator<<(std::ostream& os, const FooPp& fpp)
        {
            os << '[' << fpp.a << "]," << fpp.f;
            return os;
        }
    };

    struct foopp_compare
    {
        bool operator()(const FooPp* pA, const FooPp* pB ) const
        {
            return *pA < *pB;
        }
    };

public:
    virtual ~Bar(){};
    Bar(const std::vector<Foo>&);

    std::vector<FooPp> vf;
    std::priority_queue<FooPp*, std::vector<FooPp*>, foopp_compare> fq;
};

Bar.cpp
=======

#include "Bar.h"

Bar::FooPp::FooPp(const Foo& f)
{
    this->f = f;
    a = f.b;
}

bool Bar::FooPp::operator<(const FooPp& other) const
{
    return f < other.f;
}

Bar::Bar(const std::vector<Foo>& vf)
{
    for (std::vector<Foo>::const_iterator f = vf.begin();
            f != vf.end();
                ++f)
    {
        this->vf.push_back(*f);
        fq.push(&(this->vf.back()));
    }
}

main.cpp
========

#include <iostream>
#include "Bar.h"

int main()
{
    // Foo
    Foo f1(1);
    Foo f2(6);
    std::vector<Foo> vf;
    vf.push_back(f1);
    vf.push_back(f2);
    // Bar
    Bar b(vf);
    // print b.vf: [1]{1}, [6],{6};
    std::cout << b.vf[0] << '\n';
    std::cout << b.vf[1] << '\n';
    // print the top of the prio_q: [6],{6};
    std::cout << *(b.fq.top()) << '\n';
    // change "a" in b.vf[1] -> [-12],{6}
    b.vf[1].a = -12;
    // print b.vf[1]: [-12],{6};
    std::cout << b.vf[1] << '\n';
    // print the top of the prio_q: [-12],{6};
    std::cout << *(b.fq.top()) << '\n';
    return 0;
}

And this is what I get instead:
./example
[1],{1}            // OK
[6],{6}            // OK
[1],{135704652}    // ??
[-12],{6}          // OK
[1],{135704652}    // ??

It seems that the std::vector<FooPp> is initialized correctly, but I do not understand what's happening with the std::priority_queue, which should have been initialized with pointers to elements of the std::vector<FooPp>. What's wrong?
By the way.. this is the makefile for those of you that are on Unix machines
Makefile
========

CXX      := g++
LD       := g++
CXXFLAGS := -Wall -g -O0 --std=c++0x -I.

SRC := $(shell ls *.cpp)
OBJ := ${SRC:%.cpp=%.o}

.PHONY: clean

example: $(OBJ)
    $(LD) $^ -o $@

clean:
    rm -rf $(OBJ) *~ example

A: You're modifying the underlying vector vf with each push, and invalidating all iterators (and addresses taken from them therein) in the process.
The quickest way I see to fix this is modifying the constructor for Bar:
Bar::Bar(const std::vector<Foo>& vf)
    : vf(vf.begin(), vf.end())
{
    for (std::vector<FooPp>::iterator f = this->vf.begin();
         f != this->vf.end();
         ++f)
    {
        fq.push(&(*f));
    }
}

Output
[1],{1}
[6],{6}
[6],{6}
[-12],{6}
[-12],{6}

There are a host of other things I would do with this code (using initializer lists, etc.), but that is about the smallest code change I can think of that will deliver you something that works.

A: I think that the problem is here
Bar::Bar(const std::vector<Foo>& vf)
{
    for (std::vector<Foo>::const_iterator f = vf.begin();
            f != vf.end();
                ++f)
    {
        this->vf.push_back(*f);
        fq.push(&(this->vf.back()));
    }
}

When you add new elements to the vector it can reallocate the used memory. So this value &(this->vf.back()) becomes invalid.


text:
Q: WHERE clause is not filtering in logical order I'm writing a general search Stored Procedure to search in a table based on many filters which user can select in the UI (using MS-SQL 2008).
Here is ther simplified version:
CREATE PROCEDURE SearchAll
    @FirstName NVARCHAR(MAX) = NULL,
    @LastName NVARCHAR(MAX) = NULL,
    @Age INT = NULL
AS
    SELECT *
    FROM persons
    WHERE
        (@FirstName IS NULL OR FirstName = @firstname)
        AND (@LastName IS NULL OR LastName = @LastName)
        AND (@Age IS NULL OR Age = @Age)

It seems that if I pass NULL to @Age there'll be no performance cost. But, when I'm testing with huge amount of data, I have a great perfomance lost!
Here is the queries which are the same logicaly but VERY different practically:
DECLARE @FirstName NVARCHAR(MAX) = NULL
DECLARE @Age INT = 23
------------First slow------------
SELECT *
FROM persons
WHERE
    (@FirstName IS NULL OR FirstName = @firstname)
    AND (@Age IS NULL OR Age = @Age)
------------Very fast------------
SELECT *
FROM persons
WHERE
    Age = @Age

Did is miss a point?
I know that SQL engine finds the best match for indexes, and ... (before running the query),but it's obvious that: @FirstName IS NULL and there's no need to analyse anything.
I've also tested ISNULL function in the query (the same result).

A: Queries that contain this construct of @variable is null or @variable = column are a performance disaster. This is because SQL plans are created so they work for any value of the variable. For a lengthy discussion of the topic, the problems and possible solutions see Dynamic Search Conditions in T-SQL

A: The problem, as has already been mentioned, is that the query plan will be built to work with any value of the variables. You can circumvent this by building the query with only the paremeter required, as follows:
CREATE PROCEDURE SearchAll
    @FirstName NVARCHAR(MAX) = NULL,
    @LastName NVARCHAR(MAX) = NULL,
    @Age INT = NULL
AS
BEGIN
    DECLARE @sql NVARCHAR(MAX), @has_where BIT
    SELECT @has_where = 0, @sql = 'SELECT * FROM persons '

    IF @FirstName IS NOT NULL
        SELECT @sql = @sql + 'WHERE FirstName = ''' + @FirstName + '''', @has_where = 1
    IF @LastName IS NOT NULL
        SELECT @sql = @sql + CASE WHEN @has_where = 0 THEN 'WHERE ' ELSE 'AND ' END + 'LastName = ''' + @LastName + '''', @has_where = 1
    IF @Age IS NOT NULL
        SELECT @sql = @sql + CASE WHEN @has_where = 0 THEN 'WHERE ' ELSE 'AND ' END + 'Age = ' + CAST(@Age AS VARCHAR), @has_where = 1

    EXEC sp_executesql @sql
END

redpajama_set_name: RedPajamaStackExchange


text:
Q: Adding the output of one graph to another graph I would like to find a way to translate and add the bottom graph (from y = -20 to 0) onto the above graph (from y = 0-20) so that the final domain is between y = 0 to 20:

However, I am finding problems doing it, as the graph I used to draw the bottom graph (R12) has already a negative input, thus it will not show up on the positive y-axis. Here is my code:
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np

N = 1001
lower = 0
upper = 20
u = np.linspace(lower, upper, N)
t1a, t3a = np.meshgrid(u,-u)
t1, t3 = np.meshgrid(u,u)
omega = 10
delta = 5
tau = 2
mu = 1
t2 = 0.1

def g(t):
    return delta * (omega ** 2) * (tau ** 2) * ((np.e ** (-t/tau))+(t/tau)-1)

R12 = 1 * (mu ** 4) * (np.e **(-1j * omega * (t3a-(t1a)))) * (np.e ** (-g(t1a)+g(t2)-g(t3a)-g(t1a+t2)-g(t2+t3a)+g(t1a+t2+t3a)))
R45 = 1 * (mu ** 4) * (np.e ** (-1j * omega * (t3+t1))) * (np.e ** (-g(t1)-g(t2)-g(t3)+g(t1+t2)+g(t2+t3)-g(t1+t2+t3)))
R12_fft = np.fft.fftshift((np.fft.fft2((R12)))) / np.sqrt(len(R12))
R45_fft = np.fft.fftshift((np.fft.fft2((R45)))) / np.sqrt(len(R45))
R_pure = (R12_fft + R45_fft)

plt.contourf(t1a,t3a,R12_fft, cmap = 'seismic')
plt.contourf(t1,t3,R45_fft, cmap = 'seismic')
plt.xlabel('${\omega}_{3}$', fontsize = 24)
plt.ylabel('${\omega}_{1}$', fontsize = 24)
plt.xlim(-20, 20)
plt.ylim(-20, 20)
plt.gca().set_aspect('equal', adjustable='box')
plt.colorbar()
plt.show()

As an example, if I try to do the simple adding:
plt.contourf(t1,t3,R_pure, cmap = 'seismic')

it basically gives me back the same shape of the graph. What I would like instead is superimposing the bottom graph onto the top and adding the output together. Is there any way I can achieve this? Thank you!

A: I feel like it's a bit too dumb, so it's probably wrong.
R_pure = (R12_fft + abs(R45_fft))


text:
Q: SOQL Count() limits Summer '18 changed Count() impact on query row limit from "number of records matched" to 1.
Is there still some form of a limit, like selectivity criteria related limits, or can an arbitrary number of records be counted?

A: We have found that COUNT queries can still face limits in the form of exceeding CPU limits in the transaction, and I believe this is actually caused when the WHERE clause for the SOQL query requires significant filter-related processing against unindexed columns.
This help page discusses "selectivity":

For best performance, SOQL queries must be selective, particularly for queries inside triggers. To avoid long execution times, the system can terminate nonselective SOQL queries. Developers receive an error message when a non-selective query in a trigger executes against an object that contains more than 200,000 records. To avoid this error, ensure that the query is selective.

It goes on to say:

A query is selective when one of the query filters is on an indexed field and the query filter reduces the resulting number of rows below a system-defined threshold. The performance of the SOQL query improves when two or more filters used in the WHERE clause meet the mentioned conditions.

Even then, the platform doesn't always terminate the query and you face CPU limits being exceeded instead of the selectivity exception. I have a hunch this happens when the platform is forced to perform some post-query, in-memory filtering to fully apply all the conditions in the WHERE clause.


text:
Q: Ubuntu 10.04 keep disconnecting idle ssh connections after few minutes? I just installed a new Ubuntu Server 10.04 and I observed that if I do not use my connection for a while it will just disconnect me.
This never happened to me on CentOS or even on older Ubuntu.
/var/log/auth does not contain any hints regarding the disconnections.
Inside /etc/ssh/sshd there is line with TCPKeepAlive yes. What is happening?

A: please edit you sshd config:
nano /etc/ssh/sshd_config
search for "ClientAliveInterval"
change it to 0
reload sshd
/etc/init.d/ssh restart

A: Based on your comment, just add the following to your /etc/ssh/sshd_config
UseDNS no


text:
Q: Как запросить данные с PostgreSQL в обратном порядке Для получения данных с БД PostgreSQL я использую данный код:
async getAll(req, res){                                          //get all and get filtered (by need) by manufacturer, body type
    let {manufacturerId, carNameId,limit,page} = req.query
    page = page || 1
    limit = limit || 100
    let offset = page * limit - limit                                 //skip limit cars on next page
    let cars;
    if (!manufacturerId && !carNameId){                                          //get all
        cars = await Car.findAndCountAll({limit, offset})                           //for knowing total cars amount use findAndCountAll() instead of findAll() - for pagination
    }
    if (manufacturerId && !carNameId){                                                          //filtering by manufacturer
        cars = await Car.findAndCountAll({where: {manufacturerId}, limit, offset})
    }
    if (!manufacturerId && carNameId){                                          //filtering by car name
        cars = await Car.findAndCountAll({where: {carNameId}, limit, offset})
    }
    if (manufacturerId && carNameId){                                           //filtering by car name and manufacturer
        cars = await Car.findAndCountAll({where: {carNameId,manufacturerId}, limit, offset})
    }
    return res.json(cars)
}

Здесь идет запрос текущей страницы пользователя и количество отображаемых на странице элементов, далее - фильтрация.
Мне нужно отображение элементов в обратном порядке. Чтобы на клиент приходил уже перевернутый JSON. Не совсем понимаю как это сделать правильно.
Мои попытки привели меня только к обратному порядку на странице. Условно: на странице не с 1 по 10 а с 10 по 1.
Цель: если на странице по 10 элементов, а всего в БД 100 элементов, то на первой странице должен быть с 100 по 90 элемент


text:
Q: Add class in drop area (file input) when dragging an external image over Hi how to add class using Jquery when I'm dragging element over drop area.
This is my HTML

   <form action="">
      <input class="uploadfile" type="file" id="imageLoader" name="imageLoader">

Drag and Drop or browse from you computer

   </form>

I want to add class in upload div class something like this

A: You can do this with javascript by "listen" to event dragover

var upload = document.querySelector('.upload');

upload.addEventListener("dragover", function( event ) {
  this.classList.add('dragging');
}, false);

upload.addEventListener("drop", function( event ) {
  this.classList.remove('dragging');
}, false);
.dragging {
  border:1px solid green;
}

  <form action="">
    <input class="uploadfile" type="file" id="imageLoader" name="imageLoader">

Drag and Drop or browse from you computer

  </form>

A: To remove dragging class when you leave drag area you can add this to Mosh Feu code:
upload.addEventListener("dragleave", function( event ) {
    this.classList.remove('dragging');
}, false);


text:
Q: How to order slice of pointers using gqlgen and dataloaden (graphql dataloader) if some keys are NULL? I have these entities:

*

*Golang struct:

type Player struct {
    ID        int
    CreatedAt time.Time
    City      City
    CityID    int
    Team      *Team
    TeamID    *int
    Score     int
}

*

*GraphQL schema:

type Player {
  id: ID!
  createdAt: Time!
  City: City!
  Team: Team
  Score: Int!
}

As you can see:

*

*City is mandatory

*Team (and TeamID in Golang struct) is NOT mandatory, so I'm using a pointer type (*)
What I don't understand now is how to use dataloaden (a GraphQL dataloader).
Here the generated code for CityById loader, generated with: go run github.com/vektah/dataloaden CityByIdLoader int *my_project/entities.City:
CityById: CityByIdLoader{
  maxBatch: 100,
  wait:     1 * time.Millisecond,
  fetch: func(keys []int) ([]*entities.City, []error) {
    cities, err := myRepo.CitiesByKeys(keys)
    // directly ordered in DB based on keys` order: it works
    return cities, []error{err}
  },
},

What about []*int for TeamID?
Here's the generated code for TeamById loader, generated with: go run github.com/vektah/dataloaden TeamByIdLoader *int *my_project/entities.Team:
TeamById: TeamByIdLoader{
  maxBatch: 100,
  wait:     1 * time.Millisecond,
  fetch: func(keys []int) ([]*entities.Team, []error) {
    teams, err := myRepo.TeamsByKeys(keys)
    // I cannot order in DB because of `NULL` keys, right?
    // How to order these results?
    return teams, []error{err}
  },
},

I don't understand how to re-order teams by keys if I cannot do it in DB because of NULL values in keys.


text:
Q: Copy values from one Oracle associative array to another I have two pl/sql associative arrays array1 and array2
TYPE T_ARRAY1_REC IS RECORD(COL1 NUMBER,COL2 NUMBER,COL3 NUMBER,COL4 varchar2(1));
TYPE T_ARRAY1 IS TABLE OF T_ARRAY1_REC INDEX BY BINARY_INTEGER;
array1 T_ARRAY1;

TYPE T_ARRAY2_REC IS RECORD(COL1 NUMBER,COL2 NUMBER,COL3 NUMBER);
TYPE T_ARRAY2 IS TABLE OF T_ARRAY2_REC INDEX BY BINARY_INTEGER;
array2 T_ARRAY2;

How can I copy the value of col3 of array2 into col3 of array1? col1 and col2 are the common columns in both arrays
Data for array 1
col1 col2 col3 col4
1     4         P
2     5         T
3     6         P

Data for array 2
col1 col2 col3
1     4   56
2     5   67
3     6   89

After copying data in array1 should look like this
col1 col2 col3 col4
1     4   56   P
2     5   67   T
3     6   89   P

A: If you assume that the associative arrays may not be in the same order and can be sparse (so you cannot use a FOR loop) then you can loop through the arrays using a WHILE loop and FIRST and NEXT on the associative array:
DECLARE
  TYPE T_ARRAY1_REC IS RECORD(COL1 NUMBER,COL2 NUMBER,COL3 NUMBER,COL4 varchar2(1));
  TYPE T_ARRAY1 IS TABLE OF T_ARRAY1_REC INDEX BY BINARY_INTEGER;
  array1 T_ARRAY1;

  TYPE T_ARRAY2_REC IS RECORD(COL1 NUMBER,COL2 NUMBER,COL3 NUMBER);
  TYPE T_ARRAY2 IS TABLE OF T_ARRAY2_REC INDEX BY BINARY_INTEGER;
  array2 T_ARRAY2;

  i PLS_INTEGER;
  j PLS_INTEGER;

  FUNCTION findArray1Index(i_col1 NUMBER, i_col2 NUMBER)
    RETURN PLS_INTEGER
  IS
    i PLS_INTEGER := array1.FIRST;
  BEGIN
    WHILE i IS NOT NULL LOOP
      IF array1(i).col1 = i_col1 AND array1(i).col2 = i_col2 THEN
        RETURN i;
      END IF;
      i := array1.NEXT(i);
    END LOOP;
    RETURN NULL;
  END;
BEGIN
  array1(1).col1 := 1;
  array1(1).col2 := 4;
  array1(1).col4 := 'P';

  array1(2).col1 := 2;
  array1(2).col2 := 5;
  array1(2).col4 := 'T';

  array1(7).col1 := 3;
  array1(7).col2 := 6;
  array1(7).col4 := 'p';

  array2(1).col1 := 1;
  array2(1).col2 := 4;
  array2(1).col3 := 56;

  array2(7).col1 := 2;
  array2(7).col2 := 5;
  array2(7).col3 := 67;

  array2(4).col1 := 3;
  array2(4).col2 := 6;
  array2(4).col3 := 89;

  i := array2.FIRST;
  WHILE i IS NOT NULL LOOP
    j := findArray1Index(array2(i).col1, array2(i).col2);
    IF j IS NOT NULL THEN
      array1(j).col3 := array2(i).col3;
    END IF;
    i := array2.NEXT(i);
  END LOOP;

  i := array1.FIRST;
  WHILE i IS NOT NULL LOOP
    DBMS_OUTPUT.PUT_LINE(
      array1(i).col1 || ', ' ||
      array1(i).col2 || ', ' ||
      array1(i).col3 || ', ' ||
      array1(i).col4
    );
    i := array1.NEXT(i);
  END LOOP;
END;
/

db<>fiddle here


text:
Q: How to return variable value outside api function call using jquery or javascript module.exports = function (ctx, application) {
var API;
var usermandData = [];
var clientmandData = [];
var taskmandData = []

API = {

    GetMandatoryFieldsforUser: function () {
        return MandatoryFields.User;
    },

    GetMandatoryFieldsforClient: function () {
        return MandatoryFields.Client;
    },

    GetMandatoryFieldsforTask: function () {
        return MandatoryFields.Task;
    }

};

var UserFields = $.get("api/mapping/mandatoryfield?type=USER", function (d) {
    this.mandatoryuserdata = JSON.parse(d.Data);
    this.mandatoryuserdata.forEach(function (data) {
        usermandData.push(data.DisplayName);  // returns  ["First Name", "Last Name", "Location", "Email"]
    });
})

var ClientFields = $.get("api/mapping/mandatoryfield?type=CLIENT", function (d) {
    this.mandatoryClientdata = JSON.parse(d.Data);
    this.mandatoryClientdata.forEach(function (data) {
        clientmandData.push(data.DisplayName); // returns ["Client Type", "Last Name / Entity Name", "Originating Location", "Responsible Person"],
    });
})

var TaskFields = $.get("api/mapping/mandatoryfield?type=TASK", function (d) {
    this.mandatoryTaskdata = JSON.parse(d.Data);
    this.mandatoryTaskdata.forEach(function (data) {
        taskmandData.push(data.DisplayName);  //returns  ["Client Name", "Period End Date", "Task Type", "Responsible Person"]
    });
})

MandatoryFields = {
    User: usermandData,
    Client: clientmandData,
    Task: taskmandData
}

Reqres.setHandler('Dataexportwizard:getMandatoryfields', function (type) {
   // console.log(mandData)
    switch (type) {
        case "USER": return API.GetMandatoryFieldsforUser();
        case "CLIENT": return API.GetMandatoryFieldsforClient();
        case "TASK": return API.GetMandatoryFieldsforTask();
    }
});

My issue here is since it is a async function MandatoryFields.User, MandatoryFields.Client and MandatoryFields.Task returns null value i need to push value of usermandData,      clientmandData,        taskmandData    into MandatoryFields.User ,   MandatoryFields.Client    , MandatoryFields.Task  field How to achieve it using jquery or javascript.
since MandatoryFields object executes before jQuery get method I can only use values inside function call but i need to use it inside MandatoryFields object how can i achieve it using jquery

A: One of the best solution to handle these type of async tasks to use "Promises" (JS feature added by ES6). Try this code may be this will help : -
module.exports = function (ctx, application) {
var API;
var usermandData = [];
var clientmandData = [];
var taskmandData = []

API = {
    GetStepContainerData: function () {
        return StepContainerData;
    },

    GetStepData: function () {
        return stepData;
    },

    GetMandatoryFieldsforUser: function () {
        return MandatoryFields.User;
    },

    GetMandatoryFieldsforClient: function () {
        return MandatoryFields.Client;
    },

    GetMandatoryFieldsforTask: function () {
        return MandatoryFields.Task;
    }

};

Promise.all([
    new Promise(function(resolve,reject){
        $.get("api/mapping/mandatoryfield?type=USER", function (d) {
            this.mandatoryuserdata = JSON.parse(d.Data);
            this.mandatoryuserdata.forEach(function (data) {
                usermandData.push(data.DisplayName);  // returns  ["First Name", "Last Name", "Location", "Email"]
            });
            resolve();
        });
    }),

    new Promise(function(resolve,reject){
        $.get("api/mapping/mandatoryfield?type=CLIENT", function (d) {
            this.mandatoryClientdata = JSON.parse(d.Data);
            this.mandatoryClientdata.forEach(function (data) {
                clientmandData.push(data.DisplayName); // returns ["Client Type", "Last Name / Entity Name", "Originating Location", "Responsible Person"],
            });
            resolve();
        })
    }),

    new Promise(function(resolve,reject){
        $.get("api/mapping/mandatoryfield?type=TASK", function (d) {
            this.mandatoryTaskdata = JSON.parse(d.Data);
            this.mandatoryTaskdata.forEach(function (data) {
                taskmandData.push(data.DisplayName);  //returns  ["Client Name", "Period End Date", "Task Type", "Responsible Person"]
            });
            resolve();
        });
    })
    ]
).then(function(result){

    // After resolving all the promises this method will execute
    MandatoryFields = {
        User: usermandData,
        Client: clientmandData,
        Task: taskmandData
    }
});

Reqres.setHandler('Dataexportwizard:getMandatoryfields', function (type) {
   // console.log(mandData)
    switch (type) {
        case "USER": return API.GetMandatoryFieldsforUser();
        case "CLIENT": return API.GetMandatoryFieldsforClient();
        case "TASK": return API.GetMandatoryFieldsforTask();
    }
});


text:
Q: Can't seem to split a string in Python I'm trying to split a string at its commas in Python at the moment and I'm getting the error main() missing 1 required positional argument: 'self'
This is what I have as of right now.
def main(self):
    last_letters('Ani,Trevor,Karen,Jasmine,Ryan')

def last_letters(self):
    last_letters1 = last_letters.split(",")
if __name__ == '__main__':
    main()

EDIT:
After I remove self from the def, I am still left with this error--
`Traceback (most recent call last):
  File "/home/main.py", line 13, in <module>
    main()
  File "/home/main.py", line 2, in main
    last_letters('Ani,Trevor,Karen,Jasmine,Ryan')
TypeError: last_letters() takes 0 positional arguments but 1 was given

`

A: If you declare that a function takes a positional argument, then you must supply that argument when calling the function.
As it is, your main() function does not require any argument so just change it to:
def main():
    last_letters('Ani,Trevor,Karen,Jasmine,Ryan')

Also, the argument name self is by convention used as a reference to an object instance within the object itself. You find it as the first argument to a method (a function that is bound to an instance of an object), whereas you are using standalone function.
The argument to last_letters() is the string 'Ani,Trevor,Karen,Jasmine,Ryan' when that function is called in main(). last_letters() does require the argument, but for the aforementioned reasons it should not be named self. You could just call it s or something descriptive of its value.
Finally the line last_letters1 = last_letters.split(",") won't work. You need to call split() on a string instance, like this:
def last_letters(text):
    names = text.split(",")
    # do something with names...
    # return a list containing the last letter of each name
    return [name[-1] for name in names]

A: I suggest you write code first without functions as this is a small program and once it's running, slowly convert into functions and this helps in understanding  it
without functions.
if __name__ == '__main__':
    last_letters="Ani,Trevor,Karen,Jasmine,Ryan"
    last_letters1 = last_letters.split(",")
    print(last_letters1)

The mistake you did is you're trying to pass str/word but you didn't specify that in the function (just give a name so that value you passed will be stored in it)
def main():
    last_letters('Ani,Trevor,Karen,Jasmine,Ryan')

def last_letters(word):
    last_letters1 = word.split(",")
    print(last_letters1)

if __name__ == '__main__':
    main()

Exactly your code updated
def main():
    last_letters('Ani,Trevor,Karen,Jasmine,Ryan')

def last_letters(last_letters):
    last_letters1 = last_letters.split(",")
    print(last_letters1) # to print data
if __name__ == '__main__':
    main()

A: There's a number of issues:

*

*You call main() in and appropriate way, but as you can tell from the call main(), it doesn't need a parameter, so instead of declaring it with self as a parameter, it could just be:

def main():
    last_letters('Ani,Trevor,Karen,Jasmine,Ryan')

*

*Similarly, last_letters doesn't need self either. Typically, you only see self as a parameter in methods on a class, but these are just functions by themselves (and even for a class, the parameter doesn't need to be called self, it's just a convention). However, you do need to pass a text to last_letters, so it makes sense to define a parameter like text:

def last_letters(text):
    return text.split(",")

*

*Also note that I changed the code of the function to return the result of the split, this ensures that the result is available wherever the function was called, if you do something with it, like capture it in a variable, or print it. Let's print it from main():

def main():
    print(last_letters('Ani,Trevor,Karen,Jasmine,Ryan'))

*

*Since your function is called last_letters, you probably just want the last letters:

def last_letters(text):
    return [word[-1] for word in text.split(",")]

So, the result is then:
def main():
    print(last_letters('Ani,Trevor,Karen,Jasmine,Ryan'))

def last_letters(text):
    return [word[-1] for word in text.split(",")]

if __name__ == '__main__':
    main()

And the output:
['i', 'r', 'n', 'e', 'n']


text:
Q: Foundations book using category theory for student embarking on PhD in mathematical biology? I'm about to embark on a PhD in mathematical biology. My major is in computer science.
I would like to acquire a more rigorous understanding of math, which I am going to need to tackle some research problems. My plan is, initially, to go through Linear Algebra Done Right by Axler, and Principles of Mathematical Analysis by Rudin as a refresher.
I was considering to go through a foundations book like Naive Set Theory by Halmos beforehand. But perhaps a category theory-based approach could be more enriching, as it could help me to see connections between many areas and concepts in math. Is this a good idea?
Sets for Mathematics and Conceptual Mathematics, both by Lawvere seem to be popular choices. The former seems to be a nice construction of set theory using categories instead of ZFC, but not much more than that. The latter seems to spend more time addressing the connection between categories and different branches of math, like linear maps. Any suggestions?

A: As Artem helpfully suggests in a comment to the question, you might want to try David Spivak's Category Theory for Scientists (Old Version). See also the MIT OpenCourseware page and John Baez's blog entry.
You might also be interested in Robert Ghrist's Elementary Applied Topology, noting that Chapter 10 takes a category-theoretic perspective and that computational geometry and topology are increasingly being applied to biology (see, for instance, the work of Gunnar Carlsson, Herbert Edelsbrunner, Vidit Nanda and others).
I hope this complements Edward Hart's answer, which is probably more relevant if you plan to focus on dynamical systems and the like, although even then you may benefit from studying abstract mathematics and subjects such as topology (including computational homology, which can be used to help analyze dynamical systems). I agree that his advice to "find out exactly which areas of mathematics you will be using (broadly speaking) and then study that specifically" is eminently sensible. I would just add that studying category theory could help in developing your conceptual thinking skills, regardless of the specific areas in which you become involved, and increasingly it has applications beyond foundational matters.

A: From my very limited knowledge of mathematical biology I was under the impression that the more relevant areas of mathematics will be the "applied" ones, as such I don't think that reviewing the abstract areas of mathematics will be very helpful too you. My other thought is that without doing a maths degree it will be very difficult to cover much ground in areas such as Category theory (which I only studied having completed an undergraduate degree in pure mathematics) especially if you haven't seen a lot of very algebraic mathematics (rings, groups and modules etc.).
Areas I think are often applied to parts of mathematical biology are things like dynamical systems and stochastic differential equations. As such, Rudin would be an excellent starting point and then maybe something like 'probability with martingales'. Axler's linear algebra book is fantastic(although not applied). I would stay away from pure set theory simply because most mathematicians who don't study foundations don't need it on a day to day basis.
Basically I think that acquiring a more rigorous understanding of mathematics is a fantastic idea, but the best way to prepare for your research would probably be to find out exactly which areas of mathematics you will be using (broadly speaking) and then study that specifically.


text:
Q: Entity Framework 6 + SQLSpatialFunctions I'm in the process of migrating a code base from the Entity Framework 5 to 6. I've found documentation to assist in this but I'm finding some challenges with the changes made to DBGeography and specifically SQLSpatialFunctions. EF6 contains breaking changes that include removing classes out of System.Spatial over to System.Data.Entity.Spatial (and into the core EF assembly and out of System.Data.Entity). I have not found a replacement for the SQLSpatialFunctions in the EF6 and due to the breaking changes I can't make use of the existing ones. I know these are essentially queries against functions in SQL Server but they were very convenient, they integrate into my queries nicely, and I rather not have to develop my own library to accomplish this (I started to investigate EdmFunctions but it seemed to be a bit of a rabbit hole).
Anyone with any suggestion?
Thanks!

A: They are in the EntityFramework.SqlServer assembly (where they belong), in the System.Data.Entity.SqlServer namespace, see https://entityframework.codeplex.com/workitem/879


text:
Q: How do I create a popup window when doing oauth? I'm would like to do what lifestream and other sites have done with oauth authentication by using a pop up window.  They open a popup window which somehow wasn't blocked by the popup blocker and grey out their site.  Then upon allowing oauth access it says redirecting back to original site and kills the popup and returns the site to normal color.  How would I go about doing something like this?  If I posted anything I shouldn't have its alright because all these accounts are bogus anyway.

A: In javascript, the window.open() function will do this for you. With its api, you can set its location and get data from events occurring in it.
Popup blockers will not block this popup if it is created from a function that is executed when the user clicks a button. Popup blockers only block windows if there was no user input provided to create it.

A: The thing is, this is not a pop-up window. It's what usually called lightbox. A js script like fancybox, lightbox and many others. You basically can open an iframe in a div with a absolut position and high z-index, then put an overlay underneath.


text:
Q: A lot of requests being generated to o.aolcdn.com My computer at work seems to generating a lot of requests to files from o.aolcdn.com. The admins think that I do a lot of browsing. I don't believe I do that much and curious to know how could this be happening.
I know CDN sites are usually used for content delivery, but I am certainly not intending to use the amount of content that is being reported by the Barracuda-based proxy.
Any idea where these requests might be coming from?

A: It's typical for a single webpage to generate 10 or 20 HTTP requests, or even more.  When you factor in all the images, the CSS stylesheets, and AJAX requests generated by Javascript, it isn't unusual.
Web mail windows will also generate periodic AJAX HTTP requests to check for mail updates.  I haven't investigated but I would wager that it would also be downloading updated ads from o.aolcdn.com during that time.  I haven't been on Aol in forever but if you have chat windows or anything else that periodically updates it might be sending requests that you aren't aware of.
If you are using a browser (e.g., Chrome) that prefetches content then even more can be generated.  Also, if you've disabled caching of Web content to prevent being tracked at work, that could be a source of an increased number of requests as your browser needs to refetch data that you saw during your last browsring session.
It's also entirely possible you have a virus or other malware making those requests as well.


text:
Q: GitHub Actions not working strange error message So I get this error message for serveral github action runs:
The following team project collection is stopped: u58HQO13OlVT6yx9h86l8AENZAdSC6hwRnuQGH6RTqpb03FYH8. Start the collection and then try again. Administrator Reason: Creating Collection Host

The following is the workflow I am using:
name: Java docs deploy to gh-pages

on:
  push:
    branches:
      - master
      - docs-test

jobs:
  docs:

    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v1
      - name: Set up JDK 1.11
        uses: actions/setup-java@v1
        with:
          java-version: 1.11
      - name: Docs with gradle
        run: ./gradlew javadoc
      - name: Build and Deploy
        uses: JamesIves/github-pages-deploy-action@releases/v3
        with:
          ACCESS_TOKEN: ${{ secrets.ACCESS_TOKEN }}
          BRANCH: gh-pages # The branch the action should deploy to.
          FOLDER: build/docs/javadoc # The folder the action should deploy.

I already tried rerunning it... Any ideas?

A: Apologies - this is an internal GitHub error message.  We were rolling out a new deployment that had errors for some workflows, and I'm afraid that yours was one of the workflows affected.
We've rolled that deployment back - if you run your workflow now, the problem should be resolved.  Apologies for the inconvenience!


text:
Q: jquery populate select options with json matching same order I have the following json data:
 {
      "324": "Aguacate",
      "196": "Fresa",
      "7875": "Mandarina",
      "197": "Platano",
      "9517": "Uvas"
 }

For any reason, when I populate the target select dropdown's options, it returns the options in a different order (by ID):
 {
      "196": "Fresa",
      "197": "Platano",
      "324": "Aguacate",
      "7875": "Mandarina",
      "9517": "Uvas"
 }

Considering that the script looks like:
  $.getJSON("http://path/to/blabla.json", customfunction);

  function customfunction(data) {

        var $select = $('#mymail_data_socio');

        // First, empty the select field
        $select.find('option').remove();

        $.each(data,function(key, value) {
              $select.append('<option value=' + key + '>' + value + '</option>');
        });

  }

Is there any way to return the options in the same order as in my json file? How I should rewrite my script in order to achieve it?
Thanks!

A: This is a browser specific issue (basically chrome issue), where the browser javascript engine loops through the object properties in order (numeric properties) : https://bugs.chromium.org/p/v8/issues/detail?id=164
You can use a prefix and then replace it in the loop as follows:

var obj = {
      "id_324": "Aguacate",
      "id_196": "Fresa",
      "id_7875": "Mandarina",
      "id_197": "Platano",
      "id_9517": "Uvas"
 };

 function customfunction(data) {

        var $select = $('#mymail_data_socio');

        // First, empty the select field
        $select.find('option').remove();

        $.each(data,function(key, value) {
              $select.append('<option value=' + key.replace('id_', '') + '>' + value + '</option>');
        });

  }

  customfunction(obj);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="mymail_data_socio"></select>

A: The other option is to use JSONArray and can be iterated with inner loop (can be quite hectic with more than one iteration) which will give the desired result with the same order specified.
here is the example with both ways


text:
Q: polymer paper-dialog within paper-dialog I am trying to make the confirmation dialog show up after I tap on affirmative button on "base" dialog. This confirmation dialog never appears. Instead, the "base" dialog closes immediately when I tap on its affirmative button.
How do I fix the problem? Thanks in advance!
file confirm-dialog.html:
<link rel="import" href="https://polygit.org/components/PolymerElements/paper-dialog-behavior/paper-dialog-behavior.html">
<link rel="import" href="https://polygit.org/components/PolymerElements/paper-button/paper-button.html">
<dom-module id="confirm-dialog">
    <template>
        <paper-dialog>

[[msgHeader]]

            <content></content>

                <paper-button dialog-dismiss>[[msgDismiss]]</paper-button>
                <paper-button dialog-confirm>[[msgConfirm]]</paper-button>

        </paper-dialog>
    </template>
</dom-module>

file index.html:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <link rel="import" href="http://polygit.org/components/polymer/polymer.html">
    <link rel="import" href="http://polygit.org/components/PolymerElements/paper-dialog/paper-dialog.html">
    <link rel="import" href="https://polygit.org/components/PolymerElements/paper-button/paper-button.html">
    <link rel="import" href="confirm-dialog.html">

<dom-module id="dialog-in-dialog">
    <template>
        <button on-tap="Button1Clicked">Open Base Dialog</button>
        <paper-dialog id="base">

Base Dialog

This is base dialog.

            <confirm-dialog msg-header="Confirm Dialog" msg-dismiss="Cancel" msg-confirm="Do it">Sure want to break the window?</confirm-dialog>

                <paper-button dialog-dismiss>Cancel</paper-button>
                <paper-button dialog-confirm on-tap="OpenDialog2">Break the window</paper-button>

        </paper-dialog>
    </template>
</dom-module>

<dialog-in-dialog></dialog-in-dialog>

<link rel="import" href="https://polygit.org/components/polymer/polymer.html">
<link rel="import" href="https://polygit.org/components/paper-dialog/paper-dialog.html">
<link rel="import" href="https://polygit.org/components/paper-button/paper-button.html">

<dom-module id="confirm-dialog">
  <template>
    <paper-dialog>

[[msgHeader]]

      <content></content>

        <paper-button dialog-dismiss>[[msgDismiss]]</paper-button>
        <paper-button dialog-confirm>[[msgConfirm]]</paper-button>

    </paper-dialog>
  </template>
</dom-module>

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

  <dom-module id="dialog-in-dialog">
    <template>
      <button on-tap="Button1Clicked">Open Base Dialog</button>
      <paper-dialog id="base">

Base Dialog

This is base dialog.

        <confirm-dialog msg-header="Confirm Dialog" msg-dismiss="Cancel" msg-confirm="Do it">Sure want to break the window?</confirm-dialog>

          <paper-button dialog-dismiss>Cancel</paper-button>
          <paper-button dialog-confirm on-tap="OpenDialog2">Break the window</paper-button>

      </paper-dialog>
    </template>
  </dom-module>

  <dialog-in-dialog></dialog-in-dialog>

[edit]
I want the parent paper-dialog keep opened after its child paper-dialog is opened. According to the helps from the kind guru, I remove paper-button from the parent paper-dialog as shown in this revision:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <link rel="import" href="../bc/polymer/polymer.html">
    <link rel="import" href="../bc/paper-dialog/paper-dialog.html">
    <link rel="import" href="../bc/paper-button/paper-button.html">
    <link rel="import" href="confirm-dialog.html">

    <dom-module id="dialog-in-dialog">
        <template>
            <button on-tap="Button1Clicked">Open Base Dialog</button>
            <paper-dialog id="base">

Base Dialog

This is base dialog.

                <button on-tap="OpenDialog2">Break the window</button>

                    <paper-button dialog-dismiss>Exit</paper-button>

            </paper-dialog>
            <confirm-dialog msg-header="Confirm Dialog" msg-dismiss="Cancel" msg-confirm="Do it">Sure want to break the window?</confirm-dialog>
        </template>
    </dom-module>

    <dialog-in-dialog></dialog-in-dialog>

A: You need to make two changes to your current code to make it work

*

*
*

*You need to remove behavior from your confirm-dialog item. As your element in itself is not going to open and is just gonna call paper-dialog's open function internally there is no need to import PaperDialogBehavior in your custom element.

*

*You need to remove dialog-confirm from the button which you are going to use to open the nested dialog. Adding that will close your parent dialog and thus your attempt to open nested dialog will fail.

or

*

*

*If you want to close your first dialog and open the second dialog you can instead of removing dialog-confirm can move your custom-dialog element out of the paper-dialog. This will on click of the button close the parent dialog and open the child dialog as depicted in the code here

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

  <link rel="import" href="https://polygit.org/components/polymer/polymer.html">
  <link rel="import" href="https://polygit.org/components/paper-dialog/paper-dialog.html">
  <link rel="import" href="https://polygit.org/components/paper-button/paper-button.html">

  <dom-module id="confirm-dialog">
    <template>
      <paper-dialog>

[[msgHeader]]

        <content></content>

          <paper-button dialog-dismiss>[[msgDismiss]]</paper-button>
          <paper-button dialog-confirm>[[msgConfirm]]</paper-button>

      </paper-dialog>
    </template>
  </dom-module>

  <dom-module id="dialog-in-dialog">
    <template>
      <button on-tap="Button1Clicked">Open Base Dialog</button>
      <paper-dialog id="base">

Base Dialog

This is base dialog.

          <paper-button dialog-dismiss>Cancel</paper-button>
          <paper-button dialog-confirm on-tap="OpenDialog2">Break the window</paper-button>

      </paper-dialog>
      <confirm-dialog msg-header="Confirm Dialog" msg-dismiss="Cancel" msg-confirm="Do it">Sure want to break the window?</confirm-dialog>
    </template>
  </dom-module>

  <dialog-in-dialog></dialog-in-dialog>


text:
Q: Mousemove for mobile I have a website with a splitscreen slider that I want to make mobile friendly. I have an addeventlistener 'mousemove' which allows the slider to go back and forth, but I also want to make it touch activated as well.
I tried replacing the 'mousemove' with 'pointermove' and 'touchmove' but nothing would change. It still won't work on mobile, help please. The codepen shows an example of what I have on my site.

document.addEventListener('DOMContentLoaded', function(){
  let wrapper = document.getElementById('wrapper');
  let topLayer = wrapper.querySelector('.top');
  let handle = wrapper.querySelector('.handle');
  let skew = 0;
  let delta = 0;

  if(wrapper.className.indexOf('skewed') != -1){
   skew = 1000;
   }

wrapper.addEventListener('mousemove', function(e){
  delta = (e.clientX - window.innerWidth / 2) * 0.5;

  handle.style.left = e.clientX + delta + 'px';

  topLayer.style.width= e.clientX + skew + delta + 'px';
  });
});
body{
  margin: 0;
  padding:0;
  font-size: 100%;
  line-height: 1.6;
  font-family: Arial, Helvetica, sans-serif;
}

#wrapper{
  position: relative;
  width: 100%;
  min-height:55vw;
  overflow: hidden;
}

.layer{
  position:absolute;
  width:100vw;
  min-height: 55vw;
  overflow: hidden;
}

.layer .content-wrap{
  position: absolute;
  width:100vw;
  min-height: 55vw;
}

.layer .content-body{
  width: 25%;
  position:absolute;
/*   top:50%; */
  top: 25%;
  text-align: center;
  transform:translateY(-50%);
  color:#fff;
}

.layer img{
  position:absolute;
  width:65%;
/*width: 35%    */
  top:50%;
  left:50%;
  transform:translate(-50%, -50%);
}

.layer h1 {
  font-size:2em;
  font-family: 'Lato', sans-serif;
}

.bottom{
  background:#686965;
  z-index:1;
}

.bottom .content-body{
  right:5%;
}

.bottom h1{
  color:#7bbe9a;
  font-family: 'Lato', sans-serif;
}

.top{
  background:#eff0ec;
  color:#222;
  z-index:2;
  width:50vw;
}

.top .content-body{
  left:5%;
  color:#333;
}

.handle{
  position: absolute;
  height: 100%;
  display: block;
  background-color: #7bbe9a;
  width: 5px;
  top:0;
  left: 50%;
  z-index:3;
}

.skewed .handle{
  top:50%;
  transform:rotate(30deg) translateY(-50%);
  height:200%;
  transform-origin:top;
}

.skewed .top{
  transform: skew(-30deg);
  margin-left:-1000px;
  width: calc(50vw + 1000px);
}

.skewed .top .content-wrap{
  transform: skew(30deg);
  margin-left:1000px;
}

@media(max-width:768px){
  body{
    font-size:75%;
  }
}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <link rel="stylesheet" href="">
    <link href="https://fonts.googleapis.com/css?family=Lato|Nixie+One" rel="stylesheet">

Designer

Developer

A: The answer is located here, in a different post.


text:
Q: Mark targets defined by implicit rules as .SECONDARY For my project, it is necessary to autogenerate .c source files using m4. For my build process, I am using GNU make, for both m4 invocation and compilation of object files that are compiled from these generated .c files.
%.c: %.c.in
        m4 -D OPNAME=$(OPNAME) -D ARGLEVEL=$(ARGLEVEL) -D SKELARGS="$(call TOM4LIST,$(SKELARGS))" -D SUBDIRS="$(call TOM4LIST,$(RSSUBDIRS))" $(BASEDIR)/op/common.m4 $< > $@

This works fine, but when compiling the corresponding .o object the .c file is automatically marked as INTERMEDIATE and gets deleted when the job is done.
I don't want this.
The documented way of preventing intermediate files from being deleted is adding the target that should be kept to the dependency list of the .SECONDARY target:
.SECONDARY: somefile.c

However, for obvious reasons,
.SECONDARY: %.c

will not work. So, how do I go about this?

A: Make all the build steps explicit. Use the fact that a single recipe can be used to build multiple targets and specify your metatargets using the list of desired files, rather than %.
OBJECTS = a.o b.o c.o
INTERMEDIARY = $(OBJECTS:.o=.c)

OBJECTS: $(@:.o=.c)
    // build command for .c to .o

INTERMEDIARY: $(@:.c=.c.in)
     m4 -D OPNAME=$(OPNAME) -D ARGLEVEL=$(ARGLEVEL) -D SKELARGS="$(call TOM4LIST,$(SKELARGS))" -D SUBDIRS="$(call TOM4LIST,$(RSSUBDIRS))" $(BASEDIR)/op/common.m4 $< > $@


text:
Q: Mismatch C# Javascript date/time The following js code in Chrome dev console.
new Date(1560780000000)

yields

Tue Jun 18 2019 00:00:00 GMT+1000 (Australian Eastern Standard Time)

however in c# on the same machine, this yields
new DateTime(1970, 1, 1).AddMilliseconds(1560780000000);

17/06/2019 14:00:00

Using
new DateTime(1970, 1, 1).ToLocalTime().AddMilliseconds(1560780000000);

yields

18/06/2019 01:00:00

The date is still out by an hour. I am trying to translate a JS date into a C# DateTime accurately. I can't change the signature of the method from DateTime, can anyone help?
KH

A: This gives me the same result:
new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(1560780000000)

or this
new DateTime(1970, 1, 1).AddMilliseconds(1560780000000).ToLocalTime()

They are not 100% equivalent, but the second one will create a date with kind Unspecified that is assumed to be UTC when you call ToLocalTime().
The difference if you call ToLocalTime() before or after AddMilliseconds() is in Daylight Saving it seems. Depending on the date, same local time will be interpreted differently. So you should always do all calculations in UTC I assume and only convert to local time to check in the end.
The problem was that you have added milliseconds that made it to be in summer when DST would make a difference (I think ).
More details here.

A: To get UTC timestamp in JavaScript :
new Date(1560780000000).toJSON();                                      // "2019-06-17T14:00:00.000Z"

C# :
DateTimeOffset.FromUnixTimeMilliseconds(1560780000000).ToString("o");  // "2019-06-17T14:00:00.0000000+00:00"

new DateTime(1970, 1, 1).AddMilliseconds(1560780000000).ToString("o"); // "2019-06-17T14:00:00.0000000"


text:
Q: PostgreSQL optimization: average over range of dates I have a query (with a subquery) that calculates an average of temperatures over the previous years, plus/minus one week per each day. It works, but it is not all that fast. The time series values below are just an example. Why I'm using doy is because I want a sliding window around the same date for every year.
SELECT days,
    (SELECT avg(temperature)
     FROM temperatures
     WHERE site_id = ? AND
      extract(doy FROM timestamp) BETWEEN
      extract(doy FROM days) - 7 AND extract(doy FROM days) + 7
    ) AS temperature
FROM generate_series('2017-05-01'::date, '2017-08-31'::date, interval '1 day') days

So my question is, could this query somehow be improved? I was thinking about using some kind of window function or possibly lag and lead. However at least regular window functions only work on specific amount of rows, whereas there can be any number of measurements within the two-week window.
I can live with what I have for now, but as the amount of data grows so does the execution speed of the query. The two latter extracts could be removed, but that has no noticeable speed improvement and only makes the query less legible. Any help would be greatly appreciated.

A: The best index for your original query is
create index idx_temperatures_site_id_timestamp_doy
  on temperatures(site_id, extract(doy from timestamp));

This can greatly improve your original query's performance.
While your original query is simple & readable, it has 1 flaw: it will calculate every day's average 14 times (on average). Instead, you could calculate these averages on a daily basis & calculate the 2 week window's weighted average (the weight for a day's average needs to be count of the individual rows in your original table). Something like this:
with p as (
  select timestamp '2017-05-01' min,
         timestamp '2017-08-31' max
)
select     t.*
from       p
cross join (select     days, sum(sum(temperature)) over pn1week / sum(count(temperature)) over pn1week
            from       p
            cross join generate_series(min - interval '1 week', max + interval '1 week', interval '1 day') days
            left join  temperatures on site_id = ? and extract(doy from timestamp) = extract(doy from days)
            group by   days
            window     pn1week as (order by days rows between 7 preceding and 7 following)) t
where      days between min and max
order by   days

However, there is not much gain here, as this is only twice as fast as your original query (with the optimal index).
http://rextester.com/JCAG41071
Notes: I used timestamp because I assumed your column's type is timestamp. But as it turned out, you use timestamptz (aka. timestamp with time zone). With that type, you cannot index the extract(doy from timestamp) expression, because that expression's output is dependent of the actual client's time zone setting.
For timestamptz use an index which (at least) starts with site_id. Using the window version should improve the performance anyway.
http://rextester.com/XTJSM42954


text:
Q: Find density function $Z=2X+Y$ Let $X$ and $Y$ be identically distributed independent random variables with density function
\begin{align}
f(t) = \begin{cases}\frac{1}{4} & 0 \leq t \leq 4\\0 & \text{otherwise}\end{cases}
\end{align}
Find the density function of $Z=2X+Y$.
I am trying to solve this question as follow:
$U=2X$
\begin{align}
f_U(u) = \frac{1}{2}f_X(\frac {u}{2})=\begin{cases}\frac{1}{8} & 0 \leq u \leq 8\\0 & \text{otherwise}\end{cases}
\end{align}
and
\begin{align}
f_Y(y) = \begin{cases}\frac{1}{4} & 0 \leq y \leq 4\\0 & \text{otherwise}\end{cases}
\end{align}
and now I am trying to solve $Z=U+Y$
\begin{align}
f_Z(z) = \int_{-\infty}^{\infty} f_U(z-y)f_Y(y)dy
\end{align}
$f_Y(y)=\frac{1}{4}$ if $0\leq y\leq4$ and $0$ otherwise, then this become:
\begin{align}
f_Z(z) = \int_{0}^{8} f_U(z-y)dy
\end{align}
now the integrated is $0$ unless $0 \leq z-y \leq 8 (i.e, z-8 \leq y \leq z)$ and then it is $\frac{1}{8}$
if $0 \leq z \leq 4$ then
\begin{align}
f_Z(z) = \frac{1}{4}\int_{0}^{z} \frac {1}{8}dy = \frac{z}{32}
\end{align}
if $4 < z \leq 12$ then
\begin{align}
f_Z(z) = \frac{1}{4}\int_{z-8}^{8} \frac {1}{8}dy = \frac{16-z}{32}
\end{align}
and $f_Z(z) = 0$ for values $z < 0$ and $z > 12$
\begin{align}
f_Z(z) = \begin{cases}
\frac{z}{32} & 0 \leq z \leq 4\\
\frac{16-z}{32} & 4 < z  \leq 12\\
0 & otherwise
\end{cases}
\end{align}


text:
Q: Visual Studio 2013 - Error occurred while trying to restore packages. The underlying connection was closed. In Visual Studio 2013, NuGet package manager fails to restore packages. When clicking Manage NuGet Packages on the project, NuGet states "Some NuGet packages are missing from this solution. Click to restore from your online package sources.". After clicking "Restore", the following error appears...
Manage NuGet Packages Window
Error occurred while trying to restore packages. The underlying connection was closed.

If you build the project, the output window shows the following errors...
Build Output Window
Restoring NuGet packages...
To prevent NuGet from restoring packages during build, open the Visual Studio Options dialog, click on the Package Manager node and uncheck 'Allow NuGet to download missing packages during build.'
NuGet Package restore failed for project MyProject: The underlying connection was closed: An unexpected error occurred on a send..
NuGet package restore failed.

Any ideas?

A: This turned out to be an issue with the CDN host that Microsoft was using didn't have SSL enabled. Trying to access the CDN URL for the RazorGenerator.MVC package was failing. If I changed the response returned to non-SSL via Fiddler it worked just fine.
It seems Microsoft just fixed their CDN issue - case closed.


text:
Q: I have fetched date from mysql in python and I want to add current time eg. 2020-08-25T04:00:00 like this I have tried this:
import datetime

dt = datetime.datetime(2012, 2, 12)
tm = datetime.time(1, 30)

combined = dt.combine(dt, tm)

print(combined)

but the output is:
2012-02-12 01:30:00

A: from datetime import datetime

# current date and time
now = datetime.now()

This would help you get the time now.

A: If the problem is the lack of T between the date and time, the following will format it that way:
combined.strftime("%Y-%m-%dT%H:%M:%S")
'2012-02-12T01:30:00'

Look at strftime if you need to change the formatting some other way.


text:
Q: What is 'The Dataflow job appears to be stuck because no worker activity has been seen in the last 1h'? My dataflow job was triggered from Apache_beam of Python.  It was worked when the runner is default, but was failed when the runner is DataFlowRunner.  I wonder some of dataflow setup is not correct in GCP project.
insertId: "18yr612ckq8"
labels: {
dataflow.googleapis.com/job_id: "2019-12-29_20_13_18-6351782926232365732"
dataflow.googleapis.com/job_name: "wordcountpy-test"
dataflow.googleapis.com/region: "us-central1"
}
logName: "projects/hsbc-9820327-cmbsp54-dev/logs/dataflow.googleapis.com%2Fjob-message"
 receiveTimestamp: "2019-12-30T05:13:27.146833360Z"
 resource: {
  labels: {
   job_id: "2019-12-29_20_13_18-6351782926232365732"
   job_name: "wordcountpy-test"
   project_id: "488006911152"
   region: "us-central1"
   step_id: ""
  }
  type: "dataflow_step"
 }
 severity: "ERROR"
 textPayload: "Workflow failed. Causes: The Dataflow job appears to be stuck because no worker activity has been seen in the last 1h. You can get help with Cloud Dataflow at   https://cloud.google.com/dataflow/support."
 timestamp: "2019-12-30T05:13:25.787782564Z" enter code here


text:
Q: How to subscribe to a nested property in a observable collection in ReactiveUI How do i subscribe to a nested property in a observable collection?
view Model:
Public Class ViewModel{

    //a collection of all Hardware Tests.
    public observableCollection<HWTest> AllHWTests;

    //constructors
    ViewModel{

    //here I want to subscribe to Ispassed changes.

    }

}

HWTest:

public class HWTest{

    //a Collection of all Hardware types, each element have a isPassed property
    //of  type bool.
    observableCollection<HWInterface> AllSignals;
}

HWInterface:
public Class HWInterface{

    //the property I would like to subscribe to at the view model
    public bool isPassed;

}

how do I subscribe  to the isPassed?
this is only an example, I didn't wrote any code at the moment.
thanks in advance.

A: ObservableCollection<T> only lets you observable the changes of membership of the collection. You need to use that to attach to events that each class member implements to see when the individual properties are changing in the members of the collection.
Here's how to use (1) ObservableCollection<T> and also (2) IObservable<T> to do what you're asking.
First we need to set up the class that we want to observe:
public class HWInterface : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public HWInterface(string name)
    {
        this.Name = name;
    }

    public string Name { get; private set; }

    private bool _isPassed = false;
    public bool IsPassed
    {
        get => _isPassed;
        set
        {
            if (_isPassed != value)
            {
                _isPassed = value;
                this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("IsPassed"));
            }
        }
    }
}

Please note I've changed your casing to use the normal C# idiomatic form.
Now I need an ObservableCollection<HWInterface> to work with:
var oc = new ObservableCollection<HWInterface>();

For (1) I need this code to watch the items in the collection:
PropertyChangedEventHandler pceh = (s, e)  => Console.WriteLine($"1: {(s as HWInterface).Name} \"{e.PropertyName}\" changed to {(s as HWInterface).IsPassed}.");

oc.CollectionChanged += (s, e) =>
{
    if (e.NewItems != null) foreach (var f in e.NewItems.OfType<HWInterface>()) f.PropertyChanged += pceh;
    if (e.OldItems != null) foreach (var f in e.OldItems.OfType<HWInterface>()) f.PropertyChanged -= pceh;
};

For (2) I need this code to watch the items in the collection:
var query =
    Observable
        .FromEventPattern<NotifyCollectionChangedEventHandler, NotifyCollectionChangedEventArgs>(
            h => oc.CollectionChanged += h,
            h => oc.CollectionChanged -= h)
        .Select(x =>
            oc
                .ToObservable()
                .SelectMany(f =>
                    Observable
                        .FromEventPattern<PropertyChangedEventHandler, PropertyChangedEventArgs>(
                            h => f.PropertyChanged += h,
                            h => f.PropertyChanged -= h)
                        .Select(y => new { foo = f, property = y.EventArgs.PropertyName })))
        .Switch();

IDisposable subscription =
    query
        .Subscribe(x => Console.WriteLine($"2: {x.foo.Name} \"{x.property}\" changed to {x.foo.IsPassed}."));

Now I can run some test code:
var a = new HWInterface("A");
var b = new HWInterface("B");
var c = new HWInterface("C");

oc.Add(a);
oc.Add(b);
oc.Add(c);

b.IsPassed = true;

b.IsPassed = false;

oc.Remove(b);

b.IsPassed = true; // `b` has been removed so doesn't fire anymore
c.IsPassed = true;

Here's my output:
1: B "IsPassed" changed to True.
2: B "IsPassed" changed to True.
1: B "IsPassed" changed to False.
2: B "IsPassed" changed to False.
1: C "IsPassed" changed to True.
2: C "IsPassed" changed to True.

A: Out of the Box ObservableCollection does not provide you what you want.  It's name suggests you can observe things internal to the list (The INotifyPropertyChangedEvent of the elements on the list).
Generally, we want to know INotifyCollectionChanged and INotifyPropertyChanged for a given ObservableCollection which requires some manual setup.  I wrote a blog on this topic.
TLDR
What you want to use is DynamicData.  It will allow you to obtain property changed notifications from internal elements of the list.


text:
Q: Unity RaycastHit2D with something specific I have a laser. its goes on forever. But when the laser touches ANYTHING like (wall, player, box, trigger colliders, etc...) it stops there. So it basically doesnt go through colliders.
But I dont want that. I want the laser to ONLY stop if the RaycastHit2D hits a wall.
Is there a way to do that? thanks in advance :D
Here's the code:
private LineRenderer lineRenderer;
public Transform LaserHit;
public Transform LaserSpawn;

void Start()
{
    lineRenderer = GetComponent<LineRenderer>();
    lineRenderer.useWorldSpace = true;
}

void Update()
{
    RaycastHit2D hit = Physics2D.Raycast(transform.position, transform.up);
    LaserHit.position = hit.point;
    lineRenderer.SetPosition(0, transform.position);
    lineRenderer.SetPosition(1, LaserHit.position);
}

A: :EDIT:
tl;dr - when you call LayerMask.NameToLayer() or anything else, you're getting the layer, which is telling you which bit corresponds to your layer. If you actually want to mask with that layer, then you need to set that bit by bit shifting. That is, if you want to raycast against only walls, then you need to get the walls layer:
int wallsLayer = LayerMask.NameToLayer("Walls");

and then you need to BIT SHIFT by that amount:
int wallsMask = 1<<wallsLayer;

Using this with the raycast command will now only return the interactions with walls. If you want to interact with everything EXCEPT walls, then you need to invert the MASK and not the LAYER:
int everythingButWalls = ~wallsMask;

Using this will now hit anything except a wall (assuming you've actually set the layer - remember that expanding the Layer options and adding a Layer does not actually SET the layer for the GameObject!)

Create a Layer for walls by going to any GameObject and, under its name, expand the "Layer" box then go to "Add Layer" and name it "Walls" or something.

Then go to your walls and set the Layer for each wall to the "Walls" layer you created.

Then when you raycast, use the Walls layer as the layer mask:
void Update()
{
    int wallsLayer = LayerMask.GetMask("Walls");
    int layerMask = 1<<wallsLayer;
    RaycastHit2D hit = Physics2D.Raycast(transform.position, transform.up, Mathf.Infinity, layerMask);
    LaserHit.position = hit.point;
    lineRenderer.SetPosition(0, transform.position);
    lineRenderer.SetPosition(1, LaserHit.position);
}

A: Make it simple and controllable, with only layerMask.value:
public LayerMask laserHitLayer;

public void RayCast()
{
    var Hit = Physics2D.Raycast(transform.position, transform.up, 2f, laserHitLayer.value);

    if (!Hit) return;

    // do something when on hit
}

You can easily select and change the desired layer in the inspector.


text:
Q: How to run multiple command systemd i want to multiple command in myapp.service file in systemd
[Unit]
Description=to serve myapp

[Service]
User=ubuntu
WorkingDirectory=/home/ubuntu/myapp
ExecStart=/home/ubuntu/.local/bin/pserve production.ini http_port=5000
ExecStart=/home/ubuntu/.local/bin/pserve production.ini http_port=5001
Restart=always

[Install]
WantedBy=multi-user.target

it throws error saying invalid argument.
i want to run two commands
pserve production.ini http_port=5000
pserve production.ini http_port=5001

How do i do that??

A: You can start multiple background processes from one systemd unit, but systemd will not be able to track them for you and do all the nice things that it does to support a daemon, such as send signals to it on various system events or auto-restart it when needed.
If you must have it as a single unit, then you can do one of the following (in my order of preference):

*

*make the two servers separate units (note you may be able to use the same config file for both, so they are two 'instances' of the same service - which makes sense, they run the same server). You will have two entries in the list of running services when you run 'systemctl'.

*make that unit a one-shot (runs a program that exits and is not monitored and restarted). Make the one-shot command start both servers in background, e.g.,
sh -c " { pserve production.ini http_port=5000 & pserve production.ini http_port=5001 & } </dev/null >/dev/null >&1"

*make a script that launches both daemons and watches for them, restarting them if needed and kills them when it is killed itself. Then you make that script the 'daemon' that systemd runs. Not really worth it, IMO - because you're doing much of the work that systemd itself is best suited to do. Of course you can spin a new copy of systemd that is configured to run just those two servers (and make that systemd as your 'one-service-for-two-commands' unit), but that seems an overkill.


text:
Q: ¿Como obtener un campo de un array con el id de otro array? Tengo 2 array de los cuales necesito traer un campo del segundo array y concatenarlo al primer array.
"data": [
        {
            "idclv_propiedad": "1",
            "id_opera": "ZHSP",
            "es_propiedad": "1",
            "idclv_marca": "2",
            "estado": "1",
            "fecha_creacion": "2018-03-20 16:10:27",
            "usuario_creacion": "sherrera",
            "usuario_ultima_modificacion": "gadrian",
            "fecha_ultima_modificacion": "2020-01-16 16:13:10"
        },
        {
            "idclv_propiedad": "2",
            "id_opera": "ZMGR",
            "es_propiedad": "1",
            "idclv_marca": "1",
            "estado": "1",
            "fecha_creacion": "2018-03-20 16:10:27",
            "usuario_creacion": "sherrera",
            "usuario_ultima_modificacion": "sherrera",
            "fecha_ultima_modificacion": "2018-03-20 16:10:27"
        }
],

el segundo:
"marca": [
        {
            "idclv_marca": "1",
            "marca": "slice",
            "estado": "1",
            "fecha_creacion": "2020-01-14",
            "usuario_creacion": "lugomez",
            "usuario_ultima_modificacion": "",
            "fecha_ultima_modificacion": "0000-00-00"
        },
        {
            "idclv_marca": "2",
            "marca": "price",
            "estado": "1",
            "fecha_creacion": "2020-01-14",
            "usuario_creacion": "lugomez",
            "usuario_ultima_modificacion": "",
            "fecha_ultima_modificacion": "0000-00-00"
        }
    ],

Lo que quiero hacer es que a partir de el campo "idclv_marca" que esta en el primer array obtener el campo "marca" del segundo array y posteriormente concatenarlo en el primer array de tan manera que la salida sea el primer array mas el campo marca del segundo array.
tengo lo siguiente pero no funciona ya que solo trae el primer registro que encuentra y no para cada uno de los elementos en el array
foreach ($data as $key => $item){

            $key = array_search($item['idclv_marca'], array_column($modelmarca, 'idclv_marca'));
            if($key){
                $array = $modelmarca[$key]['marca'];
                $item['marca'] = $array;
            }
        }

agradeceria su ayuda y quedo a sus ordenes para cualquier cosa.
saludos

A: Por lo que describes, creo que buscas algo así:
foreach($data as $i=>$d)
    foreach($modelmarca as $j=>$e)
        if($d['idclv_marca']==$e['idclv_marca'])
            $data[$i]['marca']=$e['marca'];

Obteniendo:

Array
(
    [0] => Array
        (
            [idclv_propiedad] => 1
            [id_opera] => ZHSP
            [es_propiedad] => 1
            [idclv_marca] => 2
            [estado] => 1
            [fecha_creacion] => 2018-03-20 16:10:27
            [usuario_creacion] => sherrera
            [usuario_ultima_modificacion] => gadrian
            [fecha_ultima_modificacion] => 2020-01-16 16:13:10
            [marca] => price
        )

    [1] => Array
        (
            [idclv_propiedad] => 2
            [id_opera] => ZMGR
            [es_propiedad] => 1
            [idclv_marca] => 1
            [estado] => 1
            [fecha_creacion] => 2018-03-20 16:10:27
            [usuario_creacion] => sherrera
            [usuario_ultima_modificacion] => sherrera
            [fecha_ultima_modificacion] => 2018-03-20 16:10:27
            [marca] => slice
        )

)

Por favor, confírmame si he entendido correctamente tu problema y hazme saber cualquier duda que tengas para explicar la respuesta lo mejor posible.


text:
Q: Why the same "for loop" method is not accepted by PHP, but in Javascript? As a beginner I know how to work with basic for and foreach loops in PHP. Most of the time we prefer foreach for arrays. I am asking this just for the sake of insight into this "for loop" behavior and how it varies compared with javascript. The same loop in Javascript gives us results.
(Experts feel the question is insane pls don't downvote it)
Javascript
var arrayList = ["php", "javascript", "c++", "C lang", "Python"];
var text = "";
for(var i = 0; i < arrayList.length; i++)
{
   text += arrayList[i] + "
";
}
 document.write(text);

PHP-I know it will work if I put the variable in the loop, but why not in PHP
$_array = array("PHP", "Javascript", "C++", "Jquery", "Python");
$total = count($_array);
$result = "";
for($i = 0; $ i <$total; $i++)
{
 $result += $_array[$i]."
";
 }
echo $result;

A: There are few corrections here:
<?php /* missing */
$_array = array("PHP", "Javascript", "C++", "Jquery", "Python");
$total = count($_array);
$result = "";
for($i = 0; $i <$total; $i++) /* remove extra space between $<space>i */
{
 $result .= $_array[$i]."
"; /* replace + with . */
}
echo $result;

BTW, php has implode() which does the same:
<?php
$result = implode("
",array("PHP", "Javascript", "C++", "Jquery", "Python"));
echo $result;

Equivalent short code for JS:
var text = ["php", "javascript", "c++", "C lang", "Python"].join("
");
document.write(text);

A: In PHP concatenation operator is DOT ("."), not PLUS ("+") character:
WRONG
$result += $_array[$i]."
";

RIGHT
$result .= $_array[$i]."
";


text:
Q: Test class passed, but main class only 44% Good Morning Salesforce Stackexchange
I have the following test class called "DeactivateUsers_Test" which has passed however main class "DeactivateUsers" is only getting code coverage of 44% (48/108)
@isTest

private class DeactivateUsers_Test {
    static testMethod void testuserdeactivate() {
        String mydomain = 'Hotmail.com';
        List<User> tobeadded = new List<User>();
        //enter the profile name below that you want to set for the test users.
        Profile prof = [select id from profile where name='NL: Sales & Marketing User'];
        //make sure to add/remove the fields below that are required at your company to create new users

        //create test user 3
        User u3 = new User();
        u3.email = 'u3user@' + mydomain;
        u3.lastname = 'tester';
        u3.firstname = 'u3user';
        u3.emailencodingkey='UTF-8';
        u3.alias = 'u3user';
        u3.languagelocalekey='en_US';
        u3.localesidkey='en_US';
        u3.timezonesidkey='America/Los_Angeles';
        u3.profileid = prof.Id;
        u3.isactive = False;
        u3.Inactive_Date__c = null;
        u3.username='u3user@' + mydomain;

        //add test user to the tobeupdated list
        tobeadded.add(u3);

        //create user 4
        User u4 = new User();
        u4.email = 'u4user@' + mydomain;
        u4.lastname = 'tester';
        u4.firstname = 'u4user';
        u4.emailencodingkey='UTF-8';
        u4.alias = 'u4user';
        u4.languagelocalekey='en_US';
        u4.localesidkey='en_US';
        u4.timezonesidkey='America/Los_Angeles';
        u4.profileid = prof.Id;
        u4.isactive = False;
        u4.Inactive_Date__c = null;
        u4.username='u4user@' + mydomain;

        //add test user to the tobeupdated list
        tobeadded.add(u4);

        //insert the list of new users
        insert tobeadded;

        //verify the users were inserted
        List<User> insertedlist = [select Id,Email,isactive from User Where CreatedDate = Today];
        System.debug('list includes: ' + insertedlist);
        System.assertNotEquals(insertedlist,null);

        //test the class again since the users should have been updated and will not match the query this time.
        Test.startTest();
        DeactivateUsers sh2 = new DeactivateUsers();
        String sch2 = '0 0 23 * * ?';
        System.schedule('Test DeactivateUsers data', sch2, sh2);
        Test.stopTest();
    }
}

Class :
global class DeactivateUsers implements Schedulable
{
    Public static void SendLoginEmail(String bucket, String[] adminemail, List<User> ulist){
        String timeleft = '';
        if(bucket == '1'){
            timeleft = ' 30 days ';
        }
        else{
            timeleft = ' 7 days ';
        }

        List<Messaging.SingleEmailMessage> theEmails = new List<Messaging.SingleEmailMessage>();

        for(Integer i=0;i<ulist.size();i++){
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                mail.setUseSignature(false);
                mail.setSenderDisplayName('Global CRM Team');
                mail.setTargetObjectId(ulist[i].Id);
                mail.saveAsActivity = false;
                mail.setCcAddresses(adminemail);
                mail.setSubject('Your Salesforce account is scheduled for de-activation');
                mail.setHtmlBody('
Dear ' + ulist[i].Name + ',

 You have ' + timeleft + 'to login to your Salesforce account.  If you do not login within the next' + timeleft + 'your account will be deactivated.

 Regards,

Global CRM Team
');
                theEmails.add(mail);
        }

        if(theEmails.size()>0){
            Messaging.SendEmailResult[] results = Messaging.sendEmail( theEmails );
        }
    }

    global void execute(SchedulableContext ctx)
    {
         // to run the job only in production.  Amended by Daniel Mason on 22/04/2014
        if (UserInfo.getOrganizationId() == '00DR0000001tVYyMAM')
        {
            system.debug('*****orgid*****'+UserInfo.getOrganizationId());
            Date myDate = Date.Today();
            String sDate = String.valueOf(myDate);

            //describe the User_Region__c field to get the picklist values
            Schema.DescribeFieldResult fieldResult = User.User_Region__c.getDescribe();

            //put the describe results into a list
            List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();

            //create a list to hold the regions that you want to include in the query
            List<String> myregions = new List<String>();

            //this is where you add the values to your myregions list
            for (Schema.PicklistEntry a : ple ) {
                if(a.getValue().contains('Asia') || a.getValue().contains('Japan')){
                    //do not add to search list
                }
                else{
                    //add to the search list
                    myregions.add(a.getValue());
                }
            }

            //hold the users to deactivate
            List<User> updUsers = new List<User>();
            String Usr = '';
            String Usr1 = '';
            String Usr2 = '';

            String[] AdminEmail = new String[]{};
            AdminEmail.add('daniel.Mason@Hotmail.com');

            String[] DeveloperEmail = new String[]{};
            DeveloperEmail.add('daniel.Mason@Hotmail.com');

            String eMailSub = '';
            String eMailbdy = '';

           List<User> UserList = new List<User>();
           //hold the users at 90 days
           List<User> Bucket1 = new List<User>();
           //hold the users at 113 days
           List<User> Bucket2 = new List<User>();

            if(Test.isRunningTest())
            {
                // To increase the code coverage during running the test class
                UserList = [
                    SELECT Id, Name,isactive,lastlogindate,createddate,Inactive_Date__c
                    FROM User
                    WHERE
                    isactive = False and Inactive_Date__c= null
                     LIMIT 2];
            }
            else
            {
                UserList = [ SELECT Id, Name,isactive,lastlogindate,createddate, Inactive_Date__c
                    FROM User
                    WHERE isactive = True
                    AND User_Region__c =: myregions
                    AND Management_User__c = False
                    AND Management_User__c = false
                    AND Eloqua_User__c = false
                    AND Function__c = null
                    and Local_Administrator__c Not In ('IT Support, System or Integration','Training or Test')
                    ];
            }

            Integer i =1;
            Integer j =1;
            Integer k =1;
            for(user u: UserList)
            {
                 integer Days;
                 if(u.lastlogindate == null){
                    Days = Integer.valueOf((System.Now().getTime() - u.CreatedDate.getTime())/(1000*60*60*24));
                 }else{
                    Days = Integer.valueOf((System.Now().getTime() - u.lastlogindate.getTime())/(1000*60*60*24));
                 }
                 if(Test.isRunningTest()){
                    if(Days == 0){
                    Usr1 = Usr1 + j+'. '+u.name +  '
';
                    j = j+1;
                    Bucket1.add(u);

                    Usr2 = Usr2 + k+'. '+u.name +  '
';
                    k = k+1;
                    Bucket2.add(u);

                     Usr = Usr + i+'. '+u.name +  '
';
                    i = i+1;
                    u.isActive = False;
                    u.Inactive_Date__c = System.Today();
                    updUsers.add(u);

                    }
                 }
                 else{

                     if(Days == 90){
                        Usr1 = Usr1 + j+'. '+u.name +  '
';
                        j = j+1;
                        Bucket1.add(u);
                     }
                     else if(Days == 113){
                        Usr2 = Usr2 + k+'. '+u.name +  '
';
                        k = k+1;
                        Bucket2.add(u);
                     }
                     else if(Days >=120){
                         Usr = Usr + i+'. '+u.name +  '
';
                        i = i+1;
                        u.isActive = False;
                        u.Inactive_Date__c = System.Today();
                        updUsers.add(u);
                     }
                     else{
                        //do nothing
                     }
              }
          }

          //process the 30 days to deactivation  emails
            if(Bucket1.size()>0)
            {
                try
                {
                    SendLoginEmail('1',AdminEmail, Bucket1);
                    sndEmail(AdminEmail,'30 Day notice sent List for '+sDate,'Dear Administrator,

The following Org users have been sent the 30 day deactivation notice during todayís run.

'+Usr1);
                }
                catch(Exception e)
                {
                    system.debug('Exception:'+e);
                    sndEmail(AdminEmail,'Exception in 30 Day notice emails '+sDate,'Dear Administrator,

The following exception has stopped todays 30 day deactivation notice during todayís Run.

'+e+'

 The below users will have to be manually emailed.

'+Usr1);
                }
           }
           else
           {
                sndEmail(DeveloperEmail,'No 30 day notice emails  '+sDate,'Dear Administrator,

There are no 30 day notices sent today');
           }

         //process the 1 week to deactivation  emails
         if(Bucket2.size()>0)
           {
                try
                {
                    SendLoginEmail('2', AdminEmail,Bucket2);
                    sndEmail(AdminEmail,'1 week notice sent List for '+sDate,'Dear Administrator,

The following org users have been sent the 1 week deactivation notice during todayís run.

'+Usr2);
                }
                catch(Exception e)
                {
                    system.debug('Exception:'+e);
                    sndEmail(AdminEmail,'Exception in 1 week notice emails '+sDate,'Dear Administrator,

The following exception has stopped todays 1 week deactivation notice during todayís Run.

'+e+'

 The below users will have to be manually emailed.

'+Usr2);
                }
           }
           else
           {
            sndEmail(DeveloperEmail,'No 1 week notice emails  '+sDate,'Dear Administrator,

There are no 1 week notices sent today');
           }

            //process the user deactivation
           if(updUsers.size()>0)
           {
                try
                {
                    system.debug('Try Part  --- UpdUsersListSize--'+updUsers.size());
                    update updUsers;
                    system.debug('Try Part after update');
                    sndEmail(AdminEmail,'Deactivated User List for '+sDate,'Dear Administrator,

The following org users have been deactivated during todayís run.

'+Usr);
                }
                catch(Exception e)
                {
                    system.debug('Exception:'+e);
                    sndEmail(AdminEmail,'Exception in Deactivate Users '+sDate,'Dear Administrator,

The following exception has stopped todays Deactivate Users Run.

'+e+'

 The below users will have to be manually deactivated.

'+Usr);
                }
           }
           else
           {
            sndEmail(DeveloperEmail,'No Deactivated Users '+sDate,'Dear Administrator,

There are no deactived users today');
           }
      }
    }

    Public void sndEmail(String[] ToAdr,String Sub, String bdy){
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        mail.setUseSignature(false);
        mail.setSenderDisplayName('Global CRM Team');
        mail.setToAddresses(ToAdr);
        mail.setSubject(Sub);
        mail.setHtmlBody(bdy);
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    }
}

A: A few points:

*

*You have about 17 decision points in your DeactivateUsers class, but your test class does not really test any of these decisions.

*You're adding data into the DeactivateUsers class itself using a if(Test.isRunningTest()) statement, but this should be added into your test class.  That's the point of the test class.  It sets up the data that is going to test your logic and that's where you get your code coverage from.

The point of the test class is to create the various conditions that will test the various decisions in your code.  You should have at least as many test methods in your test class as you have decisions in your code.


text:
Q: is it possible to add db_index = True to a field that is not unique (django) I have a model that has some fields like:
current_datetime = models.TimeField(auto_now_add=True)
new_datetime = models.DateTimeField(null=True, db_index=True)
and data would be like :
currun_date_time = 2023-01-22T09:42:00+0330   new_datetime =2023-01-22T09:00:00+0330
currun_date_time = 2023-01-22T09:52:00+0330   new_datetime =2023-01-22T09:00:00+0330
currun_date_time = 2023-01-22T10:02:00+0330   new_datetime =2023-01-22T10:00:00+0330
is it possible new_datetime to have db_index = True ?
the reason i want this index is there are many rows (more than a 200,000 and keep adding every day) and there is a place that user can choose datetime range and see the results(it's a statistical website). i want to send a query with that filtered datetime range so it should be done fast. by the way i am using postgresql
also if you have tips for handling data or sth. like that for such websites i would be glad too hear
thanks.

A: Yes, It is possible to have datetime field to be true. This could upgrade the performance of queries that sort or screen by the given field.
Other better ways to have an index in datetime field is:

*

*To evaluate the query plan and detect any sluggish processes or
missing indexes, take advantage of the "explain" command of your
database.

*Employ the "limit" and "offset" parameters within your    queries to
get only the necessary data.

*For retrieving associated    data in a single query, rather than
numerous queries, incorporate the "select_related" and
"prefetch_related" methods in your Django queries.

*To store the outcomes of elaborate queries and dodge    running the
same query multiple times, make use of caching systems    such as
Redis or Memcached.

*Moreover, if there are too many rows and    the data is not required
for a long period of time, you can    contemplate filing the
information in another table or database.


text:
Q: How to detect focus move direction on focus change? I have a Composable Row that has some click listeners:
val action = { ... }
Row(Modifier.clickable(action) {
  IconButton({ /* other, unrelated action */}) {}
  Text("This isn't clickable")
  Checkbox({ /* something that calls action() on toggle */ })
}

When tabbing through this UI, the focus goes to the IconButton, then the Checkbox, then the Row. I want it to skip the row. I've implemented that by adding to the Row modifier:
val manager = LocalFocusManager.current
Row(Modifier.clickable(action).onFocusChanged {
  if (it.isFocused) manager.moveFocus(FocusDirection.Next)
}) { /* same content */ }

... which works when moving forward, but not when moving backward (using Shift-Tab). And of course that's because of the FocusDirection.Next, which should instead be Previous when moving backward. But how do I detect that? The focus event doesn't have a direction property.
Update
I tried doing this by manually detecting if shift is pressed, which feels more like a hack than a solution:
val keys = LocalWindowInfo.current.keyboardModifiers
/* in onFocusChanged */
manager.moveFocus(if (keys.isShiftPressed) FocusDirection.Previous else FocusDirection.Next)

.. and also, it doesn't work. Calling manager.moveFocus(FocusDirection.Previous) if shift is pressed causes an infinite loop and application crash, presumably because it's setting the focus back to where it came from.


text:
Q: How nginx default_server interacts with ssl and connection refused So I was having an issue where I had seemingly identical configurations of nginx on otherwise identical hosts, but it was working on one and not two others. Essentially trying to connect via https caused a connection refused on 2 of the servers, but the other one worked fine. This was clearly happening at the nginx level as requests weren't even making it to the process running behind nginx and fixing the nginx conf solved the problem.
nginx.conf:
user www-data;
worker_processes 4;
pid /var/run/nginx.pid;

events {
        worker_connections 768;
        # multi_accept on;
}

http {

        ##
        # Basic Settings
        ##
        client_max_body_size 50M;
        sendfile on;
        tcp_nopush on;
        tcp_nodelay on;
        keepalive_timeout 65;
        types_hash_max_size 2048;

        include /etc/nginx/mime.types;
        default_type application/octet-stream;

        ##
        # Logging Settings
        ##

        access_log /var/log/nginx/access.log;
        error_log /var/log/nginx/error.log;

        ##
        # Gzip Settings
        ##

        gzip on;
        gzip_disable "msie6";

        ##
        # Virtual Host Configs
        ##

        include /etc/nginx/conf.d/*.conf;
        include /etc/nginx/sites-enabled/*;
}

port 80 config in sites-enabled:
server {
    listen [::]:80;
    server_name [my_domain].com [hostname].[subdomain].com;

    location / {
            return 301 https://$server_name$request_uri;
    }
}

port 443 config in sites-enabled:
server {
    listen 443 default_server ssl;
    listen [::]:443 ssl;
    server_name [my_domain].com [hostname].[subdomain].com;

    ssl_certificate /etc/ssl/certs/nginx/[certname].pem;
    ssl_certificate_key /etc/ssl/certs/nginx/[certname]-key.pem;

    root /var/www/[document root]/;
    index index.html;

    location /api {
        proxy_pass http://127.0.0.1:[internal port];
    }

    location /web {
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_pass http://127.0.0.1:[internal port];
    }

    location / {
        try_files $uri $uri/ =404;
    }
}

Initially I had listen [::]:443 ssl; only, which worked on host1 but not host2 and host3, adding default_server made host2 and host3 work properly. All three hosts were configured via saltstack with minimal interaction on my part to set them up, the only difference I've been able to think of between the hosts is that host1 and 2 are on a different provider than host3, which obviously can't be the issue. What could I have possibly missed that makes these hosts different causing the need for different configurations.
Edit: remember to check your versions, I'm an idiot

A: There is always a default server. The default_server option just lets you choose the default server instead of nginx choosing it. If your file names are different on each server, the order in which they are evaluated may be different - which means that nginx may have been using a different server block as the default on each server.
See this document for more.


text:
Q: BIOS boot order priorities are fixed after installing 20.04 After installing a dual boot W10/Ubuntu I tried to add space to some of my ubuntu partitions using the same bootable USB disk.
But if I can access BIOS I cannot change anything, it displays FIXED BOOT ORDER in the BOOT menu.
I have seen this Unable to make changes in BIOS after 17.10 installation but I cant get it to work
I have also tried but failed to add to grub (with grub customiser) an entry for my USB-stick.
I think I can find a workaround to upgrade a mounted partition since I already have the unallocated space I need but it bothers me not having access to my own BIOS, if I have to re-install all from scratch, right now I am screwed.
My BIOS


text:
Q: How can I remove focus from select box Options using javascript and css I want to remove focus outline from select options but not from select. how can i do that? I did the following for the select box
select:focus{
  outline:0px
}

I want to do the same for options.

A: When a child <option> of the parent <select> menu is selected/focused it will populate the <select> with the selection and show a focus ring around the element for this reason.
<select> is the parent element of all of your <option> child elements.
The way your <select> menu also displays is also dictated by a few things including your current OS/browser:
e.g.: all <option> elements display with a blue background on :hover and :focus on a Mac for instance
So you have the option of either removing a focus outline entirely from the <select> element and its children OR changing your <select> element into a <ul> with <li> elements that can be styled at will.
Please see this Stack Overflow post for more detail.
--
Please Note: The focus outline serves the purpose of making your element accessible for users on screen readers, so if you remove any sort of focus behavior for selected elements - folks using keyboard navigation won't be able to tell which item is selected. You can check out the W3C documentation for best practices.
You could implement two different types of <select> behavior for users with accessibility concerns (e.g.: adding a class to elements in the event that a screen reader is detected - which can be challenging, so check out this great Hackernoon blog post on the matter) to make sure both types of users' needs are taken care of.
--


text:
Q: Conditional formatting with multiple parameters I'm in Microsoft Access 2013 and trying to conditionally format a cell in a report. My first two expressions work well:
[House Party 2015]=Yes (Green)
[Declined]=Yes (Red)

I'm trying to add a yellow category where an item has been received (House Party 2015 = Yes) but not yet received [House Party Donations List].[Received]=No)
When I use an "And" expression [House Party 2015]=Yes And [Received]=No, nothing happens. I've tried reordering, creating a new field called "Not Received" [House Party Donations List].[Not Received]=Yes, but nothing seems to work.
Any guess as to why this is not working?

A: Is this the sort of output you're looking for?

Here's the conditional formatting I applied (I think the key is to move your AND statement up to the top so it's checked first, otherwise it will look at your [Donated]=Yes rule, which will show as green):

Edit:
As per comments below, here's how to locate the Record Source property of your report (in Access 2013)..
Go in to Design View for the report and go to the Design tab, then click on the Property Sheet button:

The Property Sheet should open on the right-hand side. If you go to the "Data" tab of the Property Sheet, the first property listed will be the Record Source:

The Record Source property states where the report is getting its data from. The data can either be from 1 of your tables or saved queries, in which case it would say something simple like:
[House Party Donations]
Or, it can get its data from the result of an SQL expression, for example:
SELECT Table1.[House Party 2015], Table2.Received FROM Table1 INNER JOIN Table2 ON Table1.ID = Table2.ID;
If you want to do conditional formatting in your report using fields from different tables, it's best to get all your fields in to that Record Source first. This can be done by either referring to a saved query or write/build an SQL expression directly in to the report's Record Source.
If you update your original question to list the fields from the 2 tables and make it clear which field is common to both fields (i.e. how the tables can be linked through primary/foreign keys) then I can probably help you create the query/SQL for your report's Record Source.
For example, I mocked this up in the report's Record Source query builder:

I was then able to add the fields from different originating tables to the report:

And then I could reference them in conditional formatting without ! (bang) notation:

Which results in:


text:
Q: Should new mechanic tags be added post-implementation to their original Meta requests? There is often enough that a feature-request is a good one and it does get implemented. Prior to the implementation of that feature, there isn't necessarily a tag for that feature (by virtue of the fact that the feature doesn't exist yet). Is it proper, then, that once the feature is implemented, that if necessary the original request be retagged with the tag for that feature? This is primarily for new implemented features which have enough substance to produce new tags. I have two example cases where this could turn up as a concern.
[linked-questions] was added to represent the new "Linked" section. There was no specific request that addressed this, and in fact, Jeff announced it on four separate occasions. In this case, the original "requests" were not necessarily directly about the Linked section, it merely was the implemented solution that was used.
[auto-comments] is a tag I'm adding (if it didn't already exist, which I'd be surprised for this) in light of the recent rise of questions on the subject. While looking for candidates to retag, I stumbled across the original request, which is explicitly requesting for auto-comments. In this situation, the original request is indeed about auto-comments, the tag simply didn't exist when the post was first made.
So, what do people think about this? For my own take, adding the tag helps people find the original request for certain mechanics, but in some cases it may seem like you're tagging the answer instead of the question (which feels awkward to me).

A: This seems reasonable to me.  If the question led to a feature being implemented, then that feature is closely related to the question.  Tags are there to help people find this kind of information, so it certainly shouldn't hurt anything to add it.


text:
Q: Is it possible to automate R markdown files? I need to generate a thousand R Markdown files, each essentially the same, just with different titles and a different subset of the data. Is there a way to store those titles and subsets in objects and automate creating and knitting the R Markdown files?

A: Yes. When you klick the knit button in Rstudio, it calls the function
rmarkdown::render(). This can also be done in code, either in a for loop, with apply or the purrr-version of apply called map. You will need to create a rmarkdown-document that takes parameters for the title and the subset first and then pass these to the render-function in said way.
For an introduction to paramters in your documents have a look at the documentation here.