text:
Q: ARM Template: Service Principal for a newly generated App Site I'm wondering if I'm going about this wrong... but still....
For security reasons, it would be preferred that an App used integrated security to talk to its database, using the app's Service Principal AAD account.
But how to set this up using ARMs, hopefully with no manual steps?
For example, when creating an ARM that creates an environment from scratch, starting with the App Service... how does one create an App Service Principal (or trigger the creation of one automatically?), in order to use it as a parameter when developing the new sql server and database?
Can one set up a Service Principal account before an app is installed, and then associate it to the newly installed app? That way one could pass the name of the Service Principal as Parameters.
Thank you for any advice on whether:

*

*it's actually possible (maybe ARMs actually can't be pushed that far, and security accounts are considered outside the scope of infrastructure provisioning),

*if so, how!?!

Thank you.

A: IntegratedSecurity is not applicable to Azure SQL.
I'm currently figuring out how to do it with MSI.
https://learn.microsoft.com/en-us/azure/active-directory/managed-service-identity/overview


text:
Q: need to send mail using attachment and password encryption in ansible I am facing issue with by below playbook on 2 scenarios
1) How to send mails using ansible without defining the password of the account. using SMTP username and password now in the play to send mail. but is there any alternate way to avoid specifying password or using the encryption for password.
 - name: Send email
     mail:
        host: smtpserver.com
        port: 25
        username: mydomainID
        password: mypass
        subject: "Ansible test mail"
        attach: /opt/IBM/605CLM/JazzTeamserver/server/liberty/servers/clm/logs/jts.log
        body: "Testing email"
        from: mymailid.com
        to:
          - mymailid.com
        charset: utf8
        secure: never

2) Lokking for a way to attach the log file in the mail after starting the application. but it failing.. any advise please.
Getting error as below
An exception occurred during task execution. To see the full traceback, use -vvv. The error was: IOError: [Errno 2] No such file or directory: '/opt/IBM/605CLM/JazzTeamserver/server/liberty/servers/clm/logs/jts.log'
 [WARNING]: Username and Password was sent without encryption
fatal: [localhost]: FAILED! => {"changed": false, "msg": "Failed to send mail: can't attach file /opt/IBM/605CLM/JazzTeamserver/server/liberty/servers/clm/logs/jts.log: [Errno 2] No such file or directory: '/opt/IBM/605CLM/JazzTeamserver/server/liberty/servers/clm/logs/jts.log'", "rc": 1}
        to retry, use: --limit @/etc/ansible/roles/IBM2/tasks/pingmail.retry
PLAY RECAP **************************************************************************************************************************************************
localhost                  : ok=2    changed=0    unreachable=0    failed=1

A: *

*You can use vault encrypted variable file which will contain variable with the password for the SMTP user

*What problem are you facing? Any errors?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Service worker delays several minutes before sending controllerchange event I am moving our PWA from an appcache install to service workers. Have it working except that upgrades sometimes take over 10 minutes before notifying the client via the controllerchange event.  Sometimes it is almost instant.  I have no idea what the variable is.

let swRegWorker = null;

function showUpdateBar() {
    let snackbar = document.getElementById('snackbar');
    snackbar.className = 'show'
}

// the click event on the pop up notification
document.getElementById('reload').addEventListener('click', function() {
    window.location.reload()
});

if('serviceWorker' in navigator) {
    navigator.serviceWorker.register('/swmobile.js').then(reg => {
        swRegWorker = reg;

        // check for updates every 1 minutes
        setInterval(function(){
            swRegWorker.update()
        }, 1*60000)
    });

    // Listen for claiming of our ServiceWorker
    navigator.serviceWorker.addEventListener('controllerchange', function(event) {
      console.log('cchange', event);
      showUpdateBar()
    });
}
    #snackbar {
        visibility: hidden;
        min-width: 250px;
        margin-left: -125px;
        background-color: #333;
        color: #fff;
        text-align: center;
        border-radius: 2px;
        padding: 16px;
        position: fixed;
        z-index: 1;
        left: 50%;
        bottom: 30px;
    }

    #snackbar.show {
        visibility: visible;
        -webkit-animation: fadein 0.5s;
        animation: fadein 0.5s;
    }

    #snackbar #reload {
        font-weight: bold;
    }

    @-webkit-keyframes fadein {
        from {
            bottom: 0;
            opacity: 0;
        }
        to {
            bottom: 30px;
            opacity: 1;
        }
    }

    @keyframes fadein {
        from {
            bottom: 0;
            opacity: 0;
        }
        to {
            bottom: 30px;
            opacity: 1;
        }
    }

0855

A new version of this app is available.
Click HERE to update.

var CACHE_NAME = 'app-0855';

var urlsToCache = [
    '/',
    '/mobile.html',
    '/manifest.json'
];

self.addEventListener('install',function(e) {
    caches.open(CACHE_NAME).then(function(cache) {
        console.log('updating cache to', CACHE_NAME);
        return cache.addAll(urlsToCache)
    })
    .then(function() {
        self.skipWaiting()
    })
});

self.addEventListener('activate', function(e) {
    console.log('activate');

    e.waitUntil(
        Promise.all([
            self.clients.claim(),
            caches.keys().then(function(cacheNames) {
                return Promise.all(
                    cacheNames.map(function(cacheName) {
                        if(cacheName !== CACHE_NAME) {
                            console.log('deleting', cacheName);
                            return caches.delete(cacheName);
                        }
                    })
                )
            })
        ])
    )
});

self.addEventListener('fetch', function(event) {
    event.respondWith(
        caches.match(event.request)
        .then(function(response) {
            if(response){
                return response
            }
            // not in cache, return from network
            return fetch(event.request)
        })
    )
});

So the app initially installs fine and instantly upon loading.
However, when I modify the html and cache version in the service worker js file, in the next minute I see it download and install the update and see both caches in Chrome devtool temporarily.  Then the old cache is successfully removed.
In perfect cases, the client then pops up the upgrade available message immediately.  But about 50% of the time, for no known reason, it can take 5-30 minutes before the client sees the upgrade popup to refresh and run the new version.
The console logs show that everything is working in the service worker but the self.clients.claim call seems to wait for some amount of indeterminate time before firing the controllerchange event to the client.
I've rewritten a million times and read every tutorial I can find, starting with Google's service worker lifetime cycle documentation.  I'm at a loss.  Any ideas?

A: I believe I have solved it.  I had a small test page that always worked as the spec design says, but in our "real" app, this mysterious delay kept appearing.
As it turns out, it is our use of SSEs (server sent events, or EventSource) that seemed to "lock up" an active instance of the service worker.
I added the following code in the fetch handler and all delays seemed to have gone away!

    const request = event.request;
    const acceptHeader = request.headers.get('Accept');
    const url = request.url;

    if(acceptHeader.includes('text/event-stream') || url.indexOf('events') !== -1 || url.indexOf('api') !== -1) {
        console.log('ignoring', url);
        return
    }

While I believe the above solved 99% of the issue, I still had one instance on my phone where the controllerchange notification never happened.  So as a safeguard, I also added this in the service worker file and in the client which seems redundant, but is benign and gives a 100% success rate of upgrade notifications.

function send_message_to_client(client, msg) {
    return new Promise(function(resolve, reject){
        var msg_chan = new MessageChannel();

        msg_chan.port1.onmessage = function(event){
            if(event.data.error){
                reject(event.data.error);
            }
            else{
                resolve(event.data);
            }
        };

        client.postMessage("SW says: '"+msg+"'", [msg_chan.port2]);
    });
}

function send_message_to_all_clients(msg) {
    clients.matchAll().then(clients => {
        clients.forEach(client => {
            send_message_to_client(client, msg).then(m => console.log("SW Received Message: "+m));
        })
    })
}

self.addEventListener('activate', function(e) {
    console.log('activate');
    send_message_to_all_clients('Upgrade ready!') // the NEW line

    e.waitUntil(
        Promise.all([
            self.clients.claim(),
            caches.keys().then(function(cacheNames) {
                return Promise.all(
                    cacheNames.map(function(cacheName) {
                        if(cacheName !== CACHE_NAME) {
                            console.log('deleting', cacheName);
                            return caches.delete(cacheName);
                        }
                    })
                )
            })
        ])
        .then(function() {
            console.log('promises kept')
        })
        .catch(function(err) {
            console.log('promises broken', err)
        })
    )
});
    // handler for messages coming from the service worker
    navigator.serviceWorker.addEventListener('message', function(event) {
        console.log("client received: " + event.data);
        showUpdateBar()
    });


text:
Q: Commutation in coupled Harmonic Oscillators Starting with a coupled Harmonic Oscillator problem
$$
H = \frac{p_1^2 + p_2^2}{2m} + \frac{K}{2}\left[x_1^2 + x_2^2 + \left(x_1 - x_2\right)^2\right]
   = \left(\frac{p_1^2}{2m} + \frac{2K}{2}x_1^2\right) + \left(\frac{p_2^2}{2m} + \frac{2K}{2}x_2^2\right) - Kx_1x_2\,,
$$
we define the usual creation and annihilation operators
$$
p = i\sqrt{\frac{m}{2}\sqrt{\frac{2K}{m}}}\left(a^\dagger - a\right)\,,
\\
x = \sqrt{\frac{1}{2m\sqrt{\frac{2K}{m}}}}\left(a^\dagger + a\right)
$$
and obtain
$$
H = \sqrt{\frac{2K}{m}}\left(a^\dagger a + \frac{1}{2}\right) + \sqrt{\frac{2K}{m}}\left(b^\dagger b + \frac{1}{2}\right) - \frac{1}{4}\sqrt{\frac{2K}{m}}
 \left(a^\dagger + a\right)\left(b^\dagger + b\right).
$$
We know that the solution should be
$$
H = \sqrt{\frac{K}{m}}\left(\alpha^\dagger \alpha + 1/2\right) + \sqrt{\frac{3K}{m}}\left(\beta^\dagger \beta + 1/2\right)\,.
$$
Here, $\alpha$ and $\beta$ are related to $a$ and $b$ via a transformation. Importantly, $\alpha$ and $\beta$ are composed of $a$ and $b$, not $a^\dagger$ and $b^\dagger$.
Let us look at the zero-point energy. The latter Hamiltonian shows that it is $\frac{\left(1 + \sqrt{3}\right)}{2}\sqrt{K/m}$.
When I try to get the energy using QFT, I get different results. The derivation is below.
What am I missing? Are $a$ and $b^\dagger$ not supposed to commute? Makes sense they they would...
----- ADDED DERIVATION -----
The action for the original Hamiltonian is
$$
S =\beta  \sqrt{\frac{2K}{m}} + \sum_n \bar\phi_n\left(-i\nu_n +  \sqrt{\frac{2K}{m}}\right)\phi_n+ \sum_n \bar\psi_n\left(-i\nu_n +  \sqrt{\frac{2K}{m}}\right)\psi_n
\\
 - \frac{1}{4}\sqrt{\frac{2K}{m}}\sum_n \left(\bar\phi_n \bar\psi_{-n}+ \phi_n \psi_{-n}+  \bar\phi_n \psi_{n}+\bar\psi_n \phi_{n}\right)
$$
where $\nu_n$ is the Bosonic Matsubara frequency. The complex $\psi$ and $\phi$ fields correspond to the two oscillators. The assumption was made that $a$ and $b^\dagger$ commute to get the normal ordering! Note that the harmonic indices are the same for barred-unbarred products and opposite for barred-barred and unbarred-unbarred in the last term.
Massaging the expression a bit yields
$$
S
 =\beta  \sqrt{\frac{2K}{m}} + \bar\phi_0\left(-i\nu_0 +  \sqrt{\frac{2K}{m}}\right)\phi_0+ \bar\psi_0\left(-i\nu_0 +  \sqrt{\frac{2K}{m}}\right)\psi_0
 \\
 - \frac{1}{4}\sqrt{\frac{2K}{m}} \left(\bar\phi_0 \bar\psi_{0}+ \phi_0 \psi_{0}+  \bar\phi_0 \psi_{0}+\bar\psi_0 \phi_{0}\right)
 \\
 + \sum_{n> 0}
 \begin{pmatrix}
  \bar\phi_{n}\,,\phi_{-n}\,, \bar\psi_{n}\,,\psi_{-n}
 \end{pmatrix}
 \begin{pmatrix}
  -i\nu_n + \sqrt{\frac{2K}{m}}&0& - \frac{1}{4}\sqrt{\frac{2K}{m}} & - \frac{1}{4}\sqrt{\frac{2K}{m}}
  \\
  0&-i\nu_{-n} + \sqrt{\frac{2K}{m}} & - \frac{1}{4}\sqrt{\frac{2K}{m}} & - \frac{1}{4}\sqrt{\frac{2K}{m}}
  \\
  - \frac{1}{4}\sqrt{\frac{2K}{m}} & - \frac{1}{4}\sqrt{\frac{2K}{m}}
  &
  -i\nu_n + \sqrt{\frac{2K}{m}}&0
  \\
  - \frac{1}{4}\sqrt{\frac{2K}{m}} & - \frac{1}{4}\sqrt{\frac{2K}{m}}
  &
  0&-i\nu_{-n} + \sqrt{\frac{2K}{m}}
 \end{pmatrix}
 \begin{pmatrix}
  \phi_{n}
  \\
  \bar\phi_{-n}
  \\
  \psi_{n}
  \\
  \bar\psi_{-n}
 \end{pmatrix}
$$
Next, we obtain the partition function by exponentiating the action and integrating over the fields. This gives
$$
 \mathcal{Z} = \int \mathcal{D}\left(\dots\right) e^{-S}
 \\
  = e^{-\beta  \sqrt{\frac{2K}{m}}} \prod_{n>0}\frac{1}{\beta^4\left[\nu_n^4 + 2\nu_n^2\frac{2K}{m}+\frac{3}{4}\left(\frac{2K}{m}\right)^2\right]}
 \\
 \times
 \int d\left(\bar\phi_0,\phi_0\right)\,d\left(\bar\psi_0,\psi_0\right)
 \nonumber
 \\
 \times
 \exp\left[
 -\bar\phi_0\left(-i\nu_0 +  \sqrt{\frac{2K}{m}}\right)\phi_0
 -
  \bar\psi_0\left(-i\nu_0 +  \sqrt{\frac{2K}{m}}\right)\psi_0
  +
  \frac{1}{4}\sqrt{\frac{2K}{m}} \left(\bar\phi_0 \bar\psi_{0}+ \phi_0 \psi_{0}+  \bar\phi_0 \psi_{0}+\bar\psi_0 \phi_{0}\right)
 \right]
$$
The product over $\nu_{n>0}$ can be rewritten as
$$
\prod_{n>0}\frac{1}{\beta^4\left[\nu_n^4 + 2\nu_n^2\frac{2K}{m}+\frac{3}{4}\left(\frac{2K}{m}\right)^2\right]}
\\
  =\prod_{n}\frac{1}{\beta^2\left[\left(-i\nu_n + \sqrt{\frac{K}{m}}\right) \left(-i\nu_n + \sqrt{\frac{3K}{m}}\right)\right]}\times \beta^2\left(-i\nu_0 + \sqrt{\frac{K}{m}}\right) \left(-i\nu_0 + \sqrt{\frac{3K}{m}}\right)
$$
Now the product runs over all $\nu_n$. The additional factors are there because the original product did not include the zeroth harmonic. Note that $\nu_0 = 0$.
Going back to the zeroth harmonic integral
$$
 \int d\left(\bar\phi_0,\phi_0\right)\,d\left(\bar\psi_0,\psi_0\right)
 \\
 \times
 \exp\left[
 -\bar\phi_0\left(-i\nu_0 +  \sqrt{\frac{2K}{m}}\right)\phi_0
 -
  \bar\psi_0\left(-i\nu_0 +  \sqrt{\frac{2K}{m}}\right)\psi_0
  +
  \frac{1}{4}\sqrt{\frac{2K}{m}}\left(\bar\phi_0 + \phi_0\right)\left(\bar\psi_0+\psi_0\right)
 \right]
 \\
 =
 \int \frac{dx\,dy}{\pi}\frac{da\,db}{\pi}
 \exp\left[
 -\left(x^2 + y^2 + a^2 + b^2\right)\left(\sqrt{\frac{2K}{m}}\right)
  +
  \frac{1}{4}\sqrt{\frac{2K}{m}}\left(2x\right)\left(2a\right)
 \right]
 \\
 =
 \int \frac{dx\,dy}{\pi}\frac{da\,db}{\pi}
 \exp\left[
 -\left(x^2 + y^2 + a^2 + b^2\right)\left( \sqrt{\frac{2K}{m}}\right)
  +
  \sqrt{\frac{2K}{m}}xa
 \right]
 \\
 =
 \frac{1}{\beta\left(\sqrt{\frac{2K}{m}}\right)}\int \frac{dx\,da}{\pi}
 \exp\left[
 -\left(x^2 +  a^2\right)\left( \sqrt{\frac{2K}{m}}\right)
  +
  \sqrt{\frac{2K}{m}}xa
 \right]
 \\
 =
 \frac{1}{\beta^2\sqrt{3}\frac{K}{m}}
$$
Combining all this together gives
$$
\mathcal{Z} =
e^{-\beta\sqrt{\frac{2K}{m}}} \prod_{n}\frac{1}{\beta^2\left[\left(-i\nu_n + \sqrt{\frac{K}{m}}\right) \left(-i\nu_n + \sqrt{\frac{3K}{m}}\right)\right]}\,.
$$
To get the energy of the system, we do $-T\ln\mathcal{Z}$:
$$
E = \sqrt{\frac{2K}{m}} + T\sum_n \ln\left[\beta\left(-i\nu_n + \sqrt{\frac{K}{m}}\right) \right]
+
\ln\left[\beta\left(-i\nu_n + \sqrt{\frac{3K}{m}}\right) \right]\,.
$$
The last two terms can be summed the usual way to give
$$
E = \sqrt{\frac{2K}{m}} + T \ln\left[1 - e^{-\beta\sqrt{\frac{K}{m}}}\right]
+ T \ln\left[1 - e^{-\beta\sqrt{\frac{3K}{m}}}\right]\,,
$$
which vanish at $T = 0$. The energies inside these logarithms are the correct energies of the coupled oscillator modes. However, the term in the front, the vacuum energy that should be the only thing present at $T = 0$ is wrong...


text:
Q: Getting the values of the link using get variable in php I have a link in a php file which takes mke to another page. Here is the link:
 <?php  echo ' <a href="product_detail.php?marca='.$row["maname"].'">'?>

So I know that I can take the marca from this link using $_GET["marca"] in php.
Now I want to output some categories   but only them which marca is the same as $_GET["marca"]. I create this sql query but it outputs an error in the last row:

$sql0="SELECT  marche.marca as maname
FROM marche
 WHERE maname=$_GET["marca"];
  ";

Have I done something wrong? Can someone tell me which is the right syntax to include get variable inside sql queries?Thanks!

A: Your query seems to be okay except at one place.
$sql0="SELECT marche.marca as maname FROM marche WHERE maname=".$_GET["marca"];

But you should not depend on input ,you need to first sanitize it.
e.g.,
$input = mysql_real_escape_string(trim($_GET["marca"]));

$sql0="SELECT marche.marca as maname FROM marche WHERE maname='$input'";

A: Since you try de put php in your request, you need to close the SQL request, do your action in php, then open again your SQL request, like that :
$sql0="SELECT marche.marca as maname
FROM marche
WHERE maname=" . $_GET["marca"] .";";


text:
Q: Защита от некорректного использования extern в C Есть ли какая-то - на уровне стандарта - защита от некорректного использования объявлений extern в C? Например, пусть в одном файле есть
extern int global;

в другом -
double global = 3.1416;

Ведь mangling имен - это только в C++, который, конечно, в этой ситуации защитит (на уровне линковщика), в отличие от C, который должен скомпилировать и не поморщиться...
Получается, что в обычном C - только совесть программиста препятствие к некорректному использованию? никакого иного механизма нет (помимо вынести объявление extern в заголовочный файл и включать его во все файлы проекта)?

A: В принципе на практике следует поступать именно так: объявление с extern должно располагаться в заголовочном файле, а определение (с инициализатором) в некоем файле реализации включающем этот заголовочный файл. Тогда есть надежда, что такие очевидные ошибки вызовут диагностическое сообщение от компилятора.
Никакой другой "официальной" защиты в С нет.

A: Давайте начнём с того, что уясним, что данная проблема - это не проблема компилятора или конкретного языка программирования. Если модуль А компилируется сегодня в Голландии, а модуль В - через три года в Урюпинске, то НИКАКОЙ компилятор или язык программирования не сможет обеспечить проверку внешних описаний.
Далее, можно ли  считать данную проблему проблемой линкера? Отчасти... Т.е. если данный конкретный формат объектного модуля ПРЕДУСМАТРИВАЕТ описание типа для каждой области внешней памяти, то линкер сможет выполнить эту проверку, если он на это запрограммирован. И вылазит две проблемы:

*

*Существуют разные форматы ОМ даже в рамках одной ОС

*Существуют разные линкеры даже для одного формата ОМ

Вы говорите о каких-то конкретных формате ОМ и линкере?
Если речь идёт о линкере ld из состава linux, для модулей ELF, то рекомендую посмотреть на его опцию --warn-common. Как мне кажется, она может выдать предупреждения о всех подозрительных местах.


text:
Q: Assigning a variable with the contents of a file Does anyone know how to assign to a variable (from a batch /fisier.bat script) the contents of another file (file.txt). -CMD Windows

A: this gets the first line of a file into a variable:
<file.txt set /p "var="
echo %var%


text:
Q: Module-vs-vector space, a sentence in the book by Blyth I am now reading the book by Blyth, 'Module thery---an approach to linear algebra'.
I do not understand such a paragraph with which he motivates the learning of module theory:
In many ways, however, the notion of a vector space is too restrictive. Perhaps one way we can illustrate this is by asking the following question: has it occurred to the reader that, in most elementary introductions to linear algebra, determinants are defined for square matrices whose entries belong to a given field yet, come the consideration of eigenvalues, the matrix whose determinant has to be found has its entries in a polynomial ring? Put another way, should the various properties of determinants not really be developed in a more general setting?
Can anyone explain it in detail?

A: The eigenvalues of a matrix $A$ over a field $k$ are the roots of the characteristic polynomial $\chi(A)=\det(\lambda I-A)$. But what is this thing we're taking the determinant of? $\lambda$ is not an element of $k$, but an indeterminate, so to properly describe $\lambda I-A$ we ought to say its coefficients, e.g. $2-\lambda$, are elements of the polynomial ring $k[\lambda]$. So this is an example of a determinant of a matrix with entries from a ring that's not a field.


text:
Q: ActiveRecord:Rollback not working as expected in Rails 4 Still fairly new to Rails. Working on a group project to build a chess app we've got everything working except for a transaction rollback in our checkmate? method.
Moves are saved directly to the database.  Then, our check? method queries the database to see if the king is in check.  This created a problem for us for two reasons - 1. if you move yourself into check the move has to be undone 2. to determine checkmate you need to move pieces on the board and see if the king is still in check.  We implemented transactions for problem 1. and it works fine.
However, for checkmate the first thing we check is to see if the king can move himself out of check.  This method runs through the 9 squares the king might occupy to see if any of them successfully move him out of check.  I know the method is a bit sloppy now, but we're trying to get it to work then we can refactor.
Our goal is to move the king, see if it gets him out of check, then rollback the move.  The rollback should happen every time but the rollback never occurs.
 # determine if king can move himself out of check
  def can_move_out_of_check?
    success = false
    y_start = y_position
    ((x_position - 1)..(x_position + 1)).each do |x|
      ((y_start - 1)..(y_start + 1)).each do |y|
        Piece.transaction do
          move_to(x, y) if valid_move?(x, y)
          # if game.check?(color) comes up false,
          # even once, assign  true
          success = true unless game.check?(color)
          # reset any attempted moves
          fail ActiveRecord::Rollback
        end
      end
    end
    success
  end

I've tried different options King.transaction ActiveRecord::Base.transaction. Per one suggestion I tried ActiveRecord::Base.transaction(require_new: true) which rolled back on each check but also wouldn't allow me to make a valid move when the king was in check.
I feel like I'm missing something really simple.

A: A working configuration would be:
  def can_move_out_of_check?
    success = false
    y_start = y_position
    ActiveRecord::Base.transaction do
      ((x_position - 1)..(x_position + 1)).each do |x|
        ((y_start - 1)..(y_start + 1)).each do |y|
          move_to(x, y) if valid_move?(x, y)
          # if game.check?(color) comes up false,
          # even once, assign  true
          success = true unless game.check?(color)
          # reset any attempted moves
          fail ActiveRecord::Rollback
        end
      end
    end
    success
  end

Which would work because everything happens in the same transaction.


text:
Q: How to darken image on EMAIL? What's the best way to darken a background image in emails with CSS?
Eg I know usually you can use Filter etc, but I'm not sure if it works across all email providers
If using filter, this darkens the entire email including the 'overlay', and since absolute positioning isn't appropriate it's not a good solution
If using background linear gradient, it works great on many email apps, but some like hotmail won't recognise it since it uses 'shorthand' (background:linear-gradient(rgba(0, 0, 0, 0.5),rgba(0, 0, 0, 0.5)), url('my_url')) -is there a way to not use shorthand for this?

A: There are two common ways:
1) using CSS3:
.yourBackgroundImage {
    //halve image brightness
    filter:brightness(50%);
}

2) Using overlay:
.yourBackgroundImage {
    position: relative;
}
//yourBackgroundImageOverlay is a div inside youBackgroundImage
.yourBackgroundImageOverlay {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    // control overlay alpha by tweaking .5 in background color
    background-color: rgba(0, 0, 0, .5);
}


text:
Q: How to resolve SOQL SOSL Injection security error I am fairly new to salesforce. I am getting the soql sosl injection error in the below method while doing query. How to resolve this error?
 public static Days_Unavailable__c getAvlRecordById(String avlId){
            String query = QUERY_PART1 + ' where Id = \'' + avlId + '\' and Event_Status__c!=NULL ';

            selector.checkRead(QUERY_PART1_FIELDS);
            List<Days_Unavailable__c> avlList = Database.query(query);

            if(avlList != null && avlList.size() > 0 ){
                return avlList.get(0);
            }else{
                return null;
            }

        }

I set the 'QUERY_PART1' and 'QUERY_PART1_FIELDS'  as:
    final static String QUERY_PART1 = 'select Id, Weekly_Recurrence__c, Recurrence_Weekdays__c, Recurrence_End_Date__c, Start_Date__c, Candidate_Management__r.name, Candidate_Management__r.Placement__r.name, Candidate_Management__r.Placement__r.Company__r.name,End_Date__c, Event_Status__c, EventReason__c, Contact__c from Days_Unavailable__c';
    final static String QUERY_PART1_FIELDS = 'Id, Start_Date__c, Candidate_Management__r.name, Candidate_Management__r.Placement__r.name, Candidate_Management__r.Placement__r.Company__r.name,End_Date__c, Event_Status__c, EventReason__c, Contact__c';

A: You have two options:

*

*Use a merge variable. Simple, compact, easy to read.
String query = QUERY_PART1 + ' where Id = :avlId and Event_Status__c!=NULL ';

*Escape the input.
String query = QUERY_PART1 + ' where Id = \'' + String.escapeSingleQuotes(avlId) +
    '\' and Event_Status__c!=NULL ';

I also recommend very strongly you use complete words in all your variable names. Abbreviations are horrendous for readability.


text:
Q: Why did Wordpress overwrite my custom TwentyTwelve Theme? Do the standard TwentyTweleve, TwentyThriteen and TwentyFourteen Wordpress themes update automatically? I had some pretty heavy customizations in the TwentyTwelve Wordpress theme that were overwritten out of now where. Did not update Wordpress to a later version.
Do those themes update automatically? If I rename the folder to "MyCustomTheme" will I prevent this from happening again?

A: First and foremost, anytime you preform a core update on any application, you should always do a backup of your system in its' current state including any databases you may have in place.
Beyond that, you can prevent WordPress from overwriting any customization to the default themes by simply renaming that theme's folder.
However, I also recommend looking into starter themes for WordPress such as Underscores and Bones instead of starting with one of the built in themes.

A: The accepted answer is a lot of bull.
Here is what happens and what you should do
First of all, NEVER make any changes to any core file/plugin or theme, except when you are the author of that particular theme/plugin. The most obvious reason is the one that you've seen now, every change gets overwritten on updates. The core themes automaticaaly updates with core update.
The solution, create a child theme. The bundled themes are excellent for child themes. Child themes are really easy to create, 5minute max. You can modify the parent theme as you like, and the great thing is, it never gets updated or overwritten on core updates. You are the only one that can alter your child theme or update it as you wish.
There are many tutorials out there on child themes, even the codex have a page dedicated page to creating a child theme. Read that, it should help you out a lot.


text:
Q: CMSMarkStackSizeMax param in JVM 8 We have recently changed the JDK version from 1.7 to 1.8.
We are running normal JVM process with the below Memory Arguments , please below is just the snippet of the same.
MEM_ARGS="-DTENURED_SIZE=5G -Xms10G -Xmx10G -DCONSERVATIVE_ZONE=0 -DMEMORY_PANIC_DISABLE=YES "
-XX:+UseParNewGC -XX:NewSize=256m -XX:MaxNewSize=256m -XX:SurvivorRatio=3
GC_ARGS="-XX:-UseBiasedLocking -XX:+CMSPrecleanRefLists1 "
GC_ARGS="$GC_ARGS -XX:+CMSPrecleanRefLists2 "
GC_ARGS="$GC_ARGS -XX:+CMSClassUnloadingEnabled "
GC_ARGS="$GC_ARGS -XX:+CMSScavengeBeforeRemark "
GC_ARGS="$GC_ARGS -XX:PrintCMSStatistics=2 "
GC_ARGS="$GC_ARGS -XX:+UseCMSInitiatingOccupancyOnly "
GC_ARGS="$GC_ARGS -XX:CMSMarkStackSize=4m  "
GC_ARGS="$GC_ARGS -XX:CMSMarkStackSizeMax=5G "
GC_ARGS="$GC_ARGS -XX:ParGCDesiredObjsFromOverflowList=20k "
GC_ARGS="$GC_ARGS -XX:+UseConcMarkSweepGC  "
GC_ARGS="$GC_ARGS -XX:CMSInitiatingOccupancyFraction=40 "
GC_ARGS="$GC_ARGS -XX:+PrintGCApplicationStoppedTime  "
GC_ARGS="$GC_ARGS -XX:-OmitStackTraceInFastThrow  "

When we start the JVM we are receiving the below error in our log
Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize=384m; support was removed in 8.0

MarkStackSizeMax of 5368709120 is invalid; must be between 1 and
  2147483646 Error: Could not create the Java Virtual Machine. Error: A
  fatal exception has occurred. Program will exit.

What is the issue with MarkStackSize why we need to reduce it to less than 2 GB when same 5G value was working fine in JDK1.7?
Apart from this what is the MarkStackSize I could not find any information about the parameter.

A: Marking stack is the structure for traversing the reachable object graph during marking phase of GC.
JDK-8000244 added the range check for MarkStackSizeMax argument.
The upper limit is now (max_jint - 1).
I can't imagine a case when a larger value may be ever needed, so I suggest to simply remove the argument and let JVM choose the default. Most likely, this will not affect the performance anyway.


text:
Q: How to properly use LIKE statement in sql query I have database which contains a field named groupid and group name.
sample data
groupid   groupname
123          abc
234          bcr
1237         cde

I like to compare groupid with another inputted data, its size is greater than size of group id.
I tried a query that not return correct answer
SELECT *
  FROM mydata
 WHERE groupid LIKE '12309098';

My expected answer is abc
What are the changes to made for correct answer
thanks in advance

A: Since you want the value in the row to be the prefix of your input and not the other way around, you can just turn LIKE around the other way;
SELECT *
FROM mydata
WHERE '12309098' LIKE CONCAT(groupid, '%');

An SQLfiddle to test with;
EDIT: Since you asked about SQLite, there you need to use || for concatenation;
SELECT *
FROM mydata
WHERE '12309098' LIKE `groupid` || '%';

Another SQLfiddle.

A: You could do like below:
SELECT *
FROM my data
WHERE '12309098' LIKE CONCAT('%', groupid, '%');

A: You could use something like this. But it is highly subjective to your SQL Server. For Oracle following syntax should be fine
SELECT *
  FROM mydata
 WHERE groupid LIKE SUBSTR('12309098',1, LENGTH(groupid));

A: If you are sure that input data will start with 123, then:
SELECT * FROM mydata WHERE groupid LIKE '123%';

If you are sure that input data will contain 123, then:
SELECT * FROM mydata WHERE groupid LIKE '%123%';


text:
Q: Vue.js change {{ }} tags I want to change the {{ something }} by <% something %> in Vue.js, how could I achieve that, is it even possible?
An equivalent for what I look for in AngularJS:
var app = angular.module('app', [], function($interpolateProvider) {
    $interpolateProvider.startSymbol('<%');
    $interpolateProvider.endSymbol('%>');
});

A: If you are working with Vue 3.x, the documentation tells you to do this:
Vue.createApp({
  // Delimiters changed to ES6 template string style
  delimiters: ['${', '}']
})

A: You should modify the delimiters property of configuration object.
Vue.config.delimiters = ['<%', '%>']

Edit: This solution works for Vue 1.x and lower. See @Skip and @jaynabonne responses for Vue 2.x solution

A: I am running Vue 2.1.0 standalone and this is what I had to use
Vue.options.delimiters = ['{[{', '}]}'];

A: With the latest version (2.0.5), the above doesn't work. Rather than assigning to the global config, you pass the delimiters as an option to the Vue instance:
new Vue({
    el: '#app',
    data: data,
    delimiters: ["<%","%>"]
});

At least, that's what I had to do to make it work.

A: Use this code to change template engine in vue js
 new Vue({
        el: '#app',
        data: {
            message: 'hello world'
        } ,
        delimiters: ['<%' , '%>']
    });


text:
Q: Update one MySQL table with values from another (Datatype of the original table is JSOn) I'm trying to update one MySQL table based on information from another.
The original table where I would like to compare the values to the other table to be updated has a JSON object in it.
Here is what my tables look like
Original Table
Table1
id | programme
------------
1  | ["22","34"]
2  | ["10","11","12","13","14","15","17","18","19","20"]

Table to be updated
Table2
id | programme_id | table1_id
-----------------------------
1  |     22       |
2  |     18       |
3  |     12       |

UPDATE table2
INNER JOIN table1 USING (programme_id)
SET table2.table1_id = table1.id

Here is the expected output:
id | programme_id | table1_id
-----------------------------
1  |     22       |   1
2  |     18       |   2
3  |     12       |   2

A: set sql_safe_updates = 0;
update table2
inner join table1
on JSON_SEARCH(table1.programme,'one',table2.programme_id) is not null
set table2.table1_id = table1.id;


text:
Q: Copy content from webpage and paste it in another website to search in Edge or Chrome browser Need help please.
How can I achieve the following?
I use https://spur.us/context website to investigate IP addresses.
Currently I am having to copy IP address from a website and paste manually in the spur.us website which is time consuming. I want to make this process quicker.
How can I just select an IP address like shows in below image and open in separate website by attaching the copied content like https://spur.us/context/20.238.65.64

Is there any tool/extensions I can use or setting within browser?
TIA

A: quick way is, you can customize browser search engine check this https://support.google.com/programmable-search/answer/4513882?hl=en#:~:text=From%20the%20Programmable%20Search%20Engine,can%20always%20add%20more%20later.
I don't think if there is an extension exists for this purpose.
Any experienced Extension developer, including me, can make one you. feel free to connect.

A: Is it that you need to navigate to https://spur.us/context/20.238.65.64 by only selecting 20.238.65.64 and performing some sort of action within a single page? It looks like the context menu wouldn't help (the browser would directly lead you to this ip address instead of searching for it), but you can achieve it by specifying your own search engine. Please go to the following url for search engine setting.
Edge: edge://settings/searchEngines?search=engine
Chrome: chrome://settings/searchEngines?search=search+engine
You can add spur.us as a search engine. You need to choose Make default after adding it and make sure your search engine url looks like this: https://spur.us/context/%s
Then, you need to

*

*Copy the ip address.

*Press Ctrl+E to call the default search engine.

*Paste the ip address.

Now you will be able to see the expected result. Though it may not be exactly what you've asked for, I think it does smooth the work flow. Remember to make default your previous default search engine after the work is finished.


text:
Q: Reducing code duplication from common code calling common class I have a class 'A' which is almost perfect for my needs.
Class 'B' uses class 'A'
I've now designed Class 'C' and Class 'D' and noticed that there is a good chunk of code in class 'B', 'C' and 'D' for using Class 'A' is duplicated. I've separated out this code in specific, standalone functions in each of the classes.
Now I'm wondering where this code should go. At the moment, the functions are duplicated in the three calling classes (B, C and D).
Placing the functions into class 'A' would break the single responsibility principle. Inheritance to add functionality would likely break both SRP and LSP.
The one that seems that it may work is composition.
Q: Is designing a complete class just for a few functions over kill?
Q: Would it be valid for classes 'B', 'C' and 'D' to access both the new class 'E' (which would depend on A) and the old class 'A' (which would have to be the same instance as the instance in the new class 'E'), or should the new class 'E' provide sufficient functionality so that Classes B, C and D don't need to access Class A directly? It would seem that its then an incomplete interface with additional functionality.
Or should the new class 'E' do something and return the result to class B, C, D, which they can then pass on to class 'A' themselves. Actually, no, that can't work as the class would have to called again on certain return values.
Or should I do it a completely different way?
(and why does software design require so much thinking?)
An example usage scenario:
Class B: while ((A->DoSomething() == ERROR/TIMEOUT/etc) && (retries < 3)) { retries ++; A->SetSomeParameters(); }
(actual code is larger)

A: If the code so duplicated is (a) large(ish), (b) will probably change in lockstep to all using classes, and thus (c) runs the risk of drifting apart creating new bugs, I'd go for creating a (hidden) class containing that functionality and inherit it as needed.
In any case, consider carefully costs vs benefits. Adding one version of the function(s) creates rigidity which might need to be removed (splitting up again) later on. "Do work now, it might be useful later on" more often than not turns out to just create extra work for later (Murphy's law being absolutely relentless). The overall architecture is more important than details of possible duplications.


text:
Q: Get files not in hidden folders The test is failing because it's getting the files from hidden folders too. How can I modify the code so that it skips the hidden folders?
def get_files_not_in_hidden_folder(parent_folder: str, extension: str) -> List[str]:
    """
    Get all files recursively from parent folder,
    except for the ones that are in hidden folders
    """
    files = []
    for root, _, filenames in os.walk(parent_folder):
        for filename in filenames:
            if filename.endswith(extension) and not root.startswith('.'):
                files.append(os.path.join(root, filename))
    logger.debug(f"get_files_not_in_hidden_folder: {parent_folder}, {extension} -> {files}")
    return files

def test_get_files_not_in_hidden_folder():
    Path('tmp').mkdir(parents=True, exist_ok=True)
    Path('tmp/test.json').touch()
    Path('tmp/tmp/.tmp').mkdir(parents=True, exist_ok=True)
    Path('tmp/tmp/.tmp/test.json').touch()
    Path('tmp/.tmp/tmp').mkdir(parents=True, exist_ok=True)
    Path('tmp/.tmp/tmp/test.json').touch()

    assert get_files_not_in_hidden_folder('tmp', '.json') == ['tmp/test.json']

    shutil.rmtree(Path('tmp'))

A: What you call root is the full path, including parent names.
If you want to convert to just the directory name, you can use os.path.basename,  like:
    for root, _, filenames in os.walk(parent_folder):
        for filename in filenames:
            if filename.endswith(extension) and "/." not in root:
                files.append(os.path.join(root, filename))

A: I would implement this something like as follows ...
def my_walk(root_dir):
    files,dirs = [],[]
    try:
        for fname in os.listdir(root_dir):
            if not fname.startswith("."):
               fpath = os.path.join(root_dir,fname)
               if os.path.isdir(fpath):
                  dirs.append(fpath)
               else:
                  files.append(fpath)
    except:
        print("SKIP:",root_dir)
    yield root_dir,dirs,files
    for d in dirs:
        yield from my_walk(d)

I think should work ...
for root, _, filenames in my_walk(parent_folder):
    print(f"{root} contains {filenames}")


text:
Q: Expected value of first and second moment I have the following

*

*Let $X_1, X_2, \ldots, X_n$, $Y_1, Y_2, \ldots, Y_n$ and $W_1, W_2, \ldots, W_n$ be independent, real-valued random variables

*Suppose that $X_n$ are i.i.d. with
$$E\left[X_n\right]=0,\quad\quad E\left[X_n^2\right]=1$$

*Suppose that $Y_n$ only are indpendent, but not identical, with:
$$E\left[Y_n\right]=0,\quad\quad E\left[Y_n^2\right]=n^2$$

*Suppose that $W_n\sim\text{Bernoulli}\left(\frac{1}{n^2}\right)$ with
$$P(W_n=0)=1-\frac{1}{n^2},\quad P(W_n=1)=\frac{1}{n^2}$$

*Define
$$Z_n=X_n+W_nY_n$$

I have to find $E\left[Z_n\right]$
$$
E\left[Z_n\right]=E\left[X_n+W_nY_n\right]
  =E\left[X_n\right]+E\left[W_n\right]E\left[Y_n\right]
  =0+E\left[W_n\right]\cdot 0
  =0
$$
and $E\left[Z_n^2\right]$:
$$
  E\left[Z_n^2\right]=E\left[\left(X_n+W_nY_n\right)^2\right]=E\left[X_n^2\right]+E\left[W_n^2\right]E\left[Y_n^2\right]+2E\left[X_n\right]E\left[Y_n\right]E\left[W_n\right]
$$
$$
  =1+E\left[W_n^2\right]n^2+2\cdot 0\cdot 0\cdot E\left[W_n\right]=1+\frac{1}{n^2}n^2=2
$$
I am not sure whether this is possible, when $Y_n$ only is indpendent, but not also identical. Any help regarding this, will be greatly appreciated.

A: The crux of your question is: are your steps OK when we only have independence, or was identical distribution required anywhere? The answer to that is: $\fbox{no, you're fine.}$
The big algebraic rule that you applied several times is the expression $\mathbb E[U V] = \mathbb E[U] \mathbb E[V]$ for various random variables $U$, $V$. This applies so long as $U, V$ are independent of one another (and everything in your problem statement is independent of everything else). Whether they are identically distributed is irrelevant.
If it makes you any more comfortable with it, you're making a statement for each value of $n$, and you're showing that the expectation happens to be the same for every possible value of $n$.


text:
Q: Can't install an app downloaded from the internet I am having problems publishing my application through the internet.
I have an application built to 1.6 or latter android system, I have published a link accessible by the mobile browser to let users download the application and install it on their phone.
The download goes with no problems in all of the devices I have tested but in 2.1 devices or lower I can t install the app and a warning message is given to me: "Application is not installed".
I google for a while at in the end I have found the problem: You can t install an application from the sdcard until version 2.2
I don t know how to get over this problem, I would really want to give users the opportunity to download the app from my web to all devices. Any advice?

A: Did you check in the manifest file the minVersion, minSdk, api-version fields ?
http://developer.android.com/guide/practices/compatibility.html

A: There is an app that you can install and then install an apk from sdcard. The app is called apkInstaller. Another way to install an apk is using adb command for those ones that have installed.

A: Include the android:installLocation attribute with a value of "auto" or "preferExternal" in the  element.
Refer this:http://developer.android.com/guide/appendix/install-location.html
Cheers!!!


text:
Q: string initialization in C I am writing insertion sort using strings. I have char arrays like:
 char array1[4] = {'a', 'b', 'c', '\0'};
 char array2[4] = {'b', 'd', 'e', '\0'};

And I need to use this operation:
char string[2];
string[1] = array1;
string[2] = array2;

Is it possible ?
Because in insertion sort I need a string.
This is the insertion code:
char* insertionsort(char* a, int n) {
   int k;
   for (k = 1; k < n; ++k) {
      int key = a[k];
      int i = k - 1;

      while ((i >= 0) && (key < a[i])) {
         a[i + 1] = a[i];
         --i;
      }

      a[i + 1] = key;
   }

   return a;
}

A: char array1[4] = {'a', 'b', 'c', '\0'};  // same as char *array1 = "abc";
char array2[4] = {'b', 'd', 'e', '\0'};  // same as char *array2 = "bde";

char *string [2]; // an array of 'pointers to chars' / array of strings

string[1] = array1; // this will work
string[2] = array2; // this will work

A:
So I need to write this operation :

char string [2];
string[1] = array1;
string[2] = array2;

Is it possible ?

Short answer: no, it's not. Arrays are not assignable. You can use strcpy to copy the elements from one string to another, but in this case that won't work either -- you've defined string as an array of 2 chars, but you're trying to assign an entire array of chars to each of those.
It's not entirely clear that it's what you want, but one possibility would be:
char *string[2];
string[1] = array1;
string[2] = array2;

In this case, string is an array of two pointers to char, and the assignments set those to point to the first character of each of your previously defined strings.
Since you've tagged this as both C and C++, I'll add a bit about that: this is written as very much C code. If you're actually using C++, you probably want something more like:
std::string[2] = {"abc", "bde"};

Even in C, I'd prefer to initialize and use string constants where they make sense:
char array1[] = "abc";
char array2[] = "bde";

char *string[] = {array1, array2};

Or even just:
 char const *string[] = {"abc", "bde"};

A: Of course not. Just remember,
    char ary[4] = {'a', 'b', 'c', '\0'}; //define an array of char

When you use ary like this:
    char string[2];
    string[0] = ary;

ary degenerates from the name of an array to a pointer! So, what you do above is assigning a pointer to a char type, and which will lead to a type warning when compiling.
This is very important in C!
And you can fix it like this:
    char *string[2];             //an array of pointers to char
    string[1] = array1;          //correct
    string[2] = array2;


text:
Q: How do I go about heading down the Independent Road? I want to do an independent ending of New Vegas but I can't figure out how to do it. Last time I found myself on the NCR ending without even realizing it. How do I start the Independent road?

A: (Since we're talking about endings, spoilers ahoy!)
The "independent New Vegas" ending is all about Yes Man.  You'll first encounter Yes Man on the 13th floor of The Tops casino, and he'll discuss Benny's plan with you after you've dealt with Benny, either by killing him or having him flee.  Discuss Benny's plan with Yes Man, and he'll explain what needs to be done to finish this quest line.
You can switch factions even late into the game, so don't worry too much if you've started down some NCR, Legion, or House questlines before you start dealing with Yes Man.  You'll get a warning from each of the other factions in the form of a new quest when you're nearing the point of no return.
The "No Gods, No Masters" ending is also the "catch-all" ending if you end up doing a lot of really bad things to everyone.  If you want to ensure you can't possibly win the game any other way, try killing all the leaders of all the other factions.  You'll be in for a fight, but you'll have locked in your ending choice...


text:
Q: C# 4.0: Convert pdf to byte[] and vice versa How do I convert a pdf file to a byte[] and vice versa?

A: // loading bytes from a file is very easy in C#. The built in System.IO.File.ReadAll* methods take care of making sure every byte is read properly.
// note that for Linux, you will not need the c: part
// just swap out the example folder here with your actual full file path
string pdfFilePath = "c:/pdfdocuments/myfile.pdf";
byte[] bytes = System.IO.File.ReadAllBytes(pdfFilePath);

// munge bytes with whatever pdf software you want, i.e. http://sourceforge.net/projects/itextsharp/
// bytes = MungePdfBytes(bytes); // MungePdfBytes is your custom method to change the PDF data
// ...
// make sure to cleanup after yourself

// and save back - System.IO.File.WriteAll* makes sure all bytes are written properly - this will overwrite the file, if you don't want that, change the path here to something else
System.IO.File.WriteAllBytes(pdfFilePath, bytes);

A: Easiest way:
byte[] buffer;
using (Stream stream = new IO.FileStream("file.pdf"))
{
   buffer = new byte[stream.Length - 1];
   stream.Read(buffer, 0, buffer.Length);
}

using (Stream stream = new IO.FileStream("newFile.pdf"))
{
   stream.Write(buffer, 0, buffer.Length);
}

Or something along these lines...

A: using (FileStream fs = new FileStream("sample.pdf", FileMode.Open, FileAccess.Read))
            {
                byte[] bytes = new byte[fs.Length];
                int numBytesToRead = (int)fs.Length;
                int numBytesRead = 0;
                while (numBytesToRead > 0)
                {
                    // Read may return anything from 0 to numBytesToRead.
                    int n = fs.Read(bytes, numBytesRead, numBytesToRead);

                    // Break when the end of the file is reached.
                    if (n == 0)
                    {
                        break;
                    }

                    numBytesRead += n;
                    numBytesToRead -= n;
                }
                numBytesToRead = bytes.Length;
}


text:
Q: JavaScript: slice object name "course_DxhYTv2copzWyBhKo" : {
    "interest" : "DxhYTv2copzWyBhKo",
    "type" : "course",
    "affinity" : 3
}

From Object Name "course_DxhYTv2copzWyBhKo",
I want to slice "DxhYTv2copzWyBhKo"

A: Using String#split:

const data = {
  "course_DxhYTv2copzWyBhKo" : {
    "interest" : "DxhYTv2copzWyBhKo",
    "type" : "course",
    "affinity" : 3
  }
};

const key = Object.keys(data)[0];
const sliceAfterSubStr = "course_";

const slicedSubStr = key.split(sliceAfterSubStr)[1];

console.log(slicedSubStr);

Using String#substr:

const data = {
  "course_DxhYTv2copzWyBhKo" : {
    "interest" : "DxhYTv2copzWyBhKo",
    "type" : "course",
    "affinity" : 3
  }
};

const key = Object.keys(data)[0];
const sliceAfterSubStr = "course_";
const sliceIndex = key.indexOf(sliceAfterSubStr);

const slicedSubStr = sliceIndex !== -1
  ? key.substr( sliceIndex + sliceAfterSubStr.length )
  : undefined;

console.log(slicedSubStr);

A: You can use the split operation on a string. Take a look at the following code snippet.

const courses = {
  "course_DxhYTv2copzWyBhKo": {
    "interest": "DxhYTv2copzWyBhKo",
    "type": "course",
    "affinity": 3
  },
  "course_DSdasdnDASnoiddDs": {
    "interest": "DSdasdnDASnoiddDs",
    "type": "course",
    "affinity": 3
  }
}

console.log(Object.keys(courses).map(key => key.split("_")[1]))


text:
Q: Hashmaps contain the same key I have a
Stack<MyThread> rts;
each Thread contains a HashMap with a Custom Object Key.
HashMap<CustomObject> myMap = rts.pop().mapOfThread;
and I have the HashMap of these CustomObjectKeys
MyThread.CustomObjectMap
I need the fastest way to check if any of the HashMaps in the Threads in the Stack contains the same key as my CustomObject HashMap.

A: So, if I understand correctly, you have a number of disjoint HashMaps that may share keys, and you want to see if any keys are the same across any or all?
If so, I don't really see a solution other than iterating through the keySet() and checking each HashMap to see if the key is present, probably via containsKey().


text:
Q: How connect programmaticaly the UISlider with a Label below of the slider which the view is normaly to all iphone screens? I make an array for the range of a UISlider, and I put each values on a label below the slider, but if I change iPhone screen (5s, 6s, 8, Xr)
the label doesn't show the correct position of the UISlider values.
How should I connect the range of UISlider array values, with the Label below for every iPhone screen?
Expected results
Debug View Hierarchy

There is a method for the setup Auto Layout regardless of the different iphone screen . Where you see Easy.Layout that is EasyPeasy Auto-Layout is the same of Apple documentation Auto Layout Constrains.
func setupLabels() {
    let values = [0, 3.7, 11, 22, 43, 50, 100]
    values.forEach({
        let sliderValuesLabel = UILabel()
        if $0 == values.first {
            sliderValuesLabel.text = "ALLE"
            wrapperView.addSubview(sliderValuesLabel)
            sliderValuesLabel.easy.layout(

                Top(15).to(uislider),
                Leading().to(uislider, .leading), // Left Position
                Bottom(1)
            )

        } else if $0 == values.last {
            sliderValuesLabel.text = "\(Int($0))+"
            wrapperView.addSubview(sliderValuesLabel)
            sliderValuesLabel.easy.layout(
                Trailing().to(uislider, .trailing), // Right Position
                Top(15).to(uislider),
                Bottom(1)
            )

        } else  {
            sliderValuesLabel.text = "\(Int($0))"
            wrapperView.addSubview(sliderValuesLabel)

            let thumbRect = uislider.thumbRect(forBounds: uislider.bounds,
                                               trackRect: uislider.trackRect(forBounds: uislider.bounds),
                                               value: uislider.value)
            let thumRectToView = uislider.convert(thumbRect, to: uislider ) // Convert

            sliderValuesLabel.easy.layout(
                Top(15).to(uislider),
                Bottom(1),
                CenterX(thumRectToView.midX)

            )
        }
    })

}

A: You will need to set constraints on the label using Auto-Layout. This will keep it in a fixed position on all devices.


text:
Q: Sort List> Alphabetically for the string value of tuple, C# How can I sort a list(Tuple<string, class>) in ascending order for the values of string item of tuple ?

A: var ordered = myList.OrderBy(t => t.Item1).ToList();

A: list.OrderBy(x => x.Item1);

Assumes your string is in Item1.


text:
Q: int ** vs int [ROWS][COLS]
Possible Duplicate:
casting char[][] to char** causes segfault?

I have a 2D array declared like this:
int arr[2][2]={ {1,2},{3,4}};

Now if I do:
int ** ptr=(int**) arr;

and:
cout<<**ptr;

I am getting a segmentation fault (using g++-4.0).
Why so? Shouldn't it be printing the value 1 (equal to arr[0][0])?

A: You can't cast a linear array to a pointer-to-pointer type, since int** doesn't hold the same data int[][] does.
The first holds pointers-to-pointers-to-ints. The second holds a sequence of ints, in linear memory.

A: What you do now means creating of arrays of pointers where every pointer was explicitly casted. Therefore, you would have an array of pointers like (0x00001, 0x00002, 0x00003 and 0x00004).
When dereferenced, this pointers cause your segfault.

A: You are attempting to assign a double pointer variable to an array... this has been covered exhaustively, see here for information on this. Furthermore, since you declared

int arr[2][2] = ...;

and then try to assign arr to a double pointer

int ** ptr = ... ;

which is guaranteed to not work, hence a segmentation fault. Furthermore, that statement int ** ptr=(int**) arr; is actually cast ing one type (i.e. [][]) to another type (i.e. **) despite they are of type 'int'. They are both different and the compiler will interpret that very differently...
You could do it this way:

int *ptr = &arr;

Now *(ptr + 1)  will refer to the 0'th row, *(ptr + 2) will refer to the 1'st row and so on. The only onus on you is to not overstep the markers of where arr is used otherwise an overflow can happen or even a segmentation fault...

A: No, int ** is a pointer to a pointer to an int, but a 2-D array is an array of arrays, and &(arr[0][0]) is a pointer to an int.
I believe you should be doing this:
int *ptr = arr;
cout<<*ptr;

or this:
int *ptr = &arr[0][0];
cout<<*ptr;

A: Try
int *ptr = arr;

More Explanation:
You should assign an adress to the pointer, so it can be derefenced(i mean * operator). What you do is, pointing ptr to memory cell that has the adress a[0][0]. Therefore, you get a segmentation fault.

A: int arr[2][2] is not an array of arrays - it is a single 2d array.  In memory, it is indistinguishable from int arr[4]
What you really want is
int (*ptr)[2] = arr;


text:
Q: How to make a user press a key in a c++ program Hey I'm new to c++ and I have to make a user input the number, and whatever number that person chooses(1-5) will send them to the area that corresponds with that number. I don't really know how to do it, so can anyone show me or tell me what to do? Feel free to ask any questions. Thanks!
Code below:
cout << "1.Input New Employee"; endl;
cout << "2.Search For Employee By ID Number";  endl;
cout << "3.Edit Existing Employee Information"; endl;
cout << "4.Display all Employees"; endl;
cout << "5.EXIT";endl;

P.S: Now I get this error message"Statement cannot resolve address of overload function" can anyone tell me how to fix it? Thanks

A: Here is a script that should help show you what you need to do:
bool loop = true;
while(loop){
    cout << "What do you want to do?\n";
    cout << "    1 - Input New Employee\n";
    cout << "    2 - Search for Employee By ID Number\n";
    cout << "    3 - Edit Existing Employee Information\n";
    cout << "    4 - Display All Employees\n";
    cout << "    5 - EXIT\n";
    cout << "Your selection: ";
    string select; getline(cin, select);
    cout << "/n";
    try {
        switch(stoi(select)){
            case 1:
                employeeInput(); // Sample code
                break;
            case 2:
                employeeIDSearch(); // Sample code
                break;
            case 3:
                employeeInfoEdit(); // Sample code
                break;
            case 4:
                employeeDisplayAll(); // Sample code
                break;
            case 5:
                loop = false; // Exit loop
                break;
            default:
                cout << "Invalid Input.\n\n";
                break;
        };
    };
    catch(const std::exception& ex){
        cout << "Invalid Input.\n\n";
    };
};

Just a side note, the endl command is meant to be piped into cout, not used as a standalone statement.
EDIT: The functions I used are simply placeholders, I wanted to show how you'd use the code in the switch. Also, feel free to use this :)

A: Use "cin" get the press character.
char ch;

cin >> ch;

Now ch varriable has the pressed character. You can take input of all data types using this.

A: use cin to take the input and then switch to call corresponding functions.
int choice;
cin>>choice;
switch(choice)
{
    case 1 : //your code;
             break;
    case 2 : //your code;
             break;
   /*  rest of your cases */
}


text:
Q: Multiple IF statements with a drop down Google Sheets Query Consider the following,
I have three columns,
date, sales rep, revenue,
Date,   Sales Rep,    Revenue,
1/1/18  Jon           £250
1/1/18  Evie          £350
1/1/18  Muhammad      £220

Now, to query this data I can do the following:
IF(a2="","", QUERY(B2:C4, "Select * Where A = '"&A2&"')

now what I want to know is how one would nest multiple queries into one cell if one had multiple drop downs for the above. One selecting sales rep and one for date. So if one Selected a Sales rep & a date, they would get the specific date and sales rep but if one selected JUST a sales rep they would get all their sales regardless of date, and the reverse if possible.
I've tried an OR statement
IF(OR(a2="","", QUERY(B2:C4, "Select * Where A = '"&A2&"'), IF(a3="","", QUERY(B2:C4, "Select * Where b = '"&A3&"'))) but this didn't work.

I've created some dummy data and an open sheet for your convenience.
https://docs.google.com/spreadsheets/d/15nlBPM9u3g0XNE3xbBgSZJxyHz2JjP9io1LfqGgX4CI/edit?usp=sharing

A: It is easier to work on the SQL clause a piece at a time and then pull it together, I think. So for instance in J2 you could put
=if(ISBLANK(E2),"","B = '"&E2&"'")

which is either empty or a piece of the where clause.
In J3 do
=if(ISBLANK(E3),"","A = Date'"&text(datevalue(E3),"yyyy-mm-dd")&"'")

then J4 gets
=TEXTJOIN(" AND ",true,J2:J3)

and clinch with J5 as follows.
=if(isBlank(J4),"",query(A:C,"SELECT * WHERE " & J4))


text:
Q: OpenMP: Looping Through 'std::map' Benchmark (Dynamic Scheduling) I have to loop through std::map and the job that has to be done within each iteration has the following properties:

*

*The amount of work varies within each iteration;

*Does not need any synchronization between threads.

Looks like perfect scenario for dynamic scheduling, doesn't it?
However, non-random access iterators (such as std::map has) are notorious of troubling one as far as loop parallelization with OpenMP is concerned. For me the performance of this particular code is going to be critical, therefore in search for the most efficient solution I've created the following benchmark:
#include <omp.h>

#include <iostream>
#include <map>
#include <vector>

#define COUNT 0x00006FFF

#define UNUSED(variable) (void)(variable)

using std::map;
using std::vector;

void test1(map<int, vector<int> >& m) {
  double time = omp_get_wtime();

  map<int, vector<int> >::iterator iterator = m.begin();

#pragma omp parallel
#pragma omp for schedule(dynamic, 1) nowait
  for (size_t i = 0; i < m.size(); ++i) {
    vector<int>* v;
#pragma omp critical
    v = &iterator->second;

    for (size_t j = 0; j < v->size(); ++j) {
      (*v)[j] = j;
    }

#pragma omp critical
    iterator++;
  }

  printf("Test #1: %f s\n", (omp_get_wtime() - time));
}

void test2(map<int, vector<int> >& m) {
  double time = omp_get_wtime();

#pragma omp parallel
  {
    for (map<int, vector<int> >::iterator i = m.begin(); i != m.end(); ++i) {
#pragma omp single nowait
      {
        vector<int>& v = i->second;

        for (size_t j = 0; j < v.size(); ++j) {
          v[j] = j;
        }
      }
    }
  }

  printf("Test #2: %f s\n", (omp_get_wtime() - time));
}

void test3(map<int, vector<int> >& m) {
  double time = omp_get_wtime();

#pragma omp parallel
  {
    int thread_count = omp_get_num_threads();
    int thread_num = omp_get_thread_num();
    size_t chunk_size = m.size() / thread_count;
    map<int, vector<int> >::iterator begin = m.begin();
    std::advance(begin, thread_num * chunk_size);
    map<int, vector<int> >::iterator end = begin;
    if (thread_num == thread_count - 1)
      end = m.end();
    else
      std::advance(end, chunk_size);

    for (map<int, vector<int> >::iterator i = begin; i != end; ++i) {
      vector<int>& v = i->second;

      for (size_t j = 0; j < v.size(); ++j) {
        v[j] = j;
      }
    }
  }

  printf("Test #3: %f s\n", (omp_get_wtime() - time));
}

int main(int argc, char** argv) {
  UNUSED(argc);
  UNUSED(argv);

  map<int, vector<int> > m;

  for (int i = 0; i < COUNT; ++i) {
    m[i] = vector<int>(i);
  }

  test1(m);
  test2(m);
  test3(m);
}

There are 3 possible variants that I could come up with to imitate my task. The code is very simple and speaks for itself, please take a look at it. I've ran the tests several times and here are my results:
Test #1: 0.169000 s
Test #2: 0.203000 s
Test #3: 0.194000 s

Test #1: 0.167000 s
Test #2: 0.203000 s
Test #3: 0.191000 s

Test #1: 0.182000 s
Test #2: 0.202000 s
Test #3: 0.197000 s

Test #1: 0.167000 s
Test #2: 0.187000 s
Test #3: 0.211000 s

Test #1: 0.168000 s
Test #2: 0.195000 s
Test #3: 0.192000 s

Test #1: 0.166000 s
Test #2: 0.197000 s
Test #3: 0.199000 s

Test #1: 0.184000 s
Test #2: 0.198000 s
Test #3: 0.199000 s

Test #1: 0.167000 s
Test #2: 0.202000 s
Test #3: 0.207000 s

I'm posting this question because I found these results peculiar and absolutely unexpected:

*

*Expected test #2 to be the fastest as it does not use critical section as test #1 does;

*Expected test #3 to be the slowest as it does not really utilize dynamic scheduling, but rather relies on static distribution of jobs (which is done manually);

*Could have never expected that test #2 would be roughly equivalent to test #3 and sometimes even worse.

The questions are:

*

*Am I missing anything?

*Could you explain the test results?

*Do you have a better idea of parallelization here?

A:

*Do you have a better idea of parallelization here?

You might try imitating schedule(static,1) of an OpenMP loop, i.e. instead of processing a big chunk of successive iterations, a thread processes iterations with thread_count stride. Here is the code:
void test4(map<int, vector<int> >& m) {
  double time = omp_get_wtime();

#pragma omp parallel
  {
    int thread_count = omp_get_num_threads();
    int thread_num = omp_get_thread_num();
    size_t map_size = m.size();
    map<int, vector<int> >::iterator it = m.begin();
    std::advance(it, thread_num);

    for (int i = thread_num; i < map_size; i+=thread_count) {
      vector<int>& v = it->second;

      for (size_t j = 0; j < v.size(); ++j) {
        v[j] = j;
      }

      if( i+thread_count < map_size ) std::advance(it, thread_count);
    }
  }

  printf("Test #4: %f s\n", (omp_get_wtime() - time));
}

schedule(static,1) provides better load balancing than schedule(static) in case the amount of work is increasing or decreasing over the iteration space. This is the case for your test workload. And in case the amount of work per iteration is random, these two strategies should on average give the same balancing.
Another variant is to imitate schedule(dynamic) with the help of an atomic counter. The code:
void test5(map<int, vector<int> >& m) {
  double time = omp_get_wtime();
  int count = 0;
#pragma omp parallel shared(count)
  {
    int i;
    int i_old = 0;
    size_t map_size = m.size();
    map<int, vector<int> >::iterator it = m.begin();

#pragma omp atomic capture
    i = count++;

    while (i < map_size) {
      std::advance(it, i-i_old);
      vector<int>& v = it->second;

      for (size_t j = 0; j < v.size(); ++j) {
        v[j] = j;
      }

      i_old = i;
#pragma omp atomic capture
      i = count++;
    }
  }

  printf("Test #5: %f s\n", (omp_get_wtime() - time));
}

in a loop, a thread decides how much it should advance its local iterator over the map. The thread first atomically increments the counter and takes its previous value, thus obtaining the iteration index, then advances the iterator by the difference between the new index and the previous one. The loop repeats until the counter is increased above the map size.


text:
Q: Is it possible to repeat an image (pattern) in SVG format in Flutter? final kBackgroundImage = Image.asset(
  'assets/images/bg.png',
  repeat: ImageRepeat.repeat,
  height: double.infinity,
  width: double.infinity,
);

To do something like this with a SVG background image?


text:
Q: Error netfx.x86$IdentityHost failed to start while launching vs ide I am getting this error and it is really annoying.
I can't use visual studio ide because of it.
I have tried updating vs22.
I have tried using the repair option. (twice)
I have tried reinstalling vs22.
Nothing worked.
And I tried searching for a solution online, it seems I am the only one facing this problem.
I have used vs22 for more than 3months now, and this error only showed up like last week.
I don't know how to provide more information about this error, if I missed anything please let me know.
I would appreciate any suggestion!
Could not start visual studio due to an error.
StreamJsonRpcRemotelnvocationException:
Failed to start host 'netfx.x86$identityHost'. Host exited with exit code '-532462766'. (Errorkind: HostExited HResult: 80131500)

Error

A: Had the same issue and checked the logs.
There was a machine.config misconfiguration, in my case it was related to an Oracle driver.
I'm using a windows machine and found the logs for these at "%temp%\servicehub\logs".


text:
Q: Is there an event for when an event gets/loses listeners?
Possible Duplicate:
Is it possible to subscribe to event subscriptions in C#?

Searching for information about event events isn't easy. I'm just hoping that it's not because it can't be done. I'm just hoping that the answer is "there's an event for that," or some other means.
I'm dealing with an event where listening for the event is comparatively expensive. (A watch has to be put upon it in another system which I'm tying into, involving keeping track of which things to keep track of and COM overhead.)
Therefore, I don't really want to be watching for the event unless I know that something wants it.
The simple way of doing it is like this:
public class MyThing
{
    public delegate void MyEventHandler(object sender, MyEventArgs ea);
    public event MyEventHandler Change;

    public void StartWatching()
    {
        ...
    }

    public void StopWatching()
    {
        ...
    }
}

This is used in this manner:
var thing = new MyThing();
thing.Change += this.thing_Change
thing.StartWatching();

thing.Change -= this.thing_Change
thing.StopWatching();  // Hopefully nothing else is watching...

But this isn't as elegant as I'd like. I could do it with replacing thing.Change += x with thing.StartWatching(x), which would then start watching, and the converse would check if Change == null, but I'd like it if it could be done with the full elegance of the event model.

A: Sounds like a custom event accessor might be what you are looking for.
int count = 0;

event EventHandler MyThing.Change
{
    add
    {
        lock (Change)
        {
            if (count == 0)
            {
                StartWatching();
            }

            count++;
            Change += value;
        }
    }
    remove
    {
        lock (Change)
        {
            count--;
            if (count == 0)
            {
                StopWatching();
            }

            Change -= value;
        }
    }
}

A: Try to declare you event as property and use add/remove accessors
class YourClass
{
    public event EventHandler<EventArgs>  MyEvent
    {
        add
        {
            // Add new subscriber code here
        }

        remove
        {
            // Remove subscriber code here
        }
    }
}

A: You can override the add/remove methods for the event and do the work there.
public class MyThing
{
    public delegate void MyEventHandler(object sender, MyEventArgs ea);

    private MyEventHandler _change;
    public event MyEventHandler Change
    {
       add
      {
          var previousChange = _change;
          _change += value;
          if (previousChange == null)
          {
             StartWatching();
          }
       }
       remove
       {
          _change -= value;
          if (_change == null)
          {
             StopWatching();
          }
       }
    }

    public void StartWatching()
    {
        ...
    }

    public void StopWatching()
    {
        ...
    }
}

Currently, this is not thread-safe but you can easily make it so.


text:
Q: JLabel doesnt appear Im having this problem where my Label2 which is assigned to be a text doesn't appear on the Jframe, even though I added it. Im assuming the other Labels which I set as images are overlaping it? If that is the problem how would I go upon fixing it?
import java.awt.Dimension;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;

public class Generator extends JFrame {

    private static final long serialVersionUID = 1L;

    /**
     * Launch the application.
     */
    public static void main(final String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    final Generator frame = new Generator();
                    frame.setVisible(true);
                } catch (final Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public Generator() {
        /*
         * @Images/Text
         */
        final ImageIcon icon = new ImageIcon("data/hover_a.png");
        final JLabel label = new JLabel(icon);

        final ImageIcon icon1 = new ImageIcon("data/background.png");
        final JLabel label1 = new JLabel(icon1);

        final ImageIcon img = new ImageIcon("data/icon.png");

        final JLabel label2 = new JLabel("Test Text");

        /*
         * @Image/Text Bounds
         */
        label.setBounds(24, 266, 240, 40);
        label1.setBounds(0, 0, 289, 330);
        label2.setBounds(0, 0, 80, 15);

        /*
         * @Image Hovers
         */
        label.addMouseListener(new MouseAdapter() {

            @Override
            public void mouseEntered(final MouseEvent evt) {
                label.setIcon(new ImageIcon("data/hover_b.png"));
            }

            @Override
            public void mouseExited(final MouseEvent evt) {
                label.setIcon(new ImageIcon("data/hover_a.png"));
            }

        });

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setPreferredSize(new Dimension(295, 358));
        setTitle("test");
        getContentPane().setLayout(null);
        setResizable(false);
        setVisible(true);
        setIconImage(img.getImage());
        getContentPane().add(label);
        getContentPane().add(label1);
        getContentPane().add(label2);
        pack();
    }
}

A: From reading your code, it appears that you are trying to layer images on top of each other.  This would be much better achieved through the use of customer panels with custom painting
Have a look at the Performing Custom Painting lesson & 2D Graphics Trail
Without know precisely what you want to achieve, I would create a background panel that paints the background and then I would use a layout manager to layout the two other icons (personally, I used a GridBagLayout, but it might be a little over kill for you needs)
I would also familiarise your self with the painting order of components

A: You're calling setVisible(true) before adding all your components. Don't do this. The orde is:

*

*add your components

*call pack()

*call setVisible(true)

*if later you make changes then call revalidate() on the container, then repaint()


text:
Q: What is Business Process Management software? I'm in a position to write something along the lines of business process management (BPM) software for a small to mid-sized company, but I have no clue about the design goals, and patterns I can adapt for typical BPM.
What defines BPM and are there any typical approaches to it? How do I learn more about it?

A: I am a little confused as to exactly what you are trying to achieve. You don't just wake up one day and decide you want to write some BPM software - you must have a reason for doing so, and this reason is your design goal. BPM is a very wide ranging concept that covers many things - what particular aspect are you targeting?
And why do you feel the need to create yet another BPM suite? Is there something in current suites you do not like? Do you feel they are too bloated?
Your reason for writing the BPM is your design goal. Clearly define what these are, then you can begin looking at design patterns and start to look at what approach you are going to take to achieve these goals.

A: http://www.bpm.com/
The articles there seem like a solid start. I'd particularly recommend the "Getting Started with BPM" ones to establish the fundamentals. Key points they cover:

*

*Your first process should be a core business process that impacts how workers do their critical daily tasks.

*In the waterfall model, the system delivered wasn't quite what the business was looking for, but often ended up being what they were stuck with since a lot of work had gone into the creation of the system. In particular, the business process that represents how they actually get their work done could be incorrect, requiring them to use manual workarounds in order to implement the process that they need.

*People need to understand what's in it for them to switch to the new application and related procedures, and they need to be able to do so with a minimum of disruption to their day-to-day operation.

*Frederick Taylor vs. Peter Drucker

and so on.
Before implementing it, make sure you fully understand what it is.


text:
Q: TOP N problem with GROUP BY clause The problem: I need to find all active [GiftPledges] that have the last three [GiftDetails] have a zero amount.
SELECT gp.PledgeId FROM GiftPledge gp
      INNER JOIN GiftDetail gd ON gp.PledgeId = gd.PledgeId
      WHERE gp.PledgeStatus = 'A'
      GROUP BY PledgeId
      HAVING COUNT(PledgeId) >= 3

Now, I have all my [GiftPledges] that have at least three [GiftDetails].
SELECT TOP 3 gdi.Amt FROM GiftDetail gdi
      INNER JOIN GiftHeader ghi ON gdi.GiftRef = ghi.GiftRef
      WHERE gdi.PledgeId = gp.PledgeId
      ORDER BY ghi.GDate DESC

This gives me the three most recent [GiftDetails] associated with a given [GiftPledge].  The problem is that I don't know how to sum the second query and have it be a part of the WHERE clause in the first query.
I found this article about "Top n per Group" and that seems like the direction I need to be headed, but I'm not sure I'm on the right track.
Any help, clarifications or suggestions would be greatly appreciated.

A: SELECT gp.PledgeId FROM GiftPledge gp
      INNER JOIN GiftDetail gd ON gp.PledgeId = gd.PledgeId
      WHERE gp.PledgeStatus = 'A'
      GROUP BY PledgeId
      HAVING COUNT(PledgeId) >= 3
AND
GP.PledgeID in (
SELECT PledgeID From
(
SELECT TOP 3 gp.PledgeID, gdi.Amt  FROM GiftDetail gdi
      INNER JOIN GiftHeader ghi ON gdi.GiftRef = ghi.GiftRef
      WHERE gdi.PledgeId = gp.PledgeId
      ORDER BY ghi.GDate DESC
) x_amt
Group By PledgeID
Having SUM(AMT) ) x_sum = 0

something like that anyway.


text:
Q: Detect if snake touches apple Ruby2d I am right now creating a snake game in ruby 2d and need a way for the computer to detect when the snake touches the apple.
I have found nothing on this topic as the ruby2d community is fairly small.

A: You are gonna want to write a function that returns true whenever snake has the same xy-coordinates as the apple.
Let's suppose your apple a has member variables x and y. The snakes head s also has its current x and y coordinates saved in its member variables x and y.
def hit(a, s)
    return a.x == s.x && a.y == s.y
end

So in your gameloop always call hit(a, s) and do what you need to do based on the boolean outcome of the function.


text:
Q: Wifi not working on Ubuntu Dual Boot with windows 8.1 ( ASUS X550LD ) Hey guys i recently dual booted Windows 8 and Ubuntu 14.04 LTS on my laptop ASUS X550LD. The dual boot works perfectly but wifi doesnt connect in Ubuntu.
It connects on Windows 8 perfectly. Any help on this would be greatly appreciated.
3:00.0 Network controller [0280]: Broadcom Corporation BCM43142 802.11b/g/n [14e4:4365] (rev 01)
 Subsystem: Lite-On Communications Inc Device [11ad:6605]
 Kernel driver in use: bcma-pci-bridge

A: If you have a wired internet connection just run in a terminal
sudo apt-get install bcmwl-kernel-source


text:
Q: Setting Environment Variable from Eclipse vs. System I am using the Gurobi Optimizer, for which I need to set two environment variables: LD_LIBRARY_PATH and GRB_LICENSE_FILE.
If I set the variables using Eclipse (Run As --> Run Configuration --> Environment), everything works correctly. If I set the variables through the system (using export in Linux), I get the error
no GurobiJni46 in java.library.path

Any ideas why this happens and how to fix this?
In the end, I want to run a web application in Tomcat, which would require those variables set correctly.

A: In the case where you have set the environment variable using export are you then running your application from inside Eclipse or are you running your application from the command line?
The launcher for Eclipse usually explicitly sets the path using the command line switch -Djava.library.path which would overwrite what you have set in the environment.
If you set the LD_LIBRARY_PATH before running Tomcat it would work, provided that Tomcat doesn't override it in one of its start-up scripts!


text:
Q: Calling a WebMethod using jQueryAjax "GET" i have a ajax request which works well using "POST" but when used "GET" it gives me the following error,
{"Message":"An attempt was made to call the method \u0027GetSomething\u0027
using a GET      request, which is not allowed.","StackTrace":" at
System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData
methodData, HttpContext context)\r\n at
System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context,
WebServiceMethodData methodData)","ExceptionType":"System.InvalidOperationException"}

so here is my code, on the client side,
function test() {
        $.ajax({
            url: "Default4.aspx/GetSomething",
            type: "GET",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            success: function (res) { debugger; alert(res.d); },
            error: function (res) { debugger; alert("error"); }
        });
    }

on the server side,
[WebMethod]
public static string GetSomething()
{
    return "got something";
}

any reason why i am getting error when used "GET" ??

A: If you want to invoke it using GET, you need to add:
[WebMethod]
[ScriptMethod(UseHttpGet=true)]
....

A: Another Ways: You can add it in config File
<system.web>
    ...
    <webServices>
        <protocols>
              <add name="HttpGet"/>
        </protocols>
    </webServices>
    ...
</system.web>

A: you should add the following code before the  tag in Web .config file.
<location path="webservice.asmx">
  <system.web>
    <webServices>
      <protocols>
        <add name="HttpGet"/>
        <add name="HttpPost"/>
      </protocols>
    </webServices>
  </system.web>
</location>


text:
Q: How to incorporate time dimension in a recommender engine? I have very long history of user behaviour, when they choose to buy one of the 50 products. I want to take in account that if a user bought product1 two years ago and product2 yesterday, second purchase would be more relevant to the recommended items, than first one. What is the proper way to do so?

A: Dynamic recommender systems is a right term to google for. In the discussion above someone recommended the paper 'Collaborative filtering with temporal dynamics' by Yehuda Koren , which helped me a lot to understand the subject.


text:
Q: JavaScript подключение к серверу Мне известен метод XMLHttpRequest.
Дело в том, что он общается с сервером на протоколе http.
Мне же нужно отправлять и получать запросы/ответы в произвольной форме.
Чтобы было понятнее:
Для курсовой работы я пишу определенную программу на php. Так же, мне требуется на том же php написать сервер. С этим проблем нет.
А так же стоит задача о собственном протоколе этой программы.
Из-за того, что клиентской средой необходимо сделать браузер (благо его хоть писать не надо. Или надо?) Встает вопрос, а можно ли на js общаться с сервером с помощью произвольного протокола, и если можно, то каким образом?
Заранее спасибо за ответы, знатоки.

A: Для решения Вашей задачи по сути вариантов то и нет. Вам необходимо смотреть в сторону websocket. Передавать сможете в произвольном виде любые данные хоть текст, хоть бинарные. Для php (да и любого другого языка) без проблем найдете уже готовые реализации и примеры websocket-сервера. Для пробы пера и тестов можно первоначально обойтись без сервера и использовать тестовые эхо-сервера (типа такого).


text:
Q: Where to find the Record type listed in Current Data Storage Usage? I tried to understand the Record Type in the "Current Data Storage Usage" list view. I took that names of the below record types and searched in Account object to see if there are any record types in that name exists. I didn't find a one. Second, I don't know what is Message Logs, etc. Am I doing anything wrong here?
Account Sales Summary By Year
Message Logs
Product Unit of Measure Conversions

A: The nomenclature is a bit confusing, considering we have a feature called Record Types, but Storage Usage does not refer to that feature. It's the type of the record involved, commonly called an sObject type. You have objects called "Account Sales Summary By Year", "Message Logs", etc. These appear to be custom objects. Each custom object record consumes 2KB of space (500 per MB, 500,000 per GB); some standard objects have different space requirements. These types are directly found in Object Manager in Lightning Setup, and under Setup > Create > Objects in Classic Setup.


text:
Q: Butter Knife syncing problems Hi been having problems with getting butter knife setup. not sure where im going wrong as if tried multiple solutions but with no luck. Any help would be greatly appreciated.
below is the build project level
buildscript {
repositories {
    google()
    jcenter()
    mavenCentral()
}
dependencies {
    classpath 'com.android.tools.build:gradle:3.0.1'
    classpath 'com.jakewharton:butterknife-gradle-plugin:8.8.1'

}

the module level
apply plugin: 'com.android.application'
apply plugin: 'com.jakewharton.butterknife'
apply plugin: 'android-apt'

android {
compileSdkVersion 26
defaultConfig {
    applicationId "com.example.cormac.gymappproject"
    minSdkVersion 15
    targetSdkVersion 26
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner
 "android.support.test.runner.AndroidJUnitRunner"
      }
   buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'),
  'proguard-rules.pro'
                 }
              }
         }

    dependencies {
          implementation fileTree(dir: 'libs', include: ['*.jar'])
          implementation 'com.android.support:appcompat-v7:26.1.0'
          implementation 'com.android.support.constraint:constraint-
    layout:1.0.2'
          testImplementation 'junit:junit:4.12'
           androidTestImplementation 'com.android.support.test:runner:1.0.1'
           androidTestImplementation
        'com.android.support.test.espresso:espresso-core:3.0.1'
       compile 'com.jakewharton:butterknife:8.8.1'
       annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
       }

 [1]: https://i.stack.imgur.com/csnSd.png


text:
Q: DataGrip stuck on "connecting to database..." I try to connect to Redshift Using JetBrain DataGrip, after I fill in the datasource information (host, db, username, password etc) and try Test Connection I saw that there is a background task spawn up and prompts "Connecting to database..." and stuck there forever.
I'm able to connect with SQL WorkbenchJ with same datasource information.
Has anyone encounter this issue?

A: It turns out I have this line in my host file:
127.0.0.1   myhostname.xxx.xxxxxx.com

I change it to:
127.0.0.1   localhost

It's working now.


text:
Q: Differ IOutputFormatter per endpoint in ASP.NET Core 6 I have a legacy ASP.NET Web API 2 app which must be ported to ASP.NET Core 6 and it has the following behaviour:

*

*Some controllers return responses in Pascal-case Json

*Some controllers return responses in camel-case Json

*All controllers have the same authentication/authorization, but they return different objects using different serializers for 401/403 cases.

In ASP.NET Web API 2 it was easily solved with IControllerConfiguration (to set the formatter for a controller), AuthorizeAttribute (to throw exceptions for 401/403), ExceptionFilterAttribute to set 401/403 status code and response which will be serialized using correct formatter.
In ASP.NET Core, it seems that IOutputFormatter collection is global for all controllers and it is not available during UseAuthentication + UseAuthorization pipeline where it terminates in case of failure.
Best I could come up with is to always "succeed" in authentication / authorization with some failing flag in claims and add IActionFilter as first filter checking those flags, but it looks very hacky.
Is there some better approach?
Update1:
Implementing different output formatters for IActionResult from controller or IFilter (including IExceptionFilter) is not very difficult.
What I want is to be able to either set IActionResult or use IOutputFormatter related to Action identified by UseRouting for Authentication/Authorization error or IAuthorizationHandler, but looks like all those auth steps are invoked before either ActionContext or IOutputFormatter is invoked.
So 2 approaches I see now:

*

*hack auth code to "always pass" and handle HttpContext.Items["MyRealAuthResult"] object in IActionFilter

*expose V1OutputFormatter/V2OutputFormatter in a static field and duplicate selection logic in HandleChallengeAsync/HandleForbiddenAsync based on to what controller/action it was routed from UseRouting step.

Here is sample app that uses auth and has 2 endpoints:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<IConfigureOptions<MvcOptions>, MvcOptionsSetup>();
builder.Services.AddAuthentication(options =>
{
    options.AddScheme<DefAuthHandler>("defscheme", "defscheme");
});
builder.Services.AddAuthorization(options =>
    options.DefaultPolicy = new AuthorizationPolicyBuilder("defscheme")
        .RequireAssertion(context =>
            // false here should result in Pascal case POCO for WeatherForecastV1Controller
            // and camel case POCO for WeatherForecastV2Controller
            context.User.Identities.Any(c => c.AuthenticationType == "secretheader"))
        .Build())
    .AddSingleton<IAuthorizationMiddlewareResultHandler, AuthorizationResultHandler>();
builder.Services.AddControllers();

var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();

public class AuthorizationResultHandler : IAuthorizationMiddlewareResultHandler
{
    private readonly AuthorizationMiddlewareResultHandler _handler;
    public AuthorizationResultHandler()
    {
        _handler = new AuthorizationMiddlewareResultHandler();
    }

    public async Task HandleAsync(RequestDelegate next, HttpContext context, AuthorizationPolicy policy, PolicyAuthorizationResult authorizeResult)
    {
        // Can't set ActionContext.Response here or use IOutputFormatter
        await _handler.HandleAsync(next, context, policy, authorizeResult);
    }
}

public class DefAuthHandler : AuthenticationHandler<AuthenticationSchemeOptions>
{
    public DefAuthHandler(IOptionsMonitor<AuthenticationSchemeOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock)
        : base(options, logger, encoder, clock) { }

    protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        var claims = new List<ClaimsIdentity>();
        if (Request.Headers.ContainsKey("secretheader")) claims.Add(new ClaimsIdentity("secretheader"));
        return AuthenticateResult.Success(new AuthenticationTicket(new ClaimsPrincipal(claims), "defscheme"));
    }
}

public class MvcOptionsSetup : IConfigureOptions<MvcOptions>
{
    private readonly ArrayPool<char> arrayPool;
    private readonly MvcNewtonsoftJsonOptions mvcNewtonsoftJsonOptions;
    public MvcOptionsSetup(ArrayPool<char> arrayPool, IOptions<MvcNewtonsoftJsonOptions> mvcNewtonsoftJsonOptions)
    {
        this.arrayPool = arrayPool;
        this.mvcNewtonsoftJsonOptions = mvcNewtonsoftJsonOptions.Value;
    }

    public void Configure(MvcOptions options)
    {
        options.OutputFormatters.Insert(0, new V1OutputFormatter(arrayPool, options, mvcNewtonsoftJsonOptions));
        options.OutputFormatters.Insert(0, new V2OutputFormatter(arrayPool, options, mvcNewtonsoftJsonOptions));
    }
}

public class V1OutputFormatter : NewtonsoftJsonOutputFormatter
{
    public V1OutputFormatter(ArrayPool<char> charPool, MvcOptions mvcOptions, MvcNewtonsoftJsonOptions? jsonOptions)
        : base(new JsonSerializerSettings { ContractResolver = new DefaultContractResolver() }, charPool, mvcOptions, jsonOptions) { }

    public override bool CanWriteResult(OutputFormatterCanWriteContext context)
    {
        var controllerDescriptor = context.HttpContext.GetEndpoint()?.Metadata.GetMetadata<Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor>();
        return controllerDescriptor?.ControllerName == "WeatherForecastV1";
    }
}

public class V2OutputFormatter : NewtonsoftJsonOutputFormatter
{
    public V2OutputFormatter(ArrayPool<char> charPool, MvcOptions mvcOptions, MvcNewtonsoftJsonOptions? jsonOptions)
        : base(new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }, charPool, mvcOptions, jsonOptions) { }

    public override bool CanWriteResult(OutputFormatterCanWriteContext context)
    {
        var controllerDescriptor = context.HttpContext.GetEndpoint()?.Metadata.GetMetadata<Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor>();
        return controllerDescriptor?.ControllerName == "WeatherForecastV2";
    }
}

[ApiController]
[Authorize]
[Route("v1/weatherforecast")]
public class WeatherForecastV1Controller : ControllerBase
{
    [HttpGet]
    public IActionResult Get()
    {
        // This must be Pascal case
        return Ok(new WeatherForecast() { Summary = "summary" });
    }
}

[ApiController]
[Authorize]
[Route("v2/weatherforecast")]
public class WeatherForecastV2Controller : ControllerBase
{
    [HttpGet]
    public IActionResult Get()
    {
        // This must be camel case
        return Ok(new WeatherForecast() { Summary = "summary" });
    }
}

A: If there is no way to configure controllers independently, then you could use some middleware to convert output from selected controllers that meet a path-based predicate.
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.MapWhen(ctx => ctx.Request.Path.Containes("v2/"), cfg =>
{
   app.UseMiddleware<JsonCapitalizer>();
});
app.Run();

And then create a JsonCapitalizer class to convert output from any path that contains "v2/".  Note, this middleware will not run if the predicate in MapWhen is not satisfied.
public class JsonCapitalizer
{
    readonly RequestDelegate _nextRequestDelegate;

    public RequestLoggingMiddleware(
        RequestDelegate nextRequestDelegate)
    {
        _nextRequestDelegate = nextRequestDelegate;
    }

    public async Task Invoke(HttpContext httpContext)
    {
        await _nextRequestDelegate(httpContext);

        // Get the httpContext.Response
        // Capitalize it
        // Rewrite the response
    }
}

There may be better ways, but that's the first that comes to mind.
The following link will help with manipulation of the response body:
https://itecnote.com/tecnote/c-how-to-read-asp-net-core-response-body/

A: I also faced such a problem in ASP Core 7 and ended up with writing an attribute.
So the attribute will be applied on each Action where the response type has to be converted. You can write many an attribute for camelcase response and another attribute for pascalcase. The attribute will look like below for CamelCase
public class CamelCaseAttribute : ActionFilterAttribute
{
    private static readonly SystemTextJsonOutputFormatter formatter = new SystemTextJsonOutputFormatter(new()
    {
        ReferenceHandler = ReferenceHandler.IgnoreCycles,
        PropertyNamingPolicy = JsonNamingPolicy.CamelCase
    });

    public override void OnActionExecuted(ActionExecutedContext context)
    {
        if (context.Result is ObjectResult objectResult)
        {
            objectResult.Formatters
                .RemoveType<NewtonsoftJsonOutputFormatter>();
            objectResult.Formatters.Add(formatter);
        }
        else
        {
            base.OnActionExecuted(context);
        }
    }
}

And on the Contoller Action you can use it like below
 [CamelCase]
    public async IAsyncEnumerable<ResponseResult<IReadOnlyList<VendorBalanceReportDto>>> VendorBalanceReport([FromQuery] Paginator paginator, [FromQuery] VendorBalanceReportFilter filter, [EnumeratorCancellation] CancellationToken token)
    {
        var response = _reportService.VendorBalanceReport(paginator, filter, token);

        await foreach (var emailMessage in response)
        {
            yield return emailMessage;
        }
    }