text:
Q: $\alpha_1 \circ \alpha_2 = (1)$ Show that $\alpha_1 = \alpha_2 = (1)$. I want to prove this:
Let $\alpha_1$ and $\alpha_2$ be two disjoint cycles in $S_n$ such that $\alpha_1 \circ \alpha_2 = (1)$ Show that $\alpha_1 = \alpha_2 = (1)$. Generalize this to the product $l$, $l \ge 2$, two-by-two separate round.
And I tried to prove it but I don't have the idea. However here's my way but my professor said it's not true:
If $\alpha_1 \circ \alpha_2 = (1)$, then for any element $x$ in the set $S_n$, we have $\alpha_1(\alpha_2(x)) = x$. This implies that $\alpha_2(x)$ is a fixed point of $\alpha_1$, and so $\alpha_1$ must be the identity permutation $(1)$. Similarly, $\alpha_2$ must also be the identity permutation.
To generalize this to the product of $l$ two-by-two separate rounds, suppose that $\alpha_1, \alpha_2, ..., \alpha_l$ are distinct circuits in $S_n$ such that $\alpha_1 \circ \alpha_2 \circ ... \circ \alpha_l = (1)$. Then for any element $x$ in the set $S_n$, we have $\alpha_1(\alpha_2(...(\alpha_l(x))...)) = x$. This implies that $\alpha_l(x)$ is a fixed point of $\alpha_{l-1}$, $\alpha_{l-2}(x)$ is a fixed point of $\alpha_{l-3}$ and so on. Thus $\alpha_l = \alpha_{l-1} = ... = \alpha_1 = (1)$.
Some other ideas I had was using the inverse and so on but didn't respond.

A: Your reasoning is wrong, perhaps because you misunderstood your teacher.
Given that $\alpha_1$ and $\alpha_2$ are disjoint, each $x$ cannot be changed by both.
So, if $\alpha_1(\alpha_2(x))=x$, for all $x \in S_n$, then, for $x$ such that $\alpha_1(x)\neq x$, we have $\alpha_2(x)=x$, yielding
$$x=\alpha_1(\alpha_2(x))=\alpha_1(x),$$
a contradiction.
So $\alpha_1=(1)$ and that entails that $\alpha_2=(1)$.

For the general case, if $\alpha_1(\alpha_2(\cdots(\alpha_k(x))\cdots))=x$, apply the previous reasoning to $\alpha_1$ as before, and conclude that $\alpha_1$ must be the identity, and so $\alpha_2(\alpha_3(\cdots(\alpha_k(x))\cdots))=x$ (now, only $k-1$ cycles).
Proceed until there are only two, and conclude $\alpha_i=(1)$ for $1\leq i\leq k$.

A: Let us assume that $\alpha_2 \ne (1)$. Then $\exists x_0 \in S_n, \alpha_2(x_0) \ne x_0$. Let us call $x_1 = \alpha_2(x_0)$. Per $\alpha_1 \circ \alpha_2 = (1)$, we must have $\alpha_1(\alpha_2(x_0)) = x_0$ meaning $\alpha_1(x1) = x_0$.
So we have:
$$
\exists x_0, x_1 \in S_n, \left\lbrace
\begin{split}
x_0 \ne x_1 \\
\alpha_2(x_0) = x_1\\
\alpha_1(x_1) = x_0
\end{split}
\right.
$$
This implies that $\alpha_1$ and $\alpha_2$ cannot be disjoint, which is a contradiction.
Hence $\alpha_2$ is $(1)$, and so is $\alpha_1$


text:
Q: Typescript module resolution with custom webpack configuration Any complete guide with full examples on how to make Typescript (latest) module resolution work with custom configured webpack (latest)?
(I know CRA have this support by just adding some option in tsconfig.js)
I tried https://github.com/dividab/tsconfig-paths-webpack-plugin#readme
followed instructions here can't seem to make it work
Tried the tsconfig's baseurl and paths together with webpacks resolve alias still can't make it work.
Thanks in advance

redpajama_set_name: RedPajamaStackExchange


text:
Q: Qt 5 running file from treeView and QFileSystemModel The issue is that I've only recently started c++ programming. My question is as follows:
How do I make the file viewed in mainwindow/treeview run?
The document to view is a plain text document with a static path. sPath is the path to the directory where the files reside.
What follows here is my "mainwindow.cpp" file.
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "QDirModel"
#include "QTreeView"
#include "QFileSystemModel"
#include "QtGui"
#include "QtCore"
#include "QDir"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    QString sPath ="/home/simon/QT Projects/Bra_Programmering/utlatanden/";

    filemodel = new QFileSystemModel(this);
    filemodel->setFilter(QDir::Files | QDir::NoDotAndDotDot);
    filemodel->setNameFilterDisables(false);
    filemodel->setRootPath(sPath);
    ui->treeView->setModel(filemodel);
    ui->treeView->setRootIndex(filemodel->setRootPath(sPath));
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_treeView_doubleClicked(const QModelIndex &index)
{

};

What follows here is my "mainwindow.h" file.
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <mainwindow.h>
#include <QtCore>
#include <QtGui>
#include <QDirModel>
#include <QFileSystemModel>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private slots:

    void on_treeView_doubleClicked(const QModelIndex &index);

private:
    Ui::MainWindow *ui;
    QFileSystemModel *filemodel;
};

#endif // MAINWINDOW_H

A: If you want to open the file with the default text viewer:
void MainWindow::on_treeView_doubleClicked(const QModelIndex &index)
{
    QDesktopServices::openUrl(QUrl::fromLocalFile(filemodel->filePath(index)));
}

Or if you want to open the text file by your Qt application it should be:
void MainWindow::on_treeView_doubleClicked(const QModelIndex &index)
{
    QFile file(filemodel->filePath(index));

    if(file.open(QFile::ReadOnly | QFile::Text))
    {
        QTextStream in(&file);
        QString text = in.readAll();
        // Do something with the text
        file.close();
    }
}


text:
Q: How the meta tags of a method work? I've got this meta SoapHeader, SoapDocumentMethod...how can I know when they are executed?, before the method is executed or after it is executed? and where is the method that this metas are executing? what name it has?
[SoapHeader("AgentInfoHeaderValue")]
[SoapDocumentMethod("http://www.example.com/xml/andromeda#WORK", RequestNamespace = "http://www.example.com/xml/someapi", ResponseNamespace = "http://www.example.com/xml/someapi",
    Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = SoapParameterStyle.Wrapped)]
[return: XmlElement("return", Namespace = "", IsNullable = false, DataType = "base64Binary")]
public byte[] WORK([XmlElement(Namespace = "http://www.example.com/xml/someapi", DataType = "string", Form = XmlSchemaForm.Qualified)] string guid, [XmlElement(Namespace = "http://www.example.com/xml/someapi", DataType = "base64Binary", Form = XmlSchemaForm.Qualified)] byte[] data)
{
   //some actions
}


text:
Q: get the sum after the $unwind and $lookup returns 0 Player collection:
{ "_id" : 1, "Name" : "John Aims", "Gender" : "M", "DoB" : ISODate("1990-01-01T00:00:00Z"), "Nationality" : "USA", "Hand" : "R", "YearTurnedPro" : 2010, "Tournament" : [ { "tournamentID" : 1, "TournamentYear" : 2016 }, { "tournamentID" : 2, "TournamentYear" : 2019 }, { "tournamentID" : 3, "TournamentYear" : 2021 } ] }
{ "_id" : 2, "Name" : "George Brown", "Gender" : "M", "DoB" : ISODate("1997-03-04T00:00:00Z"), "Nationality" : "GB", "Hand" : "L", "YearTurnedPro" : 2013, "Tournament" : [ { "tournamentID" : 2, "TournamentYear" : 2016 }, { "tournamentID" : 5, "TournamentYear" : 2019 } ] }

Tournament collection:
{ "_id" : ObjectId("626c18a3d880647a888888ff"), "TournamentID" : 1, "TournamentCode" : "GS1", "Position" : 8, "PrizeMoney" : 125000, "RankingPoints" : 250 }
{ "_id" : ObjectId("626c18c2d880647a888888ff"), "TournamentID" : 2, "TournamentCode" : "GS1", "Position" : 4, "PrizeMoney" : 250000, "RankingPoints" : 500 }
{ "_id" : ObjectId("626c18ddd880647a888888ff"), "TournamentID" : 3, "TournamentCode" : "GS1", "Position" : 1, "PrizeMoney" : 1000000, "RankingPoints" : 2000 }

1st Question:
Hello, I want to get the sum of ranking points of each player.
I have tried:
db.Player.aggregate([
  {"$unwind" : "$Tournament"},
{"$lookup":
{"from":"Tournament",
"localField":"Tournament.tournamentID",
"foreignField":"TournamentID",
"as":"Tennis-player"}},
  { "$group": {
    "_id": { Name:"$Name" },
    "total_qty": { "$sum": "$Tennis-player.PrizeMoney" }
  }}
])

But I get for every played the sum is 0.
I can show it on playground as it is using more than 1 collection.
2nd question:
Would it be better to create only 1 collections with all the data?

A: *

*$unwind

*$lookup

*$set - As from stage 2 Tennis-player returns an array with guarantee only 1 document in array. Use $first to get the first document in Tennis-player array field to become a document field.

*$group
db.Player.aggregate([
  {
    "$unwind": "$Tournament"
  },
  {
    "$lookup": {
      "from": "Tournament",
      "localField": "Tournament.tournamentID",
      "foreignField": "TournamentID",
      "as": "Tennis-player"
    }
  },
  {
    $set: {
      "Tennis-player": {
        "$first": "$Tennis-player"
      }
    }
  },
  {
    "$group": {
      "_id": {
        Name: "$Name"
      },
      "total_qty": {
        "$sum": "$Tennis-player.PrizeMoney"
      }
    }
  }
])

Sample Mongo Playground

Alternative:

*

*$lookup - Work $lookup with an Array

*$project - Decorate output documents. Create total_qty field and use $reduce to perform sum operation of Tennic-player.PrizeMoney.

db.Player.aggregate([
  {
    "$lookup": {
      "from": "Tournament",
      "localField": "Tournament.tournamentID",
      "foreignField": "TournamentID",
      "as": "Tennis-player"
    }
  },
  {
    "$project": {
      "_id": {
        Name: "$Name"
      },
      "total_qty": {
        "$reduce": {
          "input": "$Tennis-player",
          "initialValue": 0,
          "in": {
            $sum: [
              "$$value",
              "$$this.PrizeMoney"
            ]
          }
        }
      }
    }
  }
])

Sample Mongo Playground (Alternative)


text:
Q: Json to csv. How to convert it? I'm experiencing some troubles to convert a Json (with nested values) to a CSV file (I want the headers at first line and the json values below).
I almost did it but I still have some issues in my output.
I wrote everything I've done so far hoping that would make the task easier for you.
Here's the json :
[
  {
    "id": 0,
    "email": "colleengriffith@quintity.com",
    "tags": [
             "consectetur",
             "quis"
    ],
    "profiles": {
      "facebook": {
        "id": 0,
        "picture": "//fbcdn.com/a2244bc1-b10c-4d91-9ce8-184337c6b898.jpg"
      },
      "twitter": {
        "id": 0,
        "picture": "//twcdn.com/ad9e8cd3-3133-423e-8bbf-0602e4048c22.jpg"
      }
    }
  },
      {
    "id": 1,
    "email": "maryellengriffin@ginkle.com",
    "tags": [
             "veniam",
             "elit",
             "mollit"
    ],
    "profiles": {
      "facebook": {
        "id": 1,
        "picture": "//fbcdn.com/12e070e0-21ea-4663-97d0-46bc9c7b67a4.jpg"
      },
      "twitter": {
        "id": 1,
        "picture": "//twcdn.com/3057792f-5dfb-4c4b-86b5-cce4d6bbf7ac.jpg"
      }
    }
  }
]

and the ouput I want :
id,email,tags,profiles.facebook.id,profiles.facebook.picture,profiles.twitter.id,profiles.twitter.picture
0,colleengriffith@quintity.com,"consectetur,quis",0,//fbcdn.com/a2244bc1-b10c-4d91-9ce8-184337c6b898.jpg,0,//twcdn.com/ad9e8cd3-3133-423e-8bbf-0602e4048c22.jpg
1,maryellengriffin@ginkle.com,"veniam,elit,mollit",1,//fbcdn.com/12e070e0-21ea-4663-97d0-46bc9c7b67a4.jpg,1,//twcdn.com/3057792f-5dfb-4c4b-86b5-cce4d6bbf7ac.jpg

Here's what I came up to so far :
require 'csv'
require 'json'
require 'set'

def get_recursive_keys(hash, nested_key=nil)
  hash.each_with_object([]) do |(k,v),keys|
    k = "#{nested_key}.#{k}" unless nested_key.nil?
      if v.is_a? Hash
      keys.concat(get_recursive_keys(v, k))
    else
      keys << k
    end
  end
end

json = JSON.parse(File.open("live.json").read)
headings = Set.new
json.each do |hash|
  headings.merge(get_recursive_keys(hash))
end

CSV.open('file3.csv', 'w') do |csv|
  csv << headings
  json.each do |hash|
    row = {}
    headings.each do |heading|
      row[heading] = nil
    end
    hash.each do |k,v|
      row[k] = v.to_s.gsub(/\r\n?/, "").delete("\n").delete("\r")
    end
    csv << row.values
  end
end

When I run, I get this :
id,email,tags,profiles.facebook.id,profiles.facebook.picture,profiles.twitter.id,profiles.twitter.picture
0,colleengriffith@quintity.com,"[""consectetur"", ""quis""]",,,,,"{""facebook""=>{""id""=>0, ""picture""=>""//fbcdn.com/a2244bc1-b10c-4d91-9ce8-184337c6b898.jpg""}, ""twitter""=>{""id""=>0, ""picture""=>""//twcdn.com/ad9e8cd3-3133-423e-8bbf-0602e4048c22.jpg""}}"
1,maryellengriffin@ginkle.com,"[""veniam"", ""elit"", ""mollit""]",,,,,"{""facebook""=>{""id""=>1, ""picture""=>""//fbcdn.com/12e070e0-21ea-4663-97d0-46bc9c7b67a4.jpg""}, ""twitter""=>{""id""=>1, ""picture""=>""//twcdn.com/3057792f-5dfb-4c4b-86b5-cce4d6bbf7ac.jpg""}}"

So I do have everything I need, however, I still have the bracket and the quote and I want to remove them from the csv file.
If anyone has an idea or a tip, that would be great !
Any help appreciated,
Thanks.

A: Set is explicitly documented to be unordered so you should convert your headings to an Array as soon as you've populated it. Yes, the current standard implementation is ordered but you're better off avoiding implementation-dependent assumptions. So the first step is to make sure headings is guaranteed to have a consistent order before we do anything with it:
headings = headings.to_a
CSV.open('file3.csv', 'w') do |csv|
  ...
end

Then you just need to fix up how you encode arrays and hashes on their way into the CSV. You can use Hash#dig to find the nested values you want and then patch up any arrays that come out with a simple Array#join call:
json.each do |hash|
  row = headings.map do |h|
    v = hash.dig(*h.split('.'))       # Dig out the (possibly) nested value
    v.is_a?(Array) ? v.join(',') : v  # Fix up arrays
  end
  csv << row
end

We're still making some assumptions (no commas in "tags", no periods in the JSON keys, ...) of course.

You could also store the headers as arrays so that you don't have to split all the time. Then you'd need to throw a join('.') in when building your header row:
add_dots = ->(a) { a.join('.') }
csv << headings.map(&add_dots)

and just splat the arrays when building v:
v = hash.dig(*h)

and adjust get_recursive_keys to work with arrays rather than period delimited strings.

A: I think you can use a gem. Which makes your things easier. Why reinvent the wheel?.
gem install json2csv

Refer here for more details


text:
Q: Значение исключения При работе с mysql получаю такую ошибку :
Traceback (most recent call last):
  File "C:/Users/Anon/Desktop/AP/AP_2_0.py", line 165, in <module>
    cursor.execute(sqlzapros)
  File "C:\Users\Anon\AppData\Roaming\Python\Python36\site-packages\mysql\connector\cursor.py", line 561, in execute
    self._handle_result(self._connection.cmd_query(stmt))
  File "C:\Users\Anon\AppData\Roaming\Python\Python36\site-packages\mysql\connector\connection.py", line 525, in cmd_query
    result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query))
  File "C:\Users\Anon\AppData\Roaming\Python\Python36\site-packages\mysql\connector\connection.py", line 427, in _handle_result
    raise errors.get_exception(packet)
mysql.connector.errors.IntegrityError: 1062 (23000): Duplicate entry 'vallues:values2' for key 'line'

Я понимаю что можно сделать обработку исключения,этого : mysql.connector.errors.IntegrityError
Но мне хотелось бы получить непосредственно значение данной строки,что бы в дальнейшем убрать ее из строки запроса.

A: Чтобы получить только саму ошибку (без остального стека) в виде строки:
In [32]: import traceback

In [33]: d = {}

In [34]: try:
    ...:     print(d['NOT_EXISTING_KEY'])
    ...: except Exception as e:
    ...:     exinfo = traceback.format_exception_only(type(e), e)
    ...:     raise
    ...:
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-34-6d43cc6d6822> in <module>()
      1 try:
----> 2     print(d['NOT_EXISTING_KEY'])
      3 except Exception as e:
      4     exinfo = traceback.format_exception_only(type(e), e)
      5     raise

KeyError: 'NOT_EXISTING_KEY'
In [36]: exinfo
Out[36]: ["KeyError: 'NOT_EXISTING_KEY'\n"]

In [37]: ''.join(exinfo)
Out[37]: "KeyError: 'NOT_EXISTING_KEY'\n"

Если просто перехватить строковое представление исключения, то часто теряется ценная информация.
Пример:
In [38]: try:
    ...:     print(d['AAA'])
    ...: except Exception as e:
    ...:     err = str(e)
    ...:

In [39]: err
Out[39]: "'AAA'"

получилось совершенно непонятное сообщение об ошибке.
PS в случае перехвата любого (Exception) исключения лучше в конце всегда добавлять raise, т.е. завершать выполнение с ошибкой, чтобы избежать неприятных сюрпризов
PPS Еще стоило бы вести "логи" того, что происходит в процессе выполнения - для этого можно воспользоваться модулем logging:
import logging
from pymysql.err import MySQLError

logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger(__name__)

try:
    cursor.execute(sqlzapros)
except MySQLError as e:
    log.exception("message")
    raise

A: try:
    assert False, "err_text '1' > '2' !"
except AssertionError as ex:
    print(type(ex))  # <class 'AssertionError'>
    print(str(ex))  # "err_text '1' > '2' !"

import sys
try:
    raise UserWarning("err_text '1' > '2' !")
except Exception:
    exc_type, exc_val, exc_tb = sys.exc_info()
    print(exc_type.__name__)  # "UserWarning"
    print(exc_val)  # "err_text '1' > '2' !"

import traceback
def full_tb_write(*args):
    '''логировать traceback'''
    if not args:
        exc_type, exc_val, exc_tb = sys.exc_info()
    elif len(args) == 3:
        exc_type, exc_val, exc_tb = args
    elif len(args) == 1:
        exc_type, exc_val, exc_tb = args[0].__class__, args[0], args[0].__traceback__

    traceback.print_tb(exc_tb, file=sys.stdout)
    with open('_log.log', 'a') as log:
        traceback.print_tb(exc_tb, file=log)

try:
    raise UserWarning("err_text '1' > '2' !")
except Exception:
    full_tb_write(*sys.exc_info())
try:
    raise UserWarning("err_text '1' > '2' !")
except Exception as ex:
    full_tb_write(ex)
try:
    raise UserWarning("err_text '1' > '2' !")
except:
    full_tb_write()

import contextlib
with contextlib.suppress(KeyError, AssertionError):
    {None: None}['key']

try:
    {None: None}['key']
except (KeyError, AssertionError):
    pass
except Exception:
    raise
else:
    pass
finally:
    pass

получить непосредственно значение данной строки
import re

err_list = []
for i in iterable:
    try:
        do(i)  # "1062 (23000): Duplicate entry 'vallues:values2' for key 'line'"
    except mysql.connector.errors.IntegrityError as ex:
        e = str(ex)
        if "Duplicate entry" in e:
            vals = re.findall(r'\'(.+?)\'', e)
            (val1, val2), key = vals[0].split(':', 1), vals[1]
            err_list.append([key, val1, val2])  # ['line', 'vallues', 'values2']


text:
Q: Better way to change class? I have a program that reads some bytes from a file. If the second byte is exactly 0, it should cast the current type to the correct one.
This is what I have:
struct Event {
    virtual ~Event() {}
};

struct MidiEvent : public Event {
    unsigned m_channel;
    uint8_t byte1;
    uint8_t byte2;
    MidiEvent(uint8_t channel) : m_channel{ channel } {}
};

struct EventNoteOff : public MidiEvent {
    uint8_t note() { return byte1; }
    uint8_t velocity() { return byte2; }
    EventNoteOff(std::fstream& t_midi_file, uint8_t channel);
};

struct EventNoteOn : public MidiEvent {
    uint8_t note() { return byte1; }
    uint8_t velocity() { return byte2; }
    EventNoteOn(std::fstream& t_midi_file, uint8_t channel);
};

And this is the part where the program decides which class assign to each bytes:
// track_type and track_chanel is a "uint8_t", m_event is a "Event *" and t_midi_file is a std::fstream opened with 'in' and 'binary' flags.

switch (track_type) {
    case 0x80:
        m_event = new EventNoteOff{ t_midi_file, track_channel };
        break;
    case 0x90:
        t_midi_file.seekg(1, t_midi_file.cur);
        char c;
        t_midi_file.read(&c, 1);
        t_midi_file.seekg(-2, t_midi_file.cur);
        if (c == 0)
            m_event = new EventNoteOff{ t_midi_file, track_channel };
        else
            m_event = new EventNoteOn{ t_midi_file, track_channel };
        break;
    ...
}

Whenever track_type is 0x90 and byte2 has the value of 0, i want m_event to behave like a EventNoteOff* with same values as before, not as an EventNoteOn*. My attempt works but I get a feel that this approach is dirty because it involves moving around the file read pointer and creating a temporal variable, when I think it could be done with a reinterpret_cast.
I tried doing
    case 0x90:
        m_event = new EventNoteOn{ t_midi_file, track_channel };
        if(dynamic_cast<EventNoteOn*>(m_event)->velocity() == 0)
            m_event = reinterpret_cast<EventNoteOff*>(m_event);
        break;

with no luck.
What is a better way to do this?


text:
Q: SQL Database Function if/then In my supabase database, I have a list of words along with their uuids in the form of

uuid
word
unique_chars
found_count

x1
apple
4
0

y2
banana
3
0

I want to return all words, which contain a specific letter – say "E" (called "main char") – and a defined set of 6 other letters (charone to charsix) from the table. Each word can (but does not have to) have the other letters; however, it must not have any letter which was not defined before (charone to charsix) Therefore, I tried using an SQL Database Function like this:
create or replace function get_possible_words_t2(mainchar text, charone text, chartwo text, charthree text, charfour text, charfive text, charsix text)
returns setof dict
language sql
as $$
  select *
  from dict
    where word ILIKE (mainchar); --HAS TO INCLUDE MAINCHAR IN WORD
    -- if charone == A = true -> skip | if charone == A = false -> and not word ilike ('%a%')
$$;

I can not make the if/then part work. I want to include the line and not word ilike ('%a%') only if charone is not equal to A. Can someone help me with the syntax? Which ever way I try, it's not working...

A: When you have this data:
CREATE TABLE words (
   word VARCHAR(200),
   id INTEGER PRIMARY KEY NOT NULL);

INSERT INTO words VALUES
   ('apple',1),
   ('banana',2),
   ('pear',3),
   ('Pineapple',4);

And these 2 functions:
DROP FUNCTION IF EXISTS cnt1(s VARCHAR(200), t varchar(200));
CREATE FUNCTION cnt1(s VARCHAR(200), t VARCHAR(200)) RETURNS INTEGER
  AS 'with RECURSIVE cte as (
  select 0 as x, $1 as y, $1 as z
  union all
  select x+1,y,substring(y,x+1,1) from cte  where  x<length($1))
select count(distinct(z)) from cte where x>0 and position(z in $2)>0;'
 LANGUAGE SQL;

DROP FUNCTION IF EXISTS cnt2(s VARCHAR(200));
CREATE FUNCTION cnt2(s VARCHAR(200)) RETURNS INTEGER
  AS 'with RECURSIVE cte as (
  select 0 as x, $1 as y, $1 as z
  union all
  select x+1,y,substring(y,x+1,1) from cte  where  x<length($1))
select count(distinct(z)) from cte where x>0 ;'
 LANGUAGE SQL;

You can do:
SELECT
   word,
   cnt2(word) unique_chars,
   cnt1(word, 'charone') found_count
FROM words;

word
unique_chars
found_count

apple
4
2

banana
3
2

pear
4
3

Pineapple
7
3

And apple has 4 unique characters, and 2 of them (a and e) are in charone.
NOTE: I hope this comes close to your requirements...


text:
Q: Adding helper function for both foundation and handlers I want to add an helper function to my yesod app that will "live" in a seperate file and could be imported in both foundation file and the handlers, i dont want to have reimport all the modules again. and i cant use the Import module because im getting circular dependencies ( Import -> helper -> foundation -> Import).

A: The GHC manual has a section on mutually recursive modules.

A: I think rather than messing around with mutually-recursive modules it might be better to just re-import all the stuff from Import that you want.


text:
Q: Multiple accessing to singleton object in .net I want to ask a question that comes my mind. This question about memory accessing, contains the object with singleton lifetime in asp.net core. So, suppose exists in this structure two thread. one of them is the normal request/response thread used in asp net. The other thread is continuous running worker service in  background.
My plan is create the task queue. And in the queue, I'm storing tasks I don't want execute in request/response thread. This stored functions is continuous executing in background.
This code partition's contains to Task Queue. So this class using in background worker service and anywhere in asp.net.
public class EventQueue : IEventQueue
{
            public LinkedList<Task> Queue = new LinkedList<Task>();

            public void AddEvent(Task task)
            {
                Queue.AddFirst(task);
            }

            public Task GetNextEvent()
            {
                var task = Queue.Last.Value;
                Queue.RemoveLast();
                return task;
            }
    }

This code partition's contains to worker service. It's doing one by one execute in queue tasks
public class QueueWorker : BackgroundService
    {
        private readonly IEventQueue _queue;

        public QueueWorker(IEventQueue queue)
        {
            _queue = queue;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                    var task = _queue.GetNextEvent();
                    if (task != null)
                        task.RunSynchronously();
            }
        }
    }

This code partition's contains to registered services.
services.AddSingleton<IEventQueue,EventQueue>();
services.AddHostedService<QueueWorker>();

Questions:

*

*Does this structure work well? I think, It's will not work well bcs there is multiple access to queue instance. Or rather worker service is always accessing to queue instance. Therefore there will be no time to access for other threads. So this approach's right?

*if singleton lifetime wasn't used and EventQueue was static(at least LinkedList property was static), Would things be different?

*Do you have any suggestions for the improvement of this structure?

A: There is Channel<T> class that is designed specifically for producer/consumer scenario like this. For your use case, say if you have a message class to send to your queue like:
class Message { public int AmountToIncrement { get; set; } }

You can register Channel<Message>, ChannelReader<Message> and ChannelWriter<Message> as singletons:
services.AddSingleton<Channel<Message>>(Channel.CreateUnbounded<Message>());
services.AddSingleton<ChannelReader<Message>>(svc => svc.GetRequiredService<Channel<Message>>().Reader);
services.AddSingleton<ChannelWriter<Message>>(svc => svc.GetRequiredService<Channel<Message>>().Writer);

So now you can inject ChannelWriter<Message> to where you want to send message, and ChannelReader<Message> to your background service (via constructor, for example). Your ExecuteAsync can use ChannelReader<T>.ReadAsync to wait for message and process it accordingly.

A: For such task I would suggest taking a look at ConcurrentQueue collection.
This should provide a thread safe collection without need for any locks.
Alternatively You could use SemaphoreSlim object as a lock, if You cannot use aforementioned queue.
As far as I know, using ConcurrentQueue should remove the access block You mentioned. If You go with SemaphoreSlim, then I would suggest a small Task.Delay() in background service loop.
As for improvement, You could always try to remodel this service to make use of events, so when something is added to queue, background service will then start processing until nothing is left.

A: I will advice against the handling of tasks on a seperate queue thread with a worker backround something.
Instead consider using async Tasks, .net is really good at pushing through data as each task has an own thread anyway this structure frees up your response thread enough:
[HttpGet("")]
public async Task<IActionResult> Get(){
  return await Task<IActionResult>.Factory.StartNew(() => {
      //TODO: Your lengthy task here
  });
}

Now say you wanted a worker type object, does it have to be a singleton? i guess not, but regardless it can be injected, however singletons have to handle concurrent requests, they really have to be required to consider using.
private readonly IWorkerInterface _worker;

public ControllerConstructor(IWorkerInterface worker){
  //Assign variable to controller variable
  _worker = worker ?? throw new ArgumentNullException(nameof(worker));
}

[HttpGet("")]
public async Task<IActionResult> Get(){
  return await Task<IActionResult>.Factory.StartNew(() => {
      //TODO: Your lengthy task here
      _worker.DoWork();
  });
}

what You get with async await pattern is that the thread is freed up to serve as soon as the task is created from factory and a wait handle is created and that is really flippin' fast, only to be required again once the task has completed.
If you want a threadsafe queue consider using the ConcurrentQueue
the problem with the background worker, as i see it is that it is not a thread pool, unless it needs it, and a thread pool is already at Your disposal through the task.factory
After all if we really want a queue and not handle our work up front, wouldn't we want it persistent, so that once controller has accepted request, it cannot be lost on server crash? then You need to consider another technology than one which lives and dies with the webserver.
Now you could have your webserver publishing on a topic on a persistent service bus which is subscribed to by your background worker only to be completed when processing actually succeeded ... i think what You have in mind is something like this, but i fear that trying to build it into the webservers RAM storage will ultimately give you headaches.


text:
Q: how to get values based on userid from firebase database using flutter I try to experience Firebase Live database with flutter. i would like get values from firebase database based on userid.  that means if user login with a mail he needs to his details based on his userid. can anyone help me in these.

A: If you have this database:
users
 userId
    mail: userx@gmail.com
    name: userx

Then to get data based on userId, try the following:
 final FirebaseDatabase database = new FirebaseDatabase(app: widget.app);
 _messagesRef = database.reference().child('users');

_messageRef.orderByKey().equalTo(userId).once().then((DataSnapshot snapshot) {
  print('Connected to the database and read ${snapshot.value}');
});

First configure the database, then reference the location, and use the query orderByKey() to be able to get the data based on the userId provided.
Check the example here:
https://github.com/flutter/plugins/blob/master/packages/firebase_database/example/lib/main.dart#L60


text:
Q: How to have iOS app communicate with database server? I have a database on a database server. No web service in place to be consumed by a web application.
If I want my iOS app to communicate with a database server (send & receive data), I know I can create a web service and then call that service from my iOS app. But what web service is recommended for this? Should I just write a .asmx web service in .NET or should I go for MVC WEB API or may be go for WCF ?? I have spend hours doing research on this. Please help.

A: A lot will depend on where you expect the service to be hosted, and what technology stack(s) are supported by the host. If you are self-hosting, then do whatever works in the technologies you know and understand. If you want to use a host that targets its services to small-to-midsize independent development teams, many providers like Heroku support things like Rails services. PHP is always an option as well. Microsoft-based solutions and Java-based solutions tend to be more widely used in larger enterprises and data centers, and if that's where you'll host your service then these would also be good options. And of course I'm speaking in broad generalities here: For any general trends I might list here there are lots of exceptions where other approaches make sense.
If you'd rather let the decision be driven by what makes things easiest for your iOS code, I would recommend you start with server-side technologies that support REST-ful interfaces using JSON to represent your service's resources. REST-ful services are very easy to consume from iOS, and JSON-based representations of resources are very easy to parse and produce in Objective-C.
I am personally used this approach to set a direction for my app. For the service side, I am going with a Rails implementation of REST-ful web services. I'm a Java developer by profession, but for a small independent project the options for hosting Java services were more limiting than with Rails so I've picked up rails on the side to make my project work. So far it's suited my project quite well.


text:
Q: How to change height of the rows of a responsive table using divs I'm trying to create a responsive table (a simple keyboard) but only the cells are being resized. I want the full keyboard to be displayed in the screen without having to scroll.
This is my code: https://jsfiddle.net/723ar2f5/2/embedded/result/
  #teclat {
    display: table;
    table-layout: fixed;
    border-spacing:5px;
    position: absolute;
    height: 100%;
  }
  #lletra {
    font-family: Verdana;
    font-size: 9vw;
  }
  .fila {
    display: table-row;
  }

  .fila div {
    display: table-cell;
  }
  .tecla {
    width: 100%;
    height: 100%;
  }

It looks fine if the screen is big enough but not in mobile screens.

A: Try something along this.
.tecla {
    width: 100%;
    height: 13vw;
}

Full code and
DEMO jsfiddle

 function esborra(tot) {
  var text = document.getElementById('text');
  if (tot == "s")
   text.value = "";
  else
   text.value = text.value.slice(0,-1);
 }
 window.onload = function(e){
   setTimeout(window.scrollTo(0,1),10);

   var elements = document.getElementsByClassName('tecla');
   for (var i = 0; i < elements.length; i++) {
      elements[i].addEventListener('click', (function(i) {
        return function() {
          document.getElementById('text').value = document.getElementById('text').value + this.getElementById('lletra').textContent;
        };
      })(i), false);
   }
 }
  body {
    height: 100%;
    width: 100%;
  }
  #teclat {
    /* display: table; */
    /* table-layout: fixed; */
    /* border-spacing: 5px; */
    /* position: relative; */
    height: 100vh;
  }
  #lletra {
    font-family: Verdana;
    font-size: 9vw;
  }
  .fila {
    display: table-row;
  }

  .fila div {
    display: table-cell;
  }
.tecla {
    width: 100%;
    height: 13vw;
}
  .tecla_marc {
    fill: red;
    stroke:black;
    stroke-width:5;
    opacity:0.5;
  }

<input type="text" id="text" style="width: 60%" readonly/><button type="button" onclick="esborra('1')"></button><button type="button" onclick="esborra('s')">Esborra</button>

<svg class="tecla">
  <rect x="2" y="2" rx="20" ry="20" width="95%" height="95%" class="tecla_marc" />
  <text id="lletra" class="lletra" alignment-baseline="middle" text-anchor="middle" fill="#ffffff" x="50%" y="52%">A</text>
</svg>

<svg class="tecla">
  <rect x="2" y="2" rx="20" ry="20" width="95%" height="95%" class="tecla_marc" />
  <text id="lletra" class="lletra" alignment-baseline="middle" text-anchor="middle" fill="#ffffff" x="50%" y="52%">B</text>
</svg>

<svg class="tecla">
  <rect x="2" y="2" rx="20" ry="20" width="95%" height="95%" class="tecla_marc" />
  <text id="lletra" class="lletra" alignment-baseline="middle" text-anchor="middle" fill="#ffffff" x="50%" y="52%">C</text>
</svg>

<svg class="tecla">
  <rect x="2" y="2" rx="20" ry="20" width="95%" height="95%" class="tecla_marc" />
  <text id="lletra" class="lletra" alignment-baseline="middle" text-anchor="middle" fill="#ffffff" x="50%" y="52%">D</text>
</svg>

<svg class="tecla">
  <rect x="2" y="2" rx="20" ry="20" width="95%" height="95%" class="tecla_marc" />
  <text id="lletra" class="lletra" alignment-baseline="middle" text-anchor="middle" fill="#ffffff" x="50%" y="52%">E</text>
</svg>

<svg class="tecla">
  <rect x="2" y="2" rx="20" ry="20" width="95%" height="95%" class="tecla_marc" />
  <text id="lletra" class="lletra" alignment-baseline="middle" text-anchor="middle" fill="#ffffff" x="50%" y="52%">F</text>
</svg>

<svg class="tecla">
  <rect x="2" y="2" rx="20" ry="20" width="95%" height="95%" class="tecla_marc" />
  <text id="lletra" class="lletra" alignment-baseline="middle" text-anchor="middle" fill="#ffffff" x="50%" y="52%">G</text>
</svg>

<svg class="tecla">
  <rect x="2" y="2" rx="20" ry="20" width="95%" height="95%" class="tecla_marc" />
  <text id="lletra" class="lletra" alignment-baseline="middle" text-anchor="middle" fill="#ffffff" x="50%" y="52%">H</text>
</svg>

<svg class="tecla">
  <rect x="2" y="2" rx="20" ry="20" width="95%" height="95%" class="tecla_marc" />
  <text id="lletra" class="lletra" alignment-baseline="middle" text-anchor="middle" fill="#ffffff" x="50%" y="52%">I</text>
</svg>

<svg class="tecla">
  <rect x="2" y="2" rx="20" ry="20" width="95%" height="95%" class="tecla_marc" />
  <text id="lletra" class="lletra" alignment-baseline="middle" text-anchor="middle" fill="#ffffff" x="50%" y="52%">J</text>
</svg>

<svg class="tecla">
  <rect x="2" y="2" rx="20" ry="20" width="95%" height="95%" class="tecla_marc" />
  <text id="lletra" class="lletra" alignment-baseline="middle" text-anchor="middle" fill="#ffffff" x="50%" y="52%">K</text>
</svg>

<svg class="tecla">
  <rect x="2" y="2" rx="20" ry="20" width="95%" height="95%" class="tecla_marc" />
  <text id="lletra" class="lletra" alignment-baseline="middle" text-anchor="middle" fill="#ffffff" x="50%" y="52%">L</text>
</svg>

<svg class="tecla">
  <rect x="2" y="2" rx="20" ry="20" width="95%" height="95%" class="tecla_marc" />
  <text id="lletra" class="lletra" alignment-baseline="middle" text-anchor="middle" fill="#ffffff" x="50%" y="52%">M</text>
</svg>

<svg class="tecla">
  <rect x="2" y="2" rx="20" ry="20" width="95%" height="95%" class="tecla_marc" />
  <text id="lletra" class="lletra" alignment-baseline="middle" text-anchor="middle" fill="#ffffff" x="50%" y="52%">N</text>
</svg>

<svg class="tecla">
  <rect x="2" y="2" rx="20" ry="20" width="95%" height="95%" class="tecla_marc" />
  <text id="lletra" class="lletra" alignment-baseline="middle" text-anchor="middle" fill="#ffffff" x="50%" y="52%">O</text>
</svg>

<svg class="tecla">
  <rect x="2" y="2" rx="20" ry="20" width="95%" height="95%" class="tecla_marc" />
  <text id="lletra" class="lletra" alignment-baseline="middle" text-anchor="middle" fill="#ffffff" x="50%" y="52%">P</text>
</svg>

<svg class="tecla">
  <rect x="2" y="2" rx="20" ry="20" width="95%" height="95%" class="tecla_marc" />
  <text id="lletra" class="lletra" alignment-baseline="middle" text-anchor="middle" fill="#ffffff" x="50%" y="52%">Q</text>
</svg>

<svg class="tecla">
  <rect x="2" y="2" rx="20" ry="20" width="95%" height="95%" class="tecla_marc" />
  <text id="lletra" class="lletra" alignment-baseline="middle" text-anchor="middle" fill="#ffffff" x="50%" y="52%">R</text>
</svg>

<svg class="tecla">
  <rect x="2" y="2" rx="20" ry="20" width="95%" height="95%" class="tecla_marc" />
  <text id="lletra" class="lletra" alignment-baseline="middle" text-anchor="middle" fill="#ffffff" x="50%" y="52%">S</text>
</svg>

<svg class="tecla">
  <rect x="2" y="2" rx="20" ry="20" width="95%" height="95%" class="tecla_marc" />
  <text id="lletra" class="lletra" alignment-baseline="middle" text-anchor="middle" fill="#ffffff" x="50%" y="52%">T</text>
</svg>

<svg class="tecla">
  <rect x="2" y="2" rx="20" ry="20" width="95%" height="95%" class="tecla_marc" />
  <text id="lletra" class="lletra" alignment-baseline="middle" text-anchor="middle" fill="#ffffff" x="50%" y="52%">U</text>
</svg>

<svg class="tecla">
  <rect x="2" y="2" rx="20" ry="20" width="95%" height="95%" class="tecla_marc" />
  <text id="lletra" class="lletra" alignment-baseline="middle" text-anchor="middle" fill="#ffffff" x="50%" y="52%">V</text>
</svg>

<svg class="tecla">
  <rect x="2" y="2" rx="20" ry="20" width="95%" height="95%" class="tecla_marc" />
  <text id="lletra" class="lletra" alignment-baseline="middle" text-anchor="middle" fill="#ffffff" x="50%" y="52%">W</text>
</svg>

<svg class="tecla">
  <rect x="2" y="2" rx="20" ry="20" width="95%" height="95%" class="tecla_marc" />
  <text id="lletra" class="lletra" alignment-baseline="middle" text-anchor="middle" fill="#ffffff" x="50%" y="52%">X</text>
</svg>

<svg class="tecla">
  <rect x="2" y="2" rx="20" ry="20" width="95%" height="95%" class="tecla_marc" />
  <text id="lletra" class="lletra" alignment-baseline="middle" text-anchor="middle" fill="#ffffff" x="50%" y="52%">Y</text>
</svg>

<svg class="tecla">
  <rect x="2" y="2" rx="20" ry="20" width="95%" height="95%" class="tecla_marc" />
  <text id="lletra" class="lletra" alignment-baseline="middle" text-anchor="middle" fill="#ffffff" x="50%" y="52%">Z</text>
</svg>

<svg class="tecla">
  <rect x="2" y="2" rx="20" ry="20" width="95%" height="95%" class="tecla_marc" />
  <text id="lletra" class="lletra" alignment-baseline="middle" text-anchor="middle" fill="#ffffff" x="50%" y="52%"> </text>
</svg>


text:
Q: I want to change individual element counter but when I increment the count it increments all the elements count What I want is to increment the count for each individual item but when I'm trying to do that it changes for every element rendered. I'm getting data from API and fetching it to redux store and mapping over the array. But could not differ each element.
return (
    <View style={styles.Container}>
      {movies ? (
        movies.map((data,i) => {
          const IMAGE_URL = data.image;
          return (
            <Card key={i}>
              <View style={styles.Content}>
                <Card.Cover style={styles.image} source={{ uri: IMAGE_URL }} />
                <ScrollView style={styles.ProductDetails}>
                  <Text
                    style={{
                      fontSize: 15,
                      fontWeight: "bold",
                      paddingBottom: 10,
                    }}
                  >
                    {data.title}
                  </Text>
                  <Paragraph>{data.description}</Paragraph>
                </ScrollView>
              </View>

              <View style={styles.BottomButtonView}>
                <View style={{ flexDirection: "row", alignItems: "center" }}>
                  <TouchableOpacity
                    key={i}
                    style={styles.ButtonContainer}
                    onPress={() => setCount(count+1)}
                  >
                    <Text style={{ color: "white" }}>+</Text>
                  </TouchableOpacity>

                  <Text style={{ padding: 10 }}>{count}</Text>

                  <TouchableOpacity
                    style={styles.ButtonContainer}
                    onPress={() => console.log('dec')}
                  >
                    <Text style={{ color: "white" }}>-</Text>
                  </TouchableOpacity>
                </View>
                <TouchableOpacity
                  onPress={() => console.log("Added to Cart")}
                  style={styles.AddToCart}
                >
                  <Text style={{ color: "white" }}>${data.price}</Text>
                </TouchableOpacity>
              </View>
            </Card>
          );
        })
      ) : (
        <Text>Getting Data....</Text>
      )}
    </View>
  );
}

A: Updating an Item in an Array :
function updateObjectInArray(array, action) {
  return array.map((item, index) => {
    if (index !== action.index) {
      // This isn't the item we care about - keep it as-is
      return item
    }

    // Otherwise, this is the one we want - return an updated value
    return {
      ...item,
      ...action.item
    }
  })
}

for Example :
const changePrice = (itemArray, item) => {
  return itemArray.map(reduxItem => {
     if(reduxItem.id === item.id){
       reduxItem.price = reduxItem.price + reduxItem.price
     }

     return reduxItem
  });
};


text:
Q: Combine multiple categories into one in Pandas I have a dataset with a column that contains categories. What I'd like to do is to combine these categories into new categories.
My dataset looks like follows (the categories column is a string column) and I have like 160 categories.
Below in my example, only four categories are shown.
Category
ZA-01
ZA-01
ZA-01
ZA-01
XA-01
XA-01
XA-01
XA-01
YA-01
YA-01
YA-01
YA-01
WA-01
WA-01
WA-01
WA-01

What I would like to get is the following (with the original order of the rows in the dataframe being unchanged, this is very important)
Category     New_Category
ZA-01        A
ZA-01        A
ZA-01        A
ZA-01        A
XA-01        A
XA-01        A
XA-01        A
XA-01        A
YA-01        B
YA-01        B
YA-01        B
YA-01        B
WA-01        B
WA-01        B
WA-01        B
WA-01        B

The easiest way to do this is to use an if elif statement but if you have like 160 categories, this is a daunting task to do and it could go wrong easily.
What I would like Python to do is to take the unique categories with df.[['categories]].unique() which preserves the order of the categories in the dataframe and then say to Python: group category one (ZA-01) and two (XA-01) into a new one named A, then group category three (YA-01) and four (WA-01) into a new one named B etc.
Is there a way to this in Python without using an if elif statement?

------------------Edit-----------------------
What if I had
Group    Category
A        ZA-01
A        ZA-01
A        ZA-01
A        ZA-01
A        XA-01
A        XA-01
A        XA-01
A        XA-01
A        ZZ-12
A        ZX-11
B        YA-01
B        YA-01
B        YA-01
B        YA-01
B        WA-01
B        WA-01
B        WA-01
B        WA-01
B        ZZ-01
B        ZZ-99
B        ZZ-99
B        AA-01

And I wanted to combine categories of two within a group (so within A I want to combine groups of two categories and within B I want to combine two categories and so on). Again, I want to preserve the order of the rows in the original dataframe.
So I want to get
Group    Category   New_Category
A        ZA-01      1
A        ZA-01      1
A        ZA-01      1
A        ZA-01      1
A        XA-01      1
A        XA-01      1
A        XA-01      1
A        XA-01      1
A        ZZ-12      2
A        ZX-11      2
B        YA-01      3
B        YA-01      3
B        YA-01      3
B        YA-01      3
B        WA-01      3
B        WA-01      3
B        WA-01      3
B        WA-01      3
B        ZZ-01      4
B        ZZ-99      4
B        ZZ-99      4
B        AA-01      5

A: For revised question:
You don't need groupby. Just use factorize with tuple of Group and Category
df['New_Category']= (pd.factorize(list(zip(df.Group, df.Category)))[0] // 2) + 1

Out[272]:
   Group Category  New_Category
0      A    ZA-01             1
1      A    ZA-01             1
2      A    ZA-01             1
3      A    ZA-01             1
4      A    XA-01             1
5      A    XA-01             1
6      A    XA-01             1
7      A    XA-01             1
8      A    ZZ-12             2
9      A    ZX-11             2
10     B    YA-01             3
11     B    YA-01             3
12     B    YA-01             3
13     B    YA-01             3
14     B    WA-01             3
15     B    WA-01             3
16     B    WA-01             3
17     B    WA-01             3
18     B    ZZ-01             4
19     B    ZZ-99             4
20     B    ZZ-99             4
21     B    AA-01             5

Original:
Use pd.factorize and floor div 2
df['new_category'] = pd.factorize(df.Category)[0] // 2

Out[154]:
   Category  new_category
0     ZA-01             0
1     ZA-01             0
2     ZA-01             0
3     ZA-01             0
4     XA-01             0
5     XA-01             0
6     XA-01             0
7     XA-01             0
8     YA-01             1
9     YA-01             1
10    YA-01             1
11    YA-01             1
12    WA-01             1
13    WA-01             1
14    WA-01             1
15    WA-01             1

After having new_category above, if you want to map to your custom categories, just do these additional steps
cats = np.array(['A', 'B'])
df['new_category'] = cats[df['new_category']]

Out[163]:
   Category new_category
0     ZA-01            A
1     ZA-01            A
2     ZA-01            A
3     ZA-01            A
4     XA-01            A
5     XA-01            A
6     XA-01            A
7     XA-01            A
8     YA-01            B
9     YA-01            B
10    YA-01            B
11    YA-01            B
12    WA-01            B
13    WA-01            B
14    WA-01            B
15    WA-01            B

Add @piRSquare method of create alphabet categories
from string import ascii_uppercase
from itertools import product
import numpy as np

letters = [*ascii_uppercase]
leading = [''] + letters
cats = np.array([*map(''.join, product(*[leading] * 3, letters))])

Or
from string import ascii_uppercase
from itertools import product
cats = np.array([*map(''.join, product(['', *ascii_uppercase], ascii_uppercase))])
cats[df.Category.factorize()[0] // 2]

Out[13]:
array(['A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B',
       'B', 'B', 'B'], dtype='<U2')

A: You can do as you said with map:
cats = df.Category.unique()

# define new categories
# replace np.arange(len(cats)) with your category names
# e.g ['A','B']
new_cats = np.repeat(np.arange(len(cats)), 2)[:len(cats)]

s = pd.Series(new_cats, index=cats)
df['New_Cat'] = df['Category'].map(s)

Output:
   Category  New_Cat
0     ZA-01        0
1     ZA-01        0
2     ZA-01        0
3     ZA-01        0
4     XA-01        0
5     XA-01        0
6     XA-01        0
7     XA-01        0
8     YA-01        1
9     YA-01        1
10    YA-01        1
11    YA-01        1
12    WA-01        1
13    WA-01        1
14    WA-01        1
15    WA-01        1

Detail: s is
ZA-01    0
XA-01    0
YA-01    1
WA-01    1
dtype: int32


text:
Q: How to conditionally apply where clause in Rails? I have the code:
ApplyJob.includes(:job, cv_attachment: :blob)
        .joins('INNER JOIN cities_jobs ON cities_jobs.job_id = apply_jobs.job_id')
        .joins('INNER JOIN industries_jobs ON industries_jobs.job_id = apply_jobs.job_id')
               .where('email = ? AND cities_jobs.city_id = ?
                       AND industries_jobs.industry_id = ?
                       AND apply_jobs.created_at BETWEEN ? AND ?',
                       applied_params[:email],
                       applied_params[:city],
                       applied_params[:industry],
                       d_start,
                       d_end)

def applied_params
  params.permit(:email, :city, :industry, :date_start, :date_end)
end

how to ignore clause inside where when corresponding params are blank. If using if else or case when the code will be very long
Example: if applied_params[:email] is not present, email = ? will not be mentioned.

A: You can conditionally chain where clauses based on provided input:
query = ApplyJob.includes(:job, cv_attachment: :blob)
                .joins('INNER JOIN cities_jobs ON cities_jobs.job_id = apply_jobs.job_id')
                .joins('INNER JOIN industries_jobs ON industries_jobs.job_id = apply_jobs.job_id')

query = query.where(email: applied_params[:email]) if applied_params[:email].present?
query = query.where(cities_jobs: { city_id: applied_params[:city] }) if applied_params[:city].present?

and so on.
Chaining where multiple times is not going to fire sql queries immediately, instead constructing a single query.
Another approach would be to initiate a mapping like:
mapping = {
  ?: { email: applied_params[:email] },
  cities_jobs: { city_id: applied_params[:city] },
  industries_jobs: { industry_id: applied_params[:industry] },
  apply_jobs: { created_at: (d_start..d_end if d_start && d_end) }
}.filter { |_, value| value.compact.presence }

and then pass it to where method:
query.where(mapping)


text:
Q: React Apollo - How to make multiple queries in a single pollInterval I have multiple queries that I want to fetch after each 10 seconds, I can fetch the queries like this:
compose(
  graphql(QUERY_1, {
    options: {
      pollInterval: 10000
    }
  }),
  graphql(QUERY_2, {
    options: {
      pollInterval: 10000
    }
  }),
  ....
)

but that would make more than one intervals which I don't want. Is there any way in react-apollo to make multiple queries under a single interval. For example something like this:
compose(
  graphql([QUERY_1, QUERY_2],
    options: { pollInterval: 10000 }
  ),
  ...
)

A: The way I did it for now is combine multiple queries in one e.g.
const QUERIES_GROUP = gql`
  {
    QUERY_1 ...,
    QUERY_2 ...
  }
`
compose(
  graphql(QUERIES_GROUP, {
    options: { pollInterval: 10000 }
  })
)

The disadvantage of using above approach is that we cannot reuse query QUERY_1 or QUERY_2 in some other component
Another option is to use batching https://www.apollographql.com/docs/link/links/batch-http.html


text:
Q: Fluent API issue - Multiplicity is not valid in Role Im trying to figure out this issue; (Ef6)
I have three tables, 'Goal' , 'GoalType', 'GoalBudget'. I have a one to one between Goal and GoalType which works fine, but when I do the same with GoalBudget which does not work - when I 'update-database' I get this error:
Goal_GoalBudget_Source: : Multiplicity is not valid in Role 'Goal_GoalBudget_Source' in relationship 'Goal_GoalBudget'. Because the Dependent Role refers to the key properties, the upper bound of the multiplicity of the Dependent Role must be '1'.
What is the issue -
many Thanks
public class Goal
{
    public int GoalId {get;set;}
    public string Name { get; set; }
    public string Description { get; set; }
    public decimal TargetAmount { get; set; }

    public int GoalBudgetId { get; set; }
    public int GoalTypeId { get; set; }
    // Navigaiton Properties
    public virtual GoalType GoalType { get; set; }
    public virtual GoalBudget GoalBudget{ get; set; }
}

public class GoalBudget
{
    public GoalBudget()
    {
        Goals = new List<Goal>();
    }
    public int GoalBudgetId { get; set; }
    public DateTime Created { get; set; }
    // Navigation Property
    public ICollection<Goal> Goals { get; set; }
}

public class GoalType
{
    public GoalType()
    {
        Goals = new List<Goal>();
    }
    public int GoalTypeId {get;set;}
    public string Name { get; set; }
    // Navigation Property
    public ICollection<Goal> Goals { get; set; }
}

The Config is :
protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        // GOAL
        modelBuilder.Entity<Goal>().Property(n => n.GoalId).IsRequired();
        modelBuilder.Entity<Goal>().Property(n => n.GoalId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
        modelBuilder.Entity<Goal>().Property(n => n.Name).IsRequired();
        modelBuilder.Entity<Goal>().Property(n => n.Name).HasMaxLength(50);
        modelBuilder.Entity<Goal>().Property(n => n.TargetAmount).IsRequired();

        //-
        modelBuilder.Entity<Goal>().HasKey(k => k.GoalId);
        modelBuilder.Entity<Goal>().HasRequired(o => o.GoalType).WithMany(o => o.Goals).HasForeignKey(k => k.GoalTypeId) ;
        modelBuilder.Entity<Goal>().HasRequired(o => o.GoalBudget).WithMany(o => o.Goals).HasForeignKey(k => k.GoalId);

        // GOAL TYPE
        modelBuilder.Entity<GoalType>().HasKey(k => k.GoalTypeId);
        // GOAL BUDGET
        modelBuilder.Entity<GoalBudget>().Property(n => n.GoalBudgetId).IsRequired();
        modelBuilder.Entity<GoalBudget>().Property(n => n.GoalBudgetId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
        modelBuilder.Entity<GoalBudget>().Property(n => n.Created).IsRequired();
        modelBuilder.Entity<GoalBudget>().HasKey(k => k.GoalBudgetId);

A: You have an error in your FluentAPI mapping:
modelBuilder.Entity<Goal>()
    .HasRequired(o => o.GoalBudget)
    .WithMany(o => o.Goals)
    .HasForeignKey(k => k.GoalId);

Your HasForeignKey method is configuring the wrong foreign key column (GoalId), it should be GoalBudgetId instead.
Try:
modelBuilder.Entity<Goal>()
    .HasRequired(o => o.GoalBudget)
    .WithMany(o => o.Goals)
    .HasForeignKey(k => k.GoalBudgetId);


text:
Q: Why inline cache is faster than dictionary mode in v8 I have read https://mrale.ph/blog/2012/06/03/explaining-js-vms-in-js-inline-caches.html. When accessing the property of object, inline-cache will need a hash of property name to lookup for the cached stub to get the offset. And in dictionary mode, look up will only need a hash too. Why inline cache is 6x faster than dictionary mode?

A: I don't think that's quite the interpretation of it.
The entire point of the inline cache is to "fast-track" the retrieval process for specific properties. The way he proposes this (and the way that it's done in V8) is to create hidden classes behind the scenes for our objects.
So a basic object like this
const obj = {
    foo: 1
}

will be backed by a hidden class, something like:
class A {
    foo: number
}

If you create a new object, obj2 with the same format, so that
const obj2 = {
    foo: 5
}

it'll be backed by the same A class.
If we add a new property to obj2:
const obj2 = {
    foo: 5,
    bar: 10
}

then it'll get backed by a different class - either to a class that already exists (if we have one of the same format), or to a new one:
class B {
    foo: number,
    bar: number
}

There's a lot more to it, but that's the gist of it.
This means that whenever you do something like obj.foo in your code, the compiler can fast-track that retrieval using inline caching - it knows that the property foo exists, and that it's of type number.
If you're doing a hash map lookup (i.e. pure Object properties) where your property might not exist (e.g. obj["baz"]), then it can no longer fast track that process, and has to check to see if baz exists, then gets it etc
For the majority of code, even the slower method is "fast enough" - unless you're doing like he's doing and running a 100k loop.
In short, inline caching is faster because it can skip a load of internal checks and casting etc - it just returns the variable
More info on this in V8: https://richardartoul.github.io/jekyll/update/2015/04/26/hidden-classes.html
https://engineering.linecorp.com/en/blog/v8-hidden-class/

A: The "inline cache" approach has two stages: configuring the inline cache and executing the inline cache.
You're right that configuring (a.k.a. "patching") the inline cache needs to hash the property key. In fact, this is typically significantly slower than a plain and simple dictionary-based approach. But it only needs to be done very infrequently (in the example program, only once per IC)!
The configured inline cache then gets executed repeatedly (in the example, 100,000 times), and every time all it does is executing the following function:
function KeyedLoadFastProperty(t, k, ic) {
  if (t.klass !== klass) {
    // Expected klass does not match. Can't use cached index.
    // Fall through to the runtime system.
    return NAMED_LOAD_MISS(t, k, ic);
  }
  return t.properties[index];
}

which, as you can see, does not need to hash anything (assuming t.klass is the same as what it was before, when the IC was patched); it does a simple index-based load from an array, which is super fast.


text:
Q: Finding x with a Python-script in a difficult equation where x is only variable I have some difficult equations where x is the only variable. For example this one:
atan(12/x)-atan(SQRT(7x)/31)=atan((3x+942+sqrt(2x^2+2))/(4+sqrt(5+x^2)))
In software like WolframAlpha I can paste it in at it will find the x for me easily.

The only idea I have now is to do some sort of brute force on each side with small iterations until Left side = Right side. I have no idea how to elegantly solve this equation using python.
Does anyone where I should start?
(Disclaimer: I have written some basic python scripts and studied some math, but my math skills and python skills are probably in the bottom 1% in the Stack Overflow-community.)
Best regards,

A: This is a difficult equation, both symbolically and numerically. Mathematica has very advanced algorithms. nsolve from sympy does not find the root without help, but you can do the following:
from sympy import *
x = symbols('x')
e0 = atan(12/x)-atan(sqrt(7*x)/31)-atan((3*x+942+sqrt(2*x**2+2))/(4+sqrt(5+x**2)))
nsolve(e0,x,0)
# gives ZeroDivisionError
nsolve(e0,x,0.001)
# gives 0.00523293635181032 - 1.6278511388129e-27*I
nsolve(e0,x,0.005)
# gives 0.00523293635181032

So you have to guess the range of the zero rather closely.
To make the search for the root easier, you can get rid of atan by taking the tan of both sides and use tan(a-b) = (tan(a) - tan(b)) / (1 + tan(a)tan(b)) :
t1 = 12 / x
t2 = sqrt(7*x) / 31
t3 = (3*x+942+sqrt(2*x**2+2)) / (4+sqrt(5+x**2))
# atan(t1) - atan(t2) = atan(t3) is equivalent to e1 = 0:
# (note: tan(atan(t1) - atan(t2)) = (t1-t2)/(1+t1*t2) )
e1 = simplify((t1-t2)/(1+t1*t2) - t3)
# gives (sqrt(x)*(31*sqrt(x) + 12*sqrt(7))*(-3*x - sqrt(2*x**2 + 2) - 942) + ...)/(sqrt(x)*...)

Now we have to give nsolve one more hint to make the root search easier, namely to take only the numerator of the expression:
e1_num = e1.as_numer_denom()[0]
# gives (sqrt(x)*(31*sqrt(x) + 12*sqrt(7))*(-3*x - sqrt(2*x**2 + 2) - 942) + (-sqrt(7)*x**(3/2) + 372)*(sqrt(x**2 + 5) + 4)
nsolve(e1_num,x,0)
# gives 0.00523293635181032


text:
Q: CSS: Stretch content div to footer div and align horizontally I'm trying to take a div that sits underneath a menu, stretch it until it reaches the footer (in case there's not enough content), and center it. I can stretch it using absolute positioning, but it will not center; and I can center it, but it won't stretch. The code looks something like this:
HTML

CSS
html, body {
    height: 100%;
    margin: 0;
    padding: 0;
}

#container {
    min-height: 100%;
    position: relative;
}

#header {
    background: #111;
    width: 500px;
    height: 125px;
    margin: auto;
}

#content {
    width: 500px;
    height: 100%;
    background: #666;
}

#footer {
    position: absolute;
    bottom: 0;
    background: #111;
    width: 100%;
}

Here's an image I created in Inkscape as an example: http://www.tiikoni.com/tis/view/?id=46baeba
I can find answers on how to stretch the content div to the bottom, but that's it. I don't want to use JavaScript/JQuery unless I absolutely need to.

A: If you're set on doing things the way you are (with the footer set to position: absolute; bottom: 0;) you can do:
#footer {
    position: absolute;
    bottom: 0;
    background: #111;
    width: 100%;
    height: 50px; // or whatever height you want
}
#content {
    width: 500px;
    background: #666;
    margin: 0px auto;
    position: absolute;
    top: 125px; // same height as header
    bottom: 50px; // same height as footer
    left: 0;
    right: 0;
    margin: auto;
}

JSFiddle: http://jsfiddle.net/g2y9Y/
But I think for what you're trying to achieve, setting absolute positioning is probably a bad idea. Are you sure your content will never be taller than 100% of the user's browser height? Why not simply set a min-height on the content? Something like this: http://jsfiddle.net/g2y9Y/1/

A: YOu can try this fiddle . I found it here - CSS Layout Help - Stretch div to bottom of page
#wrap { min-height: 100%;background-color:gray;}
#main {
    overflow: auto;
    padding-bottom: 53px; /* must be same height as the footer */
    background-color: red;
    height: 90%
}
#footer {
    position: relative;
    margin-top: -53px; /* negative value of footer height */
    height: 33px;
    line-height: 33px;
    border-bottom:20px solid #fff;
    text-align: center;
    background-color:blue;
}


text:
Q: Saving multiple linear regression models in a loop I am trying a multi linear regression with 4 independent parameters which are compared against these parameters for a class with label 0 to linearly fit the model.
from sklearn import linear_model
from pandas import DataFrame

covariates = DataFrame({'Param1':P1, 'Param2':P2, 'Param3':P3, 'Param4':P4}).iloc[cov_idx, :]
covariates = covariates.to_numpy(dtype=np.float32)

covCN = covariates[labels['Group'] == 0] # only controls as reference group to estimate effect of covariates
lm = linear_model.LinearRegression()

for k in range(images.shape[3]):
  for j in range(images.shape[2]):
    for i in range(images.shape[1]):
      if any(images[:, i, j, k, 0] != 0):
        tmpdat = images[labels['Group'] == 0, i, j, k, 0]
        lm.fit(covCN, tmpdat)
        pred = lm.predict(covariates)
        images[:, i, j, k, 0] = images[:, i, j, k, 0] - pred

I want to save the models of linear regression to predict on a different data set having similar parameters.
When I tried the below code to save the model, I figured that only one model is getting saved.
import pickle
with open("model","wb") as f:
  pickle.dump(lm,f)
with open("model","rb") as f:
  model = pickle.load(f)

covariates = DataFrame({'Param1':A1, 'Param2':A2, 'Param3':A3, 'Param4':A4}).iloc[cov_idx, :]
covariates = covariates.to_numpy(dtype=np.float32)

for k in range(images.shape[3]):
  for j in range(images.shape[2]):
    for i in range(images.shape[1]):
      if any(images[:, i, j, k, 0] != 0):
        pred = model.predict(covariates)
        images[:, i, j, k, 0] = images[:, i, j, k, 0] - pred

How do I save all the linear regression models and use it to predict on the different dataset?


text:
Q: Leading digits of Fibonacci sequence There is a standard problem to show that the distribution of leading digits of $2^n$ is that the digit $k$ occurs with the frequency $\log_{10}(k+1)-\log_{10}(k)$. (This easily generalises to other bases --- though base 2 is rather pointless!)
Since Fibonacci is also ``exponential except for an error term''. Is this true for that as well --- or does the error term make it fail?

A: Yes, this is true. The sequence of Fibonacci numbers is known to satisfy Benford's Law.
See the wikipedia page of Benford's Law for details (in particular see Distributions that satisfy Benford's law exactly).
More specifically, L. C. Washington showed in Benford's Law for Fibonacci and Lucas numbers,
Fib. Quaterly 1981 that both Fibonacci and Lucas numbers satisfy the extended Benford's Law (that is arbitrary base as mentioned in the question).
The key part of the proof is to show that $n \log \phi$ is uniformly distributed modulo $1$ where $\phi$ is the Golden Ratio (the base of the logarithm being the one for which the law should be established). This is achieved using Weyl's equidistribution theorem.


text:
Q: How to properly setup using .scss in ASP.NET MVC 4.6.1 project in purpose of implementing a new theme from Metronic? so I am trying to figure out a way how to properly include and use .scss files from my new Metronic theme into my existing ASP.NET 4.6.1 project.
The problem is there are hundreds of .scss file and I tried using Web Compiler but it breaks on some files. Maybe the best way is trough the bundles but I need to figure out how to "work" with .scss files.
I appriciate the help!


text:
Q: Where do Excel add in manifest files install to on Mac? I have an Excel add in created using the Yeoman generator and I'm trying to find where add in manifests are installed to on the Mac file system.
I know when you sideload the add in the manifest is placed in:
/Users/<username>/Library/Containers/com.microsoft.Excel/Data/Documents/wef
But this only allows the add in to be added as a developer add in every time you open Excel.
Is there a place where I can place the add in manifest to have it stay installed in Excel not as a developer add in?
Is this the correct way to distribute an add in to users without having the add in on the AppSource store or is there another way to distribute Excel add ins via .exe/.dmgs/.pkgs?
Any information about this process would be greatly appreciated.

A: There are several ways to deploy the add-in manifest. The details are in this section of the official docs: Publish.


text:
Q: Receive PubNub subscribe message and insert MongoDB database I'm trying to develop a small system with a easy architecture. In this case I have one simulator that generate random data and publish this data on PubNub. Otherwise, i have too two subscribers: one web based dashboard and MongoDB database.
At this moment, I developed the simulator and the dashboard. The next stage is receive the PubNub subscribe data and insert into MongoDB.
My issue is how I can do this remotely? What is the framework that I should use? I saw many tutorials that start MongoDB DB by terminal on local machine, remotely how this works?
Someone can give me a full explication?
Regards,
Note: I use PubNub JS SDK, my dashboard was developed in HTML, CSS and JS


text:
Q: How to find number of ways of permuting a string satisfying the below conditions? I am given a string,let say- "abcd".
Now I have to find all the strings that can be generated by permuting its character such that-

*

*There are exactly four mismatches in the generated strings and,

*The mismatches exists in pair, for e.g-

The string - "abcd" has three such permutations-
"badc","cdab","dcba".
Explanation-
Let us consider "abcd" and "badc". Now there are exactly four mismatch with , i.e- (a,b),(b,a),(c,d),(d,c) and these mismatches exists in pair.
Note that "abcde" has fifteen such permutations-
acbed,adebc,aedcb,baced,badce,baedc,cbaed,cdabe,ceadb,dbeac,dcbae,decab,ebdca,ecbda,edcba
Where I am failing?-
I am just finding the strings manually, but this becomes really time-consuming for strings of large length. Hence,I need a efficient solution

A: Hint:  Let the string have length $n$.  You choose two places for the first pair to swap, $n \choose 2$ ways. Then you choose two places for the second pair in (how many?) ways. But you could have chosen the pairs in the other order....

A: Break it up via multiplication principle:
$$abcdefgh$$

*

*Step 1: Pick which four of the $n$ letters are going to be swapped  (for example $bdeg$, pictured below)

$$\color{grey}{a}\color{red}{b}\color{grey}{c}\color{red}{de}\color{grey}{f}\color{red}{g}\color{grey}{h}$$
How many ways can this step be done in for a string of $n$ letters?

 $\binom{n}{4} = \frac{n!}{4!(n-4)!}$

*

*Step 2: Color the smallest appearing chosen letter blue.  Pick one more of the three remaining red chosen letters to color blue.  (for example $g$ pictured below)

$$\color{grey}{a}\color{blue}{b}\color{grey}{c}\color{red}{de}\color{grey}{f}\color{blue}{g}\color{grey}{h}$$
How many ways can this step be done?

 $3$ ways

Now, swap the blue letters, and swap the red letters.
$$agcedfbh$$
The pictured example has the following two mismatch pairs: $(b,g)$ and $(d,e)$.
It should be clear that every sequence of choices from the above steps will generate exactly a permutation of the desired type uniquely and that all permutations are generated by exactly one sequence of choices.  Multiplication principle then says that the number of such permutations is the product of the number of available choices at each step.

Beginnings of a generalization:
Let the string to be permuted be $\underbrace{aa\dots a}_{\alpha_a~\text{copies}} \underbrace{bb\dots b}_{\alpha_b~\text{copies}} cc\dots c\dots \underbrace{kk\dots k}_{\alpha_k~\text{copies}}$ where there are $k$ distinct letters appearing, and $\alpha_a+\alpha_b+\dots+\alpha_k = n$ letters total (counting repeated letters).
Let $\chi_{a,0}$ denote the event that two $a$'s were swapped between themselves and no other $a$'s were swapped.  Let $\chi_{a,1}$ denote the event that two $a$'s were swapped between themselves and a third $a$ was swapped with a different letter.  Let $\chi_{a,2}$ denote the event that four $a$'s were swapped amongst eachother.  Define similar events for the other letters.
Temporarily assume every letter distinct (each copy of a particular letter, assume it has a specific subscript number for example)
$$a_1b_1b_2b_3b_4c_1c_2c_3d_1e_1f_1f_2$$
Count how many permutations exist with the desired properties as above temporarily ignoring the fact that some letters are intended to be identical.

 $3\binom{n}{4}$ ways

Remove those permutations which swap at least one pair of identical letters.  To count how many of these there are, we try to count $|\chi_{a,0}\cup \chi_{a,1}\cup \chi_{a,2}\cup \chi_{b,0}\cup \dots\cup \chi_{k,2}|$.
By inclusion exclusion, this is $\sum\limits_{x\in\{a,b,\dots,k\}}\sum\limits_{i=0}^2|\chi_{x,i}| -\sum\limits_{\{x,y\}\subset\{a,b,\dots,k\},~x< y}|\chi_{x,0}\cap \chi_{y,0}|$
To count $|\chi_{x,0}|$, pick the two offending letter $x$'s, and then pick the other two non-$x$'s.  $\binom{\alpha_x}{2}\binom{n-\alpha_x}{2}$ such permutations.
To count $|\chi_{x,1}|$, pick the three offending $x$'s, pick one of them to be paired with a non-$x$, and pick the non $x$ to be paired with.  $\binom{\alpha_x}{3}\cdot 3\cdot (n-\alpha_x)$ such permutations.
To count $|\chi_{x,2}|$, pick the four offending $x$'s and then pick how they were paired.  $3\binom{\alpha_x}{4}$ such permutations.
Notice, that in expanding the union for inclusion-exclusion, the only surviving intersections are of the form $\chi_{x,0}\cap \chi_{y,0}$ with $x\neq y$ since any other intersection would imply that there were five or more selected letters.
To count $|\chi_{x,0}\cap \chi_{y,0}|$, select the two offending $x$'s and select the two offending $y$'s.  $\binom{\alpha_x}{2}\binom{\alpha_y}{2}$ such permutations.
Removing these from the original total, we have then a final total of:
$$3\binom{n}{4} - \sum\limits_{x\in \{a,b,\dots,k\}}\left(\binom{\alpha_x}{2}\binom{n-\alpha_x}{2}+\binom{\alpha_x}{3}\cdot 3\cdot (n-\alpha_x)+3\binom{\alpha_x}{4}\right) + \sum\limits_{\{x,y\}\subset\{a,b,\dots,k\},~x<y}\binom{\alpha_x}{2}\binom{\alpha_y}{2}$$
For a specific example, such as $abbbbcccdeff$, we would have $3\binom{12}{4} - \underbrace{\binom{4}{2}\binom{8}{2}}_{\chi_{b,0}} - \underbrace{\binom{4}{3}3\cdot 8}_{\chi_{b,1}} - \underbrace{3}_{\chi_{b,2}} - \underbrace{\binom{3}{2}}_{\chi_{c,0}}-\underbrace{\binom{3}{3}\cdot 3\cdot 9}_{\chi_{c,1}}-\underbrace{\binom{2}{2}\binom{10}{2}}_{\chi_{f,0}}+\underbrace{\binom{4}{2}\binom{3}{2}}_{\chi_{b,0}\cap\chi_{c,0}}+\underbrace{\binom{4}{2}\binom{2}{2}}_{\chi_{b,0}\cap\chi_{f,0}}+\underbrace{\binom{3}{2}\binom{2}{2}}_{\chi_{c,0}\cap\chi_{f,0}} = 1170$
For a smaller example which should be able to be brute forced, $abbde$ would have $3\binom{5}{4} - \binom{2}{2}\binom{3}{2} = 15-3=12$.  Specifically, they are $adebb,aedbb,babed,badbe,baedb,bbaed,bdabe,beadb,dbeab,debab,ebdba,edbba$ (copied from your earlier list, replaced $c$'s with $b$'s, and deleted the three offending permutations)


text:
Q: Select and update specific mysql data in single query I am trying to first select data from a row which contains certain characters. I would then like to update and append new data into another row of those items that were selected. This is my current solution I came up with when trying to combine the two tasks into a single query.
SELECT *
FROM `parts`UPDATE  `parts` SET
`keywords` = CONCAT(`keywords` ,  'Phillips' )
WHERE INSTR(`name`, 'PHI') > 0

A: You can make a SELECT as part of an UPDATE statement, but you can't make an UPDATE part of a SELECT statement. However, based on your example you don't need to, instead you can just do the following:
UPDATE parts
SET keywords = CONCAT(keywords,'Phillips')
WHERE name LIKE '%Phi%'

If you want to retrieve the results after you've updated them just execute the following afterwards:
SELECT *
FROM parts
WHERE name LIKE '%Phi%'


text:
Q: Rxjs: Repeat an Ajax Call Every X Seconds, but Wait for the Last One to Complete I would like to query an API every x seconds when subscribing to an autorefresher Observable, making sure that the last request has completed before sending another one.
let autoRefresher = new Observable().exhaustMap(() => Observable.defer(() => {
    return someService.returningAPromise();
}).timeout(refreshIntervalInMs).repeat());

Is there a better way to do this? How could I update the refresh interval without creating a new observable each time?

A: I'd do it like this:
import {Observable} from 'rxjs';

function doRequest() {
  if (Math.random() < 0.25) {
    return Observable.of('HTTP Response').delay(3000);
  } else {
    return Observable.of('HTTP Response');
  }
}

let autoRefresher = Observable.timer(0, 1000)
  .exhaustMap(doRequest)
  .subscribe(response => {
    console.log(response);
  });

See live demo: http://plnkr.co/edit/7HAib10r6Vdl1x2U2wFS
This randomly makes 3s delay. Operator timer() periodically emits a value. Then exhaustMap() subscribes to the preceding Observable and ignores all Observables emitted until the current one completes. So timer() is emitting values but these are ignored by exhaust().
Btw, note that I'm using TypeScript.

A: I see this is quite an old issue, I just wanted to bring up maybe a more "stable" solution. The problem with this approach is there might be windows where no request is made since the timer rans at a fixed 1s interval.
For example:
Interval 1s, Request Duration < 1s: Every 1second a request is made, but if the request takes for example 400ms to complete, it will only take 600ms until the next request starts (not 1 second)
Interval 1s, Request Duration 1,5s: Request starts at the beginning, in next interval request is still running so exhaustMap filters it, and in 3rd interval request will run again (500ms after previous request)
In my example the request will always wait 1 second before running again
import { delay, flatMap, repeat, takeUntil } from 'rxjs/operators';
import { of,Subject } from 'rxjs';

function doRequest() {
    if (Math.random() < 0.25) {
        return Observable.of('HTTP Response').delay(3000);
    } else {
        return Observable.of('HTTP Response');
    }
}

const subject: Subject<boolean> = new Subject();
of(null)
    .pipe(
        // can be used to cancel
        takeUntil(subject),
        // does request
        flatMap(doRequest),
        // delays by 1second
        delay(1000),
        // repeat steps above
        repeat(),
    )
    .subscribe(response => {
        console.log(respons);
    });

A: It is important that the takeUntil(..) is the last call in the pipe(). Otherwise the observables might not be cancelled. See https://cartant.medium.com/rxjs-avoiding-takeuntil-leaks-fb5182d047ef


text:
Q: Setting a timeout on Google Calendar API requests? I have written a program in C# using the Google Calendar API via the .NET nuget packages. One of my users is having an issue where the Events.List request seems to be timing-out after 100 seconds (throwing a TaskCanceledException). I had the user test the same request via the Google API explorer (link here) and they got error 503:
503
{
"error": {
  "errors": [
   {
    "domain": "global",
    "reason": "backendError",
    "message": "Backend Error"
   }
  ],
  "code": 503,
  "message": "Backend Error"
}
}

Google seems to recommend exponential backoff in this case, but I am not sure if that will work since this happens every single time the user clicks this particular button. Is there a way to increase the timeout limit for Google Calendar API requests?


text:
Q: Collect SNMP data from on-prem assets and send it to Azure log management I want to collect SNMP data from my on-prem equipment and send it to Azure log management.
To be more precise, I have a Linux virtual machine running in Azure that is to collect SNMP data from my on-prem router and send that data to my Azure log analytics workspace.
Is there any generally recommended and lightweight solution to this?
I was trying to achieve this using collectd, but the problem was connecting it with the OMS agent.
The collectd is to collect the SNMP data and forward it to OMS agent which then sends the data to Azure.
Now, I have a newly installed Debian 11 virtual machine. I have installed OMS agent, and collectd 5.12.0. that I have downloaded from collectd.org.
I cannot run the collectd service. The error I get is that there is a missing plugin called "write_http" which is necessary to connect it with the OMS agent (the .so file is missing, but the configuration regarding the plugin exists within the collectd.conf file).
So far I couldn't find that plugin to download it. Am I missing something?
I was wondering if someone could give me a detailed explanation/solution how to set this up from the beginning?
Thanks in advance!


text:
Q: Apply change to all parent elements that contains a certain child element using jQuery I'm trying to do the same thing as this question but my parent element does not have an id. It does have a class through. Basically I have multiple elements of the same class and some have a child element. If a member of the class example contains the child, apply some CSS change. Is this possible and how would I do it?
For example:

My guess was:
let parents = $(".example");
for (var i=0; i < parents.length; i++) {
    if (parents[i].find('#test').length) {
        parents[i].css("prop", "value")
    }
}

but parents[i].find is not a function

A: So you shouldn't have multiple instances of the same ID in a document. But in your example, you were pretty close. However, if you're already using jQuery it will make your life a bit easier.

jQuery:
(I'm using the $ to denote a jQuery collection you wouldn't need it)
A jQuery collection (in this case created by find) always has a length. So you need to test if it's empty. Also $.each() is basically looping through the collection.

let $parents = $('.example');
$parents.each(
    function(){
      var $el = $(this);
      if($el.find('.findMe').length !=0){
         $el.css('background', 'red');
      }
    }
);

Hello, World!

A: As Heretic Monkey said in the comments above, you can use has from jQuery to do this easily.

$(".example").has(".findMe").css("background-color", "red");

Hello, World!


text:
Q: Is there a way to specify the where T:new() restriction but with internal constructor? I've created a generic class that needs to instantiate its implementation type, so the implementation type has to have an accessible parameter less constructor. Looks like the new() restriction could do the job but its enforcing the implementation type to have a public constructor when I have it internal (but accessible as both are on the same assembly).

*

*Is there a reason to force it to be public rather than "accessible"?

*Is there a way to do what I need?

Thanks in advance.
EDIT: The reason to do this is that I have a class X that must be used through a Singleton. The Singleton class is a generic class and I want to make the class X constructor internal to avoid external users accessing the object in a wrong way (calling the constructor).

A: This is disallowed by the C# language as outlined in section 4.4.3 of the specification Bound and Unbound Types.

If the constraint is the constructor constraint new(), the type A must not be abstract and must have a public parameterless constructor. This is satisfied if one of the following is true.

*

*A is a value type, since all value types have a public default constructor

*A is a type parameter having the cosntructor constraint

*A is a type parameter having the value type constraint

*A is a class that is not abstract and contains an explicitly declared public constuctor with no parameters

*A is not abstract and has a default constructor.

A compiler error if any one of these conditions are not met. If you find yourself having types that are public but only with internal constructors, then most likely they should actually be internal types with public constructors.
I would recommend changing your types accessor to internal and its constructor's to public, and make it parameterless. Your public parameterless constructor could then call through to a non-parameterless private or internal constructor to do any additional initialization work.
internal class C<T> where : T new()
{
    public C() : this(new T()) {
    }

    private C(T t) {
        // Do additional initialization
    }
}

Mind you that pattern is limited, but there's nothing stopping you from using a private method instead.
internal class C<T> where T : new() {
    public C() {
        T t = new T();
        InitializeClass(t);
    }

    private void InitializeClass(T t) {
        throw new NotImplementedException();
    }
}

As per your update, here's a small example of a public singleton patter.
public class Singleton<T> where T : new()
{
    public static Singleton<T> Current {
        get;
        private set;
    }

    internal Singleton() : this(new T()) {
    }

    private Singleton(T t) {
        Current = this;
        // Do whatever you need to with T
    }

    public String Name {
        get;
        set;
    }
}

Usage
// Somewhere in your internal assembly
Singleton<String> singleton = new Singleton<String>();

// In an external assembly
Singleton.Current.Name = "SoMoS";

You don't even need to use constructors in that fashion either, you can just as easily do something simple.
public class Singleton<T> where T : new()
{
    public static Singleton<T> Current {
        get;
        private set;
    }

    internal Singleton() {
        T t = new T();
        // Do stuff with T
    }

    public String Name {
        get;
        set;
    }
}

Generics may not be the way to go if you can't design it to fit your requirements. Generics can only do so much and don't solve every problem. There are things like Factory Pattern, Injection, etc..

A:
Is there a reason to force it to be public rather than "accessible"?

Term accessible is very context sensitive, generics are not, by architecture.
In your specific case internal could be accessible, but generics are made for generic solutions.

Is there a way to do what I need?

Based on first point, no, it's not possible, nor that I'm aware of.

A: Generics are for generic solution, therefore if you use the "new" constraint, your solution have to work with every class which implements a public ctor.
If you want to implement a generic solution for a specific kind of classes you can define an abstract base class which implements a such internal constructor. Implement a generic solution for this abstract base class and use
*
where T : MyBaseClassWithInternalCtor
*
as constraint.


text:
Q: How to dual boot home PC with Linux and Windows 7? I am a pure windows person.  I have only used Macs at work and never had to use linux.  However I want to branch out.
What Linux operating system is the best for somebody that has never used it before and just Windows?
How to set up my machine to dual boot with Linux?
Ideally I would love to be able to choose which one to start up with like I did with Vista and Windows 7.

A: Personally I use Ubuntu and that's quite nice for beginners. I've also heard that Linux Mint is good.
Provided you have already got your hard drive partitioned (or a 2nd hard drive) you should just be able to install Linux from the cd and it will prompt you with where you want to install it (make sure you don't overwrite your windows partitions). It will setup Grub (or something compatible) to prompt you on start up which OS you want to boot.
(If you don't already have windows installed it's generally considered best practise to install windows first as sometimes it can overwrite your Linux boot loader with it's own. I don't know if this has changed with newer versions or not)
It's as easy as that.
If you're new to Linux though, consider trying out a live CD or a VM for a bit first.

A: You can find some detailed instruction on dual-boot between existing OS and Ubuntu here,
like this Jaunty Jackalope / Windows7 Ultimate MultiBoot 'B' page.
(Ubuntu is generally consider quite user-friendly and up-to-date regarding drivers)

A: There are many, many tutorials out there.  Pick the distribution you want and search for installation guides for it.  (K)Ubuntu is the most popular and has the largest community, but the others are good choices, too.
You'll find there are several ways to install Ubuntu.  The installation guide offers a decent overview, but you could also try Wubi (the Windows Ubuntu installer).
You might find some kinks while trying to install one of the distros, so pick a few to try.  I'd recommend Ubuntu/Kubuntu, Fedora Core, or OpenSuSE, in that order.  Ubuntu and Fedora work best with Gnome, a fairly simple desktop environment.  Kubuntu and OpenSuSE work best with KDE, which is a bit flashier.  They also have different selections of applications that come bundled, although you can install any of them.
Dual-booting is extremely common, so it's addressed by nearly every tutorial you'll find.  However, if you can afford it, consider buying another hard drive instead; unconventional advice, but you won't go wrong with it.

A: Ubuntu is probably your best option. Dual booting it should be quite easy. The normal recommended method is to install Windows first, then install Linux. It should pick up on your existing Windows isntall and give you the option of dual booting. Have a look at the guide here


text:
Q: JavaScript: calling function of parent window from child window I am opening a popup window from a page. The process goes like this:
var newwindow = window.open("mydomain.com/a.html", "Testing", 'height=600,width=800');
if (window.focus) { newwindow.focus() }

mydomain.com/a.html opens a popup mydomain.com/b.html
mydomain.com/b.html redirects the user to another site(say payment gateway)
paymentgateway.com/authenticate.html
paymentgateway.com/authenticate.html redirects the user to mydomain.com/success.html
From mydomain.com/success.html I want to execute a function written on mydomain.com/a.html
I have written
window.parent.LaunchFunction();
window.close();

but it's not working. What can be the issue? Is it possible to achieve?

A: I'm offering another way - use the local storage for communication between apps at the same origin (same protocol+domain+port).
You can add listener, that is fired when somebody change any property in localstorage.
First instance is listening
window.addEventListener('storage', onStorageChange, false);

function onStorageChange (e) {
  if (e.key === 'messageText') {
    var messageText = localStorage.getItem('messageText');
    if (messageText) { // Prevent to call when fired by `removeItem()` below
      console.log('New message from another instance has come:', messageText);
      localStorage.removeItem('messageText'); // this will fires the `onStorageChange` again.
    }
  }
}

Second instance is sending the messages
localStorage.setItem('messageText', 'Hello from second app instance');


text:
Q: Google App Engine Python -> configure yaml and websockets I`m beginning programmist with google API working in python.
I have pycharm 3.4.1 version.
I 'm trying to make a project (backend) of game bomberman. It is like i have to use content of already written game in javascript. I have my project folder and there i have this content: ![link at the bottom][1]

*

*I don't understand how exactly i should modify my yaml file to use content of web folder. I need handlers to java script, css and etc. using content of web. If someone could show me example of javascript import then I think I would be able to do analogically the same with others handlers.

*What's more. I ve been searching information about implementation websockets in python using google API but I just cant find anything useful or I just don't understand the info. I would appreciate if somebody could show me how to implement websockets and add short explanation. Please be easygoing on me because it's my first approach to google API and i don't know much about it.
Thanks for help and sorry for mistakes if I did any in the text:)
[1]http://i.stack.imgur.com/aNJCz.png

A: 1 - To handle static files in your App Engine instance, you can add something similar to the following in your app.yaml file:
handlers:
- url: /css
  static_dir: static/css

- url: /js
  static_dir: static/js

Just place your files in the static/css or static/js directories in your project.  This allows you to access the css and javascript files from the /css and /js paths on your site.  An example js import in your html file would be:
<script src="/js/your-file.js"></script>

More options for configuring your static files is in the App Engine docs at:  https://cloud.google.com/appengine/docs/python/config/appconfig
2 - App Engine has the Channel Python API available.  You can find more info on that at;
https://cloud.google.com/appengine/docs/python/channel/
However, depending on your needs, some have indicated this is too slow for some situations.  You can also create a Compute Engine instance and run Node.js with socket.io for real-time communication between users.  This is a little more involved than the basic App Engine instance but you can see that environment layout in this real-time game example:
https://cloud.google.com/appengine/docs/python/channel/


text:
Q: NTh square free semi prime I am trying to find the nth( n <= 2000000) square free semi prime.  I have the following code to do so.
 int k = 0;
for(int i = 0; i <= 1000; i++)
{
    for(int j = i +1 ; j <= 2500; j++ )
    {
        semiprimes[k++] = (primes[i]*primes[j]);
    }
}
 sort(semiprimes,semiprimes+k);

primes[] is a list of primes.
My problem is, i get different values for n = 2000000, with different limits on the for loops. Could someone tell a way to correctly calculate these limits?
Thanks in advance..

A: You want to calculate the nth first semi-prime square-free numbers. "first" means that you have to generate all of them under a certain value. Your method consist of generating a lot of those numbers, sort them and extract the nth first values.
This can be a good approach but you must have all the numbers generated. Having two different limits in your nested loops is a good way to miss some of them (in your example, you are not calculating primes[1001]*primes[1002] which should be in semiprimes).
To avoid this problem, you have to compute all the semi-prime numbers in a square, say [1,L]*[1,L], where L is your limit for both loops.
To determine L, all you need is it to count.
Let N be the number of semi-prime square-free numbers under primes[L-1]*primes[L-1].
N = (L * L - L) / 2
L*L is the total number of pairwise multiplications. L is the number of squares. This has two be divided by two to get the right number (because primes[i]*primes[j] = primes[j]*primes[i]).
You want to pick L such that n<=N. So for n = 2000000 :
    int L = 2001, k = 0;
    for(int i = 0; i < L; i++)
    {
        for(int j = i+1 ; j < L; j++ )
        {
            semiprimes[k++] = (primes[i]*primes[j]);
        }
    }
    sort(semiprimes,semiprimes+k);

A: I don't believe an approach that works by computing all semiprimes inside a box will work in any reasonable amount of time.  Say we graph the factors (p,q) of the first 2 million semiprimes.  To make the graph more symmetric, let's plot a point for both (p,q) and (q,p).  The graph does not form a nice rectangular region, but instead looks more like the hyperbola y=1/x.  This hyperbola stretches out quite far, and iterating over the entire rectangle containing these will be a lot of wasted computation.
You may want to consider first solving the problem "how many semiprimes are there below N?" and then using a binary search.  Each query can be done in about sqrt(N) steps (hint: binary search strikes again).  You will need a fairly large table of primes, certainly at least up to 1 million, probably more.  Although this can be trimmed down by an arbitrarily large constant factor with some precomputation.


text:
Q: About Channels: list Greeting everyone. I was wondering why some channels don't have a items[] while others do, based on the forUsername parameter. Is it something with the channel itself? Thanks in advance.
Was expecting the Object to have a items[], along with the etag, kind etc.

A: It is related to the channel itself.
Example:

If you want to check the channel markiplier, for search this channel
using the channels.list endpoint, you have to use the value
markiplierGAME.

URL of the request:
https://developers.google.com/youtube/v3/docs/channels/list?hl=es&apix_params={"part":["id,snippet"],"forUsername":"markiplierGAME","maxResults":50}

Try-it here
Result:
{
  "kind": "youtube#channelListResponse",
  "etag": "JzsG_zawoWkLOCBSPYcVSSSLTYg",
  "pageInfo": {
    "totalResults": 1,
    "resultsPerPage": 50
  },
  "items": [
    {
      "kind": "youtube#channel",
      "etag": "vre8w7LGy9EkWyA1AHthYN6UXbw",
      "id": "UC7_YxT-KID8kRbqZo7MyscQ",
      "snippet": {
        "title": "Markiplier",
        "description": "Hi, I'm Markiplier. I make videos. \n\nFrom quality content to meme-able garbage, from scary games to full-on interactive movies you'll find it all. You will, actually. I have over 5000 videos so I'm sure there's something you'd like. \n\nMaybe you like horror games, or funny games, or comedy sketches, or animations, or compilations, or reactions, or reviews, or challenges, or cryptic lore, or mind-crippling ennui, or stuff-that-is-guaranteed-to-probably-make-you-cry? Whatever you're into I'm sure there's something for you down in the briny deep of my video page. So why not dive in?\n\nOr don't. Life is yours to choose after all.\n",
        "customUrl": "@markiplier",
        "publishedAt": "2012-05-26T20:30:52Z",
        "thumbnails": {
          "default": {
            "url": "https://yt3.ggpht.com/ytc/AL5GRJVVORzLF5qyUfe9bpQffFSRsNB2OURZrS5237Lrpw=s88-c-k-c0x00ffffff-no-rj",
            "width": 88,
            "height": 88
          },
          "medium": {
            "url": "https://yt3.ggpht.com/ytc/AL5GRJVVORzLF5qyUfe9bpQffFSRsNB2OURZrS5237Lrpw=s240-c-k-c0x00ffffff-no-rj",
            "width": 240,
            "height": 240
          },
          "high": {
            "url": "https://yt3.ggpht.com/ytc/AL5GRJVVORzLF5qyUfe9bpQffFSRsNB2OURZrS5237Lrpw=s800-c-k-c0x00ffffff-no-rj",
            "width": 800,
            "height": 800
          }
        },
        "localized": {
          "title": "Markiplier",
          "description": "Hi, I'm Markiplier. I make videos. \n\nFrom quality content to meme-able garbage, from scary games to full-on interactive movies you'll find it all. You will, actually. I have over 5000 videos so I'm sure there's something you'd like. \n\nMaybe you like horror games, or funny games, or comedy sketches, or animations, or compilations, or reactions, or reviews, or challenges, or cryptic lore, or mind-crippling ennui, or stuff-that-is-guaranteed-to-probably-make-you-cry? Whatever you're into I'm sure there's something for you down in the briny deep of my video page. So why not dive in?\n\nOr don't. Life is yours to choose after all.\n"
        },
        "country": "US"
      }
    }
  ]
}

You clearly see the difference between the title of the channel and the supplied value in the forUsername field.
Unfortunately, I don't know if this feature is documented anywhere and for avoid such complications, I rather user the channel_id - which is an unique value.