text:
Q: Would I be in violation of these icons free license on my Android application? Since there isn't yet a Q&A site for legal issues and since this is related to an Android app, I'm posting it here, instead of Stack Overflow cause this is not code related.
I want to separate this question into 3 sub-questions which are all related though. These questions are about the Free, Commercial and Extended licenses of DryIcons.
1) Generally speaking, would I be in violation of the free license if I used some icons in my paid version of an Android app? I'm a bit confused... The free license has the following in the "Grant of Rights" section:

b. You may use the Licensed Material in any personal or commercial
  project unlimited number of times according to the DryIcons Free
  License Terms and Conditions;

From this I take that yes, I can use their icons in my paid Android app. But then I read this in the commercial license under "Restrictions":

e. Licensee may not use Licensed Material in electronic items for
  resale, such as website templates, electronic devices (i.e. computer,
  iPhone, phones, etc.) software applications, document templates,
  wallpapers, screensavers, e-cards or similar products that Licensee
  intend to sell or distribute;

Which one assumes the extended license is the one we need for a paid app. But isn't this a little bit contradictory? Doesn't that point in the free license allows me to simply use their work in paid apps?
2) Now, let's assume I really need to buy a commercial/extended license to use their work on my paid/commercial Android app, something I'll be in fact selling to an unlimited number of users.
Would I fall under the commercial/extended or the free license if I used In-app Billing in my Android app? With In-app billing I wouldn't be selling their work at all. My app would be free with a bunch of features and I would be also using their work. But since my app is free I'm also free to use their work as long as I give proper credits with a link to their website as they state in the free license (no problem doing that, I'm all for it). Then, with In-app Billing I would actually be selling extra features to my app (by providing an upgrade to a "Pro" version), not their work.
Do you think I would be in violation of the free license like this?
3) And now a similar situation as the previous point. What if, instead of In-app Billing, I would have 2 apps. One completely free using their work as the free license allows me. And another which is nothing more than an "unlock app", something that would unlock extra features on the free app. The "unlock app" is the real paid app and this app does not use their work at all.
Do you think this is exactly the same situation as in the previous point and that I'm just playing with semantics? What's your opinion on that?
Do you think I would be in violation of the free license like this?

A: The exact quote from free licence is that

You may use the Licensed Material in any personal or commercial project unlimited number of times according to the DryIcons Free License Terms and Conditions

so you look back to the section titled "Terms and Conditions" and it says:

You may use the Licensed Material in a publicly accessible web site, web application or any form of presentation publicly accessible through the World Wide Web [...]

so it does not apply to application you put on android market.
The commercial also explicitly states what it does apply to and software is not in that, so the commercial does not apply either.
The extended explicitly says:

Permitted Uses include the following:

*

*Electronic devices (i.e. computer, iPhone, phones, etc.) software applications

so you need to obtain extended license.

A: IANAL, but ...
From what you say it appears the free license can be used as long as the project is not commercially distributed (e.g. website for your own business is allowed, but website for someone else's business is not allowed).
Regarding your third question, if their license says "project", they mean "project", not "application". So if you have two apps, one free and one paid, then those would both form a commercial project.
You should consider paying for the extended license anyway, regardless of whether you need it or not, just to show the appreciation for the icon set.


text:
Q: Magento 2 - automatic product information transfer (rest, soap?) I have multiple Magento 2 websites and i do not want to use CSV or XML to update my product details. I would like to develop a feed or other connection to automatically update the product information from the main (parent) website to the other (child) websites.
Which technology would be the best to set this up? Rest? I am looking for some suggestions to point me in the right direction.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Inserting characters before whatever is on a line, for many lines I have been looking at regular expressions to try and do this, but the most I can do is find the start of a line with ^, but not replace it.
I can then find the first characters on a line to replace, but can not do it in such a way with keeping it intact.
Unfortunately I don´t have access to a tool like cut since I am on a windows machine...so is there any way to do what I want with just regexp?

A: Did you try replacing the regular expression ^ with the text you want to put at the start of each line? Also you should use the multiline option (also called m in some regex dialects) if you want ^ to match the start of every line in your input rather than just the first.
string s = "test test\ntest2 test2";
s = Regex.Replace(s, "^", "foo", RegexOptions.Multiline);
Console.WriteLine(s);

Result:
footest test
footest2 test2

A: Use notepad++. It offers a way to record an sequence of actions which then can be repeated for all lines in the file.

A: I used to program on the mainframe and got used to SPF panels.  I was thrilled to find a Windows version of the same editor at Command Technology.  Makes problems like this drop-dead simple.  You can use expressions to exclude or include lines, then apply transforms on just the excluded or included lines and do so inside of column boundaries.  You can even take the contents of one set of lines and overlay the contents of another set of lines entirely or within column boundaries which makes it very easy to generate mass assignments of values to variables and similar tasks.  I use Notepad++ for most stuff but keep a copy of SPFSE around for special-purpose editing like this.  It's not cheap but once you figure out how to use it, it pays for itself in time saved.


text:
Q: How do I disallow Jenkins admin from modifying through the UI but still allow him to run script console? My Jenkins instance is fully configured through Jenkins configuration as code plugin.
I set all the authorizations as recommended by:
https://www.jenkins.io/blog/2020/05/25/read-only-jenkins-announcement/
So I don't want anyone (including admins) to modify parameters in the UI
But I still want to allow admins to run script console.
How can I do that?


text:
Q: Surjective map in Galois cohomology? Let $p$ be a prime number, $\mathbb{F}_p$ the field with $p$ element and $\omega$ the mod $p$ cyclotomic character. Let $K$ be a finite extension of $\mathbb{Q}_p$ (the field of $p$-adic numbers) and denote by $G_K$ the absolute Galois group of $K$.  Let $V$ be a $2$ dimensional $\mathbb{F}_p$-representation of $G_K$ which is a non-split extension of $\omega$ by $\omega$. So we have a short exact sequence $1 \to \omega \to V \to \omega \to 1$ of $\mathbb{F}_p$-representations inducing a map in Galois cohomology : $H^1(G_K, V) \to H^1(G_K, \omega)$.
Is this map surjective ? If not, can we describe its image (in terms of  peu ramifiées or très ramifiées extensions) ?
EDIT : Well it turns out this map is not surjective : the map $H^2(G_K, V) \to H^2(G_K, \omega)$ is an isomorphism (it is surjective because $H^3 = 0$ and those are 1 dimensional vector spaces (it is easily seen using Tate local duality)). It implies that the map $H^1(G_K,\omega) \to H^2(G_K, \omega)$ is surjective with non trivial kernel. So I guess the only question it remains to answer is if it is possible to describe this non trivial kernel.


text:
Q: Xcode5.1.1 and Xcode6 beta7 iOS7.1 64-bit [Allocator] Allocator invalid, falling back to malloc [Allocator] Mapping failed %d
[Allocator] Allocator invalid, falling back to malloc
[Allocator] Allocator invalid, falling back to malloc
[Allocator] Allocator invalid, falling back to malloc
[Allocator] Allocator invalid, falling back to malloc
[Allocator] Allocator invalid, falling back to malloc
[Allocator] Allocator invalid, falling back to malloc
[Allocator] Allocator invalid, falling back to malloc
[Allocator] Allocator invalid, falling back to malloc
[Allocator] Allocator invalid, falling back to malloc
[Allocator] Allocator invalid, falling back to malloc
[Allocator] Allocator invalid, falling back to malloc
[Allocator] Allocator invalid, falling back to malloc
[Allocator] Allocator invalid, falling back to malloc
[Allocator] Allocator invalid, falling back to malloc
[Allocator] Allocator invalid, falling back to malloc
[Allocator] Allocator invalid, falling back to malloc
[Allocator] Allocator invalid, falling back to malloc
[Allocator] Allocator invalid, falling back to malloc
[Allocator] Allocator invalid, falling back to malloc
[Allocator] Allocator invalid, falling back to malloc
[Allocator] Allocator invalid, falling back to malloc
[Allocator] Allocator invalid, falling back to malloc
[Allocator] Allocator invalid, falling back to malloc
[Allocator] Allocator invalid, falling back to malloc
[Allocator] Allocator invalid, falling back to malloc
[Allocator] Allocator invalid, falling back to malloc
[Allocator] Allocator invalid, falling back to malloc
[Allocator] Allocator invalid, falling back to malloc
[Allocator] Allocator invalid, falling back to malloc
[Allocator] Allocator invalid, falling back to malloc
[Allocator] Allocator invalid, falling back to malloc

And my app crash!

A: For me, this is an issue with Crashlytics when running a 64-bit Simulator. Crashlytics is aware of the problem and say they're working on it.


text:
Q: Cannot connect to mongodb So I've installed mongo using home brew and I've installed it through npm, so I have the JS driver.
When I run mongo in command line though, I get this -
 MongoDB shell version: 2.2.2
connecting to: test
Thu Jan 24 02:38:26 Error: couldn't connect to server 127.0.0.1:27017 src/mongo/shell/mongo.js:91
exception: connect failed

why is that happening?

A: After you've installed MongoDB, open a terminal window and go to the file path where your MongoDB application is stored e.g c:\MongoDB. Then type mongod and hit enter. This should start this process running. Mongod is the database server that you then access via the mongo shell.
After mongod is running, open a new terminal window and type mongo then hit enter. You should now be up and running. You can test that it's working by typing the following into the mongo shell as an example:
>
>db.names.save({'name':"James"})
>db.names.find()

This should then return the document you have just saved to the database as shown in the example below.
>{"_id" ObjectID:"764tdf763dyf6337fd376","name":"James"}

Read through the documentation and look for tutorials online. 10gen have just started an excellent online course. It's free and started this week so you might still be able to register.


text:
Q: How to ensure I use the correct python version when I have multiple versions of Python installed? I have python 3.7.8 and python 3.10.0 installed. I have a question regarding the dependencies of these two. Is it okay to have this two installed at the same time but in different versions?
Does it make my site-packages conflict with one another?
On my command prompt, when I check my python version it says I am using the recent version, 3.10.0.

A: Having multiple versions on the same machine is perfectly "okay", as long as you understand how to select/use the correct python version, which is the more pertinent and useful question you should be asking yourself.
They would normally be installed in separate locations and would have separate site-packages (from How do I find the location of my Python site-packages directory?):
~$ python3.7 -c 'import site; print(site.getsitepackages())'
['/usr/local/Cellar/python@3.7/3.7.12_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages']

~$ python3.8 -c 'import site; print(site.getsitepackages())'
['/usr/local/Cellar/python@3.8/3.8.12_1/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages']

~$ python3.9 -c 'import site; print(site.getsitepackages())'
['/usr/local/Cellar/python@3.9/3.9.9/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages']

The recommended way however is to not install to these site-packages folder directly and use a virtual environment instead. There are many variations of virtual env packages/tools, but you can start with the Python docs on Virtual Environments if you are not familiar or using one yet.
With virtual environments, you can usually indicate which version of python to use when creating the virtual env, so that whenever you activate that same env, it would use the same version you used to create it.
tmp$ python3.7 -m venv app1
tmp$ source ./app1/bin/activate
(app1) tmp$ python -V
Python 3.7.12
(app1) tmp$
(app1) tmp$ deactivate

tmp$ python3.8 -m venv app2
tmp$ source ./app2/bin/activate
(app2) tmp$ python -V
Python 3.8.12
(app2) tmp$
(app2) tmp$ deactivate

tmp$ python3.9 -m venv app3
tmp$ source ./app3/bin/activate
(app3) tmp$ python -V
Python 3.9.9
(app3) tmp$
(app3) tmp$ deactivate

In the above example, I created 3 virtual environments for 3 hypothetical apps, each using a different Python version. As long as I activate the correct virtual environment, I don't have to think about which version python refers to, as it will use the same version used to create the env. See also How do I check what version of Python is running my script?.
As for installing packages, again, once you have setup the correct virtual environments, doing pip install would ensure it installs only on the site-packages on that environment, and the app running on that env would be able to import that package.
If not using a virtual environment, as I noted in my comment, the answers at Dealing with multiple Python versions and PIP? provide good suggestions on how to ensure you are installing packages for the correct Python version, namely with
$ </path/or/alias/to/specific/python/installation> -m pip install <packages>

$ python3.7 -m pip install "flake8<=3.6"
$ python3.7 -m pip list | grep flake8
flake8             3.6.0
$ ls -H /usr/local/Cellar/python@3.7/3.7.12_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages | grep flake8
flake8
flake8-3.6.0.dist-info
flake8_quotes
flake8_quotes-3.2.0.dist-info

$ python3.9 -m pip install flake8
$ python3.9 -m pip list | grep flake8
flake8           4.0.1
$ ls -H /usr/local/Cellar/python@3.9/3.9.9/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages | grep flake8
flake8
flake8-4.0.1.dist-info

The above example shows 2 different versions of flake8 installed for 2 different versions of Python, each on their own site-packages folder.

But when I run my command prompt and check my python version it says I am using the recent version. The 3.10.0.

This means the system default for python or python3 on your machine points to the 3.10 installation. Mine is set to point to Python 3.9:
tmp$ python3 -V
Python 3.9.9
tmp$ which python3
/usr/local/bin/python3
tmp$ /usr/local/bin/python3 -V
Python 3.9.9

You can:

*

*Manually change the default version

*Setup aliases to the different versions:
tmp$ type python3.7
python3.7 is aliased to `/usr/local/opt/python@3.7/bin/python3'

tmp$ type python3.8
python3.8 is aliased to `/usr/local/opt/python@3.8/bin/python3'

tmp$ type python3.9
python3.9 is aliased to `/usr/local/opt/python@3.9/bin/python3'

*Use a version management tool for switching versions, such as pyenv

A: To add onto Gino Mempin's answer it's also worth noting that in Windows you can quickly switch between versions of Python by editing the PATH environment variable in System Variables under your Environment Variables.
From my experience most people who switch between Python versions are on Linux but for all those people who might be using Windows you can just go to This PC -> Right-click -> Properties -> Advanced System Settings then from System Properties go to the Advanced tab and select Environment Variables to edit PATH. Note you don't have to delete older versions of Python here you can just add other ones and then select to move them above the others to give them priority.
You'll also need to restart your Command Prompt or Powershell after doing this if you had it open and was using Python before editing the environment variables.
After doing this you'll be able to install and manage packages for the current version of Python that has priority.


text:
Q: Windows Media Player SDK: обработать | предотвратить OutOfMemoryException WindowsMediaPlayer WMP = new WindowsMediaPlayer(); //Создаётся WMP
IWMPMediaCollection collection = WMP.mediaCollection; //"Создаётся" коллекция муз. библиотеки WMP
IWMPMedia newMedia = collection.add(path);  //А вот здесь, после 5 тысяч повторений, возникает исключение

Пробовала поймать для принудительной сборки мусора в отдельном методе – не помогло, память по-прежнему переполняется.
Интересны любые соображения и опыт тех, кто работал с этими интерфейсами.


text:
Q: Creating a stream of values while calling async fns? I can't figure out how to provide a Stream where I await async functions to get the data needed for the values of the stream.
I've tried to implement the the Stream trait directly, but I run into issues because I'd like to use async things like awaiting, the compiler does not want me to call async functions.
I assume that I'm missing some background on what the goal of Stream is and I'm just attacking this incorrectly and perhaps I shouldn't be looking at Stream at all, but I don't know where else to turn. I've seen the other functions in the stream module that could be useful, but I'm unsure how I could store any state and use these functions.
As a slightly simplified version of my actual goal, I want to provide a stream of 64-byte Vecs from an AsyncRead object (i.e. TCP stream), but also store a little state inside whatever logic ends up producing values for the stream, in this example, a counter.
pub struct Receiver<T>
where
    T: AsyncRead + Unpin,
{
    readme: T,
    num: u64,
}

// ..code for a simple `new() -> Self` function..

impl<T> Stream for Receiver<T>
where
    T: AsyncRead + Unpin,
{
    type Item = Result<Vec<u8>, io::Error>;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        let mut buf: [u8; 64] = [0; 64];
        match self.readme.read_exact(&mut buf).await {
            Ok(()) => {
                self.num += 1;
                Poll::Ready(Some(Ok(buf.to_vec())))
            }
            Err(e) => Poll::Ready(Some(Err(e))),
        }
    }
}

This fails to build, saying
error[E0728]: `await` is only allowed inside `async` functions and blocks

I'm using rustc 1.36.0-nightly (d35181ad8 2019-05-20) and my Cargo.toml looks like this:
[dependencies]
futures-preview = { version = "0.3.0-alpha.16", features = ["compat", "io-compat"] }
pin-utils = "0.1.0-alpha.4"

A: Answer copy/pasted from the reddit post by user Matthias247:

It's unfortunately not possible at the moment - Streams have to be implemented by hand and can not utilize async fn. Whether it's possible to change this in the future is unclear.
You can work around it by defining a different Stream trait which makes use of Futures like:
trait Stream<T> {
   type NextFuture: Future<Output=T>;

   fn next(&mut self) -> Self::NextFuture;
}

This article and this futures-rs issue have more information around it.

A: You can do it with gen-stream crate:
#![feature(generators, generator_trait, gen_future)]

use {
    futures::prelude::*,
    gen_stream::{gen_await, GenTryStream},
    pin_utils::unsafe_pinned,
    std::{
        io,
        marker::PhantomData,
        pin::Pin,
        sync::{
            atomic::{AtomicU64, Ordering},
            Arc,
        },
        task::{Context, Poll},
    },
};

pub type Inner = Pin<Box<dyn Stream<Item = Result<Vec<u8>, io::Error>> + Send>>;

pub struct Receiver<T> {
    inner: Inner,
    pub num: Arc<AtomicU64>,
    _marker: PhantomData<T>,
}

impl<T> Receiver<T> {
    unsafe_pinned!(inner: Inner);
}

impl<T> From<T> for Receiver<T>
where
    T: AsyncRead + Unpin + Send + 'static,
{
    fn from(mut readme: T) -> Self {
        let num = Arc::new(AtomicU64::new(0));

        Self {
            inner: Box::pin(GenTryStream::from({
                let num = num.clone();
                static move || loop {
                    let mut buf: [u8; 64] = [0; 64];
                    match gen_await!(readme.read_exact(&mut buf)) {
                        Ok(()) => {
                            num.fetch_add(1, Ordering::Relaxed);
                            yield Poll::Ready(buf.to_vec())
                        }
                        Err(e) => return Err(e),
                    }
                }
            })),
            num,
            _marker: PhantomData,
        }
    }
}

impl<T> Stream for Receiver<T>
where
    T: AsyncRead + Unpin,
{
    type Item = Result<Vec<u8>, io::Error>;

    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        self.inner().poll_next(cx)
    }
}


text:
Q: Better design for multiple function call I've written a sudoku validator for an online judge website.
https://www.urionlinejudge.com.br/judge/en/problems/view/1383
My solution works great for the 9 grid sudoku, by verifying if each column row and sudoku 3x3 block contains numbers from 1-9 using a bitset and flipping each bit at the number index.

However, I'm making multiple calls to ValidateOneBlock() specifying the iterators range.
My gut tells me that this approach could be fundamentally better. How can I improve(if possible) my code by not using a big if with many calls to ValidateOneBlock()?
#include <iostream>
#include <sstream>
#include <bitset>

namespace Constants
{
    constexpr int ROW_COL_SIZE = 9;
    const std::string STR_YES = "SIM"; //yes in Portuguese
    const std::string STR_NO = "NAO"; //no in Portuguese
}

template<unsigned int N>
class Sudoku
{
private:
    int m_matrix[N][N] {{0}};
public:
    void ReadRows();
    bool IsValid() const;
private:
    bool ValidateOneBlock(const int& minRowIndex, const int& maxRowIndex, const int& minColIndex, const int& maxColIndex) const;
};

template<unsigned int N>void Sudoku<N>::ReadRows()
{
    for(unsigned int row{0}; row<N; row++)
    {
        static std::string line;
        std::getline(std::cin, line);
        std::istringstream issline(line);

        int readnum {0};
        for(unsigned int i{0}; i<N; i++)
        {
            issline >> readnum;
            m_matrix[row][i] = readnum;
        }
    }
}

template<unsigned int N>bool Sudoku<N>::IsValid() const
{
    //9bit default ctor all zeroes, 000000000
    std::bitset<N> bitRow[N];
    std::bitset<N> bitCol[N];
    for(unsigned int i{0}; i<N; i++)
    {
        for(unsigned int j{0}; j<N; j++)
        {
            bitRow[i].flip(m_matrix[i][j]-1); //bitset index is 0 not 1.
            bitCol[i].flip(m_matrix[j][i]-1);
        }
        if(!bitRow[i].all() || !bitCol[i].all()) {
            return false;
        }
    }

    /* What ValidateOneBlock() does  is verify numbers 1-9 within the Sudoku blocks. These are the indexes
    0-0 0-1 0-2 | 0-3 0-4 0-5 | 0-6 0-7 0-8
    1-0 1-1 1-2 | 1-3 1-4 1-5 | 1-6 1-7 1-8
    2-0 2-1 2-2 | 2-3 2-4 2-5 | 2-6 2-7 2-8
    ---------------------------------------
    3-0 3-1 3-2 | 3-3 3-4 3-5 | 3-6 3-7 3-8
    4-0 4-1 4-2 | 4-3 4-4 4-5 | 4-6 4-7 4-8
    5-0 5-1 5-2 | 5-3 5-4 5-5 | 5-6 5-7 5-8
    ---------------------------------------
    6-0 6-1 6-2 | 6-3 6-4 6-5 | 6-6 6-7 6-8
    7-0 7-1 7-2 | 7-3 7-4 7-5 | 7-6 7-7 7-8
    8-0 8-1 8-2 | 8-3 8-4 8-5 | 8-6 8-7 8-8
    */

    if(N == Constants::ROW_COL_SIZE)
    {
        if( ValidateOneBlock(0, 2, 0, 2) &&
            ValidateOneBlock(0, 2, 3, 5) &&
            ValidateOneBlock(0, 2, 6, 8) &&

            ValidateOneBlock(3, 5, 0, 2) &&
            ValidateOneBlock(3, 5, 3, 5) &&
            ValidateOneBlock(3, 5, 6, 8) &&

            ValidateOneBlock(6, 8, 0, 2) &&
            ValidateOneBlock(6, 8, 3, 5) &&
            ValidateOneBlock(6, 8, 6, 8) )
        {
            return true;
        }
    }

    return false;
}
template<unsigned int N>
bool Sudoku<N>::ValidateOneBlock(const int& minRowIndex, const int& maxRowIndex,
                                 const int& minColIndex, const int& maxColIndex) const
{
    std::bitset<N> bitBlock;
    for(int i=minRowIndex; i<=maxRowIndex; i++){
        for(int j=minColIndex; j<=maxColIndex; j++){
            bitBlock.flip(m_matrix[i][j]-1);
        }
    }
    return bitBlock.all();
}
int main()
{
    int instances {0};
    std::cin >> instances;
    std::cin.clear();
    std::cin.ignore();

    for(int i{0}; i<instances; i++)
    {
        std::cout << "Instancia " << i+1 << "\n";
        Sudoku<Constants::ROW_COL_SIZE> sudokuInstance;
        sudokuInstance.ReadRows();
        if(sudokuInstance.IsValid()) {
            std::cout << Constants::STR_YES;
        } else {
            std::cout << Constants::STR_NO;
        }
        std::cout << "\n\n";
    }

    return 0;
}

A: You essentially have a 3*3 array of blocks so something like this should work:
for ( int row = 0; row < 3; row++ )
{
   for ( int column = 0; column < 3; column++ )
   {
      if (!ValidateOneBlock(row * 3, row * 3 + 2, column * 3, column * 3 + 2))
      {
         return false;
      }
   }
}
return true;

You presumably need another loop to validate the lines:
for ( int i = 0; i < 9; i++ )
{
  if (!ValidateOneBlock(i, i, 0, 8))
  {
    return false;
  }
  if (!ValidateOneBlock(0, 8, i, i))
  {
    return false;
  }
}

A: I have not tested this, but something along the following lines should work, for any N, assuming N is a multiple of 3. Actually I think it is better to parameterize Sudoku on the number of 'blocks' in both dimensions, instead of the number of values along one dimension. That will lift this specific requirement on N. Calculating the Cartesian product (cellCoordinates) is a nice candidate for further generalization.
#include <algorithm>
#include <array>
#include <numeric>

...

template<unsigned int N>
bool Sudoku<N>::IsValid() const
{
  // 9bit default ctor all zeroes, 000000000
  std::bitset<N> bitRow[N];
  std::bitset<N> bitCol[N];
  for (unsigned int i{0}; i < N; i++)
  {
    for (unsigned int j{0}; j < N; j++)
    {
      bitRow[i].flip(m_matrix[i][j] - 1);  // bitset index is 0 not 1.
      bitCol[i].flip(m_matrix[j][i] - 1);
    }
    if (!bitRow[i].all() || !bitCol[i].all())
    {
      return false;
    }
  }

  static_assert(N % 3 == 0, "N should be a multiple of 3");
  std::array<int, N / 3> indices;
  std::iota(indices.begin(), indices.end(), 0);

  std::array<std::pair<int, int>, N> cellCoordinates;
  auto curr = cellCoordinates.begin();
  for (int i : indices)
    for (int j : indices)
      *curr++ = std::pair(i, j);

  return std::all_of(
      cellCoordinates.begin(), cellCoordinates.end(), [this](const auto& c) {
        const int rowStart{c.first * 3};
        const int rowEnd{rowStart + 2};
        const int colStart{c.second * 3};
        const int colEnd{colStart + 2};
        return ValidateOneBlock(rowStart, rowEnd, colStart, colEnd);
      });
}


text:
Q: How to put a bootstrap tab inside a fixed height container? I'm trying to put a bootstrap tab control into a containing div with a fixed height. I have some details below the tab control and when I switch between tabs they jump up and down depending on the contents of each tab.  I want to avoid this so figured Id put the tab control inside a div with a fixed height, but I just cant it to work.
Here is the HTML and CS:
@media (min-width: 768px){
    fixed-height-content {
      min-height: 400px;
      max-height: 400px;
      overflow-y: scroll;
    }
}

        tab stuff in here

    --- stuff here

No matter what, the stuff underneath the fixed height div just moves up and down depending on the contents of each tab. I'm more of a developer than a CSS aficionado. So I'm finding it a difficult problem to solve, can anyone help me out ?


text:
Q: Plotting solution sets of one-dimensional autonomous systems Suppose you have a differential equation describing the evolution of an autonomous system described by $x: \mathbb{R} \rightarrow \mathbb{R}$ (domain = time, range = some scalar quantity):
$$\dot{x} = f_{\alpha\beta\gamma}(x)$$
depending on three parameters $\alpha, \beta, \gamma$, and you are looking for solutions depending on initial values $x_0 = x(0)$.
The result will be a parametrized set of curves $x_{\alpha\beta\gamma x_0}: \mathbb{R}^+ \rightarrow \mathbb{R}$.
How can this set of curves (and its structure) be made visible in the most compelling way, e.g. by showing only (or highlighting in some kind of a heat map) curves for some significant (extremal) parameter sets $\{\alpha\beta\gamma x_0\}$.
Are there heuristics to determine significant parameter sets manually (or even automatically)? And which tools are there (e.g. WolframAlpha, MATLAB) which can be fed with parametrized equations and some predefined parameter sets, and which display in a comprehensible way the "structure" of the solution set, possibly highlighting the predefined curves? (If WolframAlpha is the answer: How to do it?)

The parametrized funtion I have in mind is
$$f_{\alpha\beta\gamma}(x) = \alpha - \beta\min\{1,\gamma x\}$$
with $\alpha, \beta, \gamma > 0, \alpha < \beta$.


text:
Q: How Apache will recognize that a request is from ASP or PHP script? How Apache will recognize that a request is from ASP or PHP script

A: Usually by file extension.
For example in apache you should have lines like that:
<IfModule mod_php5.c>
     <FilesMatch "\.ph(p3?|tml)$">
          SetHandler application/x-httpd-php
     </FilesMatch>
</IfModule>

A: You can look at the HTTP Response header field "Server" which will tell you something like Server: Apache/2.4.1 (Unix)
Furthermore, ASP.NET supplies a non-standard header along the lines of X-Powered-By:ASP.NET
 and I know PHP does the same thing (although I can't find the actual message presently.)  Bottom line is look at the HTTP response headers.
http://en.wikipedia.org/wiki/List_of_HTTP_header_fields
I should add that none of these will tell you with 100% certainty (Unix could be running some other server side language in the former example; custom headers can easily be suppressed or even spoofed on the latter example) but it would give you a fairly confident guess as to what you're looking for.


text:
Q: Jquery, Highcharts enable html exportChart I have some chart with legend
legend: {
        useHTML: true,
        labelFormatter: function () {
            return '
';

            //return this.name.replace(/\d+/g, '');
        }
    }

How can I save it with standart highchart functions? Problem is that HighCHart export saves text but not pictures, what is a reason of problem? P.S. Actually legend looks fine in browser, problem is with exporting chart. Thanks

A: The problem is that the export function of Highcharts connects to their server, so without an internet connection the export function will not work. Therefore I think the function works like this: it sends the data to the server and the server generates the img or pdf and sends back the file for us to save. So, your image will not be sent to the server to be exported, only the text.


text:
Q: sorting map of the key to values with integer and strings I am trying to return the mapping of faces to letters for this die. The faces are identified using the Integer values 1 through 6, and the returned map is sorted on its keys (the face numbers).
My code is as following:
public SortedMap getValueMap() {
    SortedMap<Integer, String> sm = new TreeMap<Integer, String>();

    sm.put(new Integer(1), "A");
    sm.put(new Integer(2), "A");
    sm.put(new Integer(4), "E");
    sm.put(new Integer(3), "E");
    sm.put(new Integer(5), "G");
    sm.put(new Integer(6), "N");
    Set<Entry<Integer, String>> s = sm.entrySet();

    Iterator<Entry<Integer, String>> i = s.iterator();

    for (i=1; i.hasNext();) {
        Map.Entry m = (Map.Entry) i.next();
        int key = (Integer) m.getKey();
        String sValue = (String) m.getValue();

    }
    return "Key :" + key + "  value :" + sValue;

}

A: You don't need to initialize i=1 here. Change it to a while loop
while(i.hasNext())


text:
Q: How to resolve unable to push to GitHub due to "Invalid username or password"? I have been having this issue for a short while. Basically, I was not able to push to a personal repo on GitHub from my work computer using GitBash with https.
Here's the error message
$ git push origin master
Username for 'https://github.com':
remote: Invalid username or password.
fatal: Authentication failed for 'https://github.com/georgeliu1998/mlnd.git/'

Checked out these following threads but they don't seem to be the same situation.

*

*git invalid username or password

*GitHub authentication failing
over https, returning wrong email address

A: It turns out that I need to log in using my username, but instead of using the normal GitHub account password, I should use a personal access token that can be created here.
Edited content by Do Nhu Vy:
Because I am use GitHub feature named "Two-factor authentication" (It isn't a standard Git's feature, it's added feature by GitHub.com). After turn on the feature, I must create "Personal Access Tokens"
Reference
https://help.github.com/articles/about-two-factor-authentication/
https://github.com/settings/tokens


text:
Q: Lone space pilot searching for habitable planets with a mynah bird his only companion While traveling between potential stellar systems, a pilot stumbles across a habitable planet that shouldn't be there. He lands and starts to explore. All the flora is separate from its neighbours with no overlap. Eventually, a building appears in the distance and he realizes as he gets nearer that it is massive. He finds a door, and inside, fauna of various sizes and types, at first all alien. Then he comes across creatures from Earth, and starts to wonder how they got there. He begins to feel nervous, and he gets a feeling that someone is watching him. So he realizes that he shouldn't be there, and makes a hasty return to his ship and takes off.

A: "Hobbyist" by Eric Frank Russell

Steve Ander is flying a Probe Service ship when he gets flung across
the galaxy.  The important thing is that Steve is
lost, almost out of fuel, and stranded on a planet

On the other side of the valley is a giant structure.

Exploring the structure he
discovers clear containers containing animals, most unknown to him but
a few familiar and Terrestrial. Near the back are some machines that
today would be called 3D printers. They are producing animals,
although these animals are missing "the breath of life".


text:
Q: Can I move Google calendar events from one user to another user via API with a Service Account I have created a Service account and I need to move event1 from calendar1 of User1 to calendar2 of User2.
When I request access token as User1 with "sub":"user1@gmail.com" during JWT step and using that token When I do following
POST https://www.googleapis.com/calendar/v3/calendars/User1calendarId/events/event1Id/move?Destination=user2calendarId

I get following error
{
    "error": {
        "errors": [
            {
                "domain": "calendar",
                "reason": "requiredAccessLevel",
                "message": "You need to have reader access to this calendar."
            }
        ],
        "code": 403,
        "message": "You need to have reader access to this calendar."
    }
}

Are there any permission that needs to be assigned to Service Account in order to make this operation? or What should be correct way to move event between different user's calendar as a Service Account?

A: Explanation:
The scopes you are adding to your application are classified as sensitive scopes, as they request access to private user data such as Calendar events.

Your application would need to undergo a verification process to be able to use these scopes. For more information, please check the official documentation.

Sensitive scopes

Some of the scopes used by the following APIs are considered sensitive; see the API documentation or look for the lock icon in the Cloud Console. If your app requests sensitive scopes, and doesn't meet any of the criteria for an exception (see below), you will need to verify that your app follows the API Services User Data Policy.

For a complete list of Google APIs, see OAuth 2.0 Scopes for Google APIs. To check if scopes are sensitive or restricted, add the scopes to your project via the Google Cloud Console.


text:
Q: Cassandra connections rebalancing between seeds after a maintenance When restarting one Cassandra seed node, all its client connection are rebalance to other nodes as expected. However, when the node is up again the incoming connection are not staying to the previous level. It causes a ~10% performance impact since the other nodes are slightly more used. Restarting the client applications solve the issue.
Is it possible to have an automatic client rebalancing without a restart of the clients after some time, e.g. 1h?
I am using 4 seeds node on my application with the latest Java driver com.datastax.oss:java-driver-bom:4.15.0 and Cassandra 4.0.7. Load balancing policy used is DcInferringLoadBalancingPolicy.
Here is an example of the restart of one node. in graph.


text:
Q: AWS Amplify Avoid @connection queries on an @key or index query generating a list I have a model for orders, I made an index that would let me query the orders based on what month and year they were created.
Now that I am able to query those orders, I want to avoid unnecessary connection (order-vendor) queries every time I query using that month-year index since I only want the list of the orders' number and status. Is there a way that I can do that?
here is my schema:
type Vendor @model @searchable{
id: ID!
vendorName: String!
location: String!
telNo: String!
terms: String!
createdAt: AWSDateTime!
updatedAt: AWSDateTime!
}

type PurchaseOrder @model @searchable
@key(name:"MonthYearCreatedAt" fields:["monthYear", "createdAt"] queryField: "purchaseOrderMonthCreatedAt")
{
id: ID!
purchaseOrderNo: String!
vendor: Vendor! @connection
orders:[String!]
totalPrice: Float!
requestedBy: String!
category: String
addNotes: String
status: Status!
monthYear: String!
createdAt: AWSDateTime!
updatedAt: AWSDateTime!
}

A: You can do that by adapting your query
query getPurchases {
  purchaseOrderMonthCreatedAt(monthYear: ..., createdAt: ...) {
    items {
      totalPrice
    }
  }
}

vs
query getPurchases {
  purchaseOrderMonthCreatedAt(monthYear: ..., createdAt: ...) {
    items {
      vendor { vendorName }
      totalPrice
    }
  }
}

Using the second query will navigate the vendor connection.


text:
Q: Routing default CRUD interface for composite keys in Play Framwork I am trying to create a successful route for an entity that only has a composite key so that i may navigate to the default CRUD module's 'edit' interface.
Right now, I am successfully retrieving and displaying the list of all the club_admin's in the database, however when I try and navigate to the individual editing page of a club_admin, I receive the error of "no route."
The table in my database is:
create table club_admin  (
    club_id int not null,
    user_username varchar(25) not null,
    primary key (club_id,user_username),
    constraint fk_club_admin_club_id foreign key (club_id) references club(club_id),
    constraint fk_club_admin_user_username foreign key (user_username) references user(user_username)
);

The code for the club_admin class is:
package models;

...

@Entity
@Table(name="club_admin")
public class ClubAdmin extends GenericModel
{

        @Id
        @ManyToOne
        @JoinColumn(name="club_id", referencedColumnName="club_id")
        public Club club;

        @Id
        @ManyToOne
        @JoinColumn(name="user_username", referencedColumnName="user_username")
        public User user;

        public ClubAdmin(Club club, User user)
        {
                this.club=club;
                this.user=user;
        }

        ...
}

My guess is that the table/entity has no default id to use for the route, and thus fails. So my questions is how do I create a route, that uses the composite keys to navigate to the 'edit' page of the club_admin, without having to create a single primary key of type integer?
Thanks!

A: I found out that many to many relationships are represented by Set<class>. I should not have created the many to many class but instead should have created set of members (which represents an admin) variable on club or visa verse, depending on my needs. With this method, the many-to-many relation is created automatically. Also and there is no need to edit my routes.


text:
Q: RxAndroidBle - Long write and listen to notification characteristic I'm very new when it comes to the android / BLE space. I'm attempting to write to a characteristic and listen on the notification using the RxAndroidBle library. I've looked at many implementations that just seem to be different enough that I can't get my scenario to work properly. This post: No notification data in Write/Notification set-up is almost what I need however, when I use the code posted, I'm unable to capture any data on my peripheral, which in turn doesn't return a response since I'm not sending back a response. When I switch to a long write builder I'm able to write to my peripheral and see the data flow in, but upon returning a response from my peripheral, nothing is captured in my notification subscription.
Here's my code:
 private void writeNotify(RxBleDevice peripheral, byte[] payload) {
    Disposable connectionSubscription = peripheral.establishConnection(false)
            .flatMap( // when the connection is available...
                    rxBleConnection -> rxBleConnection.setupNotification(UUID.fromString(notifyCharacteristic)), // ... setup the notification...
                    (rxBleConnection, notifyObservable) -> Observable.combineLatest( // ... when the notification is setup...
                            rxBleConnection.createNewLongWriteBuilder().setBytes(payload).setCharacteristicUuid(UUID.fromString(writecharateristic)).setMaxBatchSize(20).build(), // ... write the characteristic...
                            //rxBleConnection.writeCharacteristic(UUID.fromString(writecharateristic), payload).toObservable(), // ... write the characteristic...
                            notifyObservable, // ... and observe for the first notification on the AP_SCAN_DATA
                            (writtenBytes, responseBytes) -> responseBytes
                    )
            )
            .flatMap(observable -> observable) // ... flatMap the result as it is Observable<byte[]>...// ... and finish after first response is received to cleanup notifications
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(
                    responseBytes -> {
                        String data = new String(responseBytes);
                    },
                    throwable -> {

                    }
            );
}

Separately, I've attempted to handle this as 2 operations where I set up my notification characteristic after performing a long write to my peripheral. Where I subscribe to the observeConnectionStateChanges method on my peripheral and wait for the disconnecting state to fire before setting up my notification characteristic. In this scenario I actually am able to receive partial responses so I know that the notification characteristic is working. I'm just not implementing this correctly. Any suggestions?


text:
Q: Java heap space outOfMemoryError To avoid the java.lang.outOfMemoryError I went to Control Panel-->Java-->Java-->View and set the runtime parameters. But it produces no change.
It is a simple program which I'm running via the command prompt. Initially I ran the code using java -Xmx1024m PercolExp(class_name) and it ran. But when I change java runtime parameters settings in the Java control panel and run the code by simply typing java PercolExp it doesn't take the heap size parameter into account.

A: The Control panel you've found is (I think) this one.  If you read the page I linked you, you will find that it is the control panel for the Java plugin used by your web browser.  It only affects the embedded JVM that is used to run applets in web pages.

A: The Java Control Panel controls the settings of the Java Runtime Environment for applets and Java Web Start applications. If you run your application from the command line (java AppName) those parameters won't be taken into account: you will need to specify them  manually every time.


text:
Q: download files using Yii2 gridFS I want to download files from gridfs using YII2. I am new to Yii I have used this code
   class classname extends \path\controller{
   $connection = new \yii\mongodb\Connection([
        'dsn' => 'mongodb://localhost:27017/files',
    ]);
    $connection->open();
    $fileCollection = new Collection();
    $collection = $connection->getCollection('fs.files');
    $records = $collection->findOne(["_id"=>'548171105e24cfe00c0000ee'],["filename"]);

but I have retrived the file details. can anyone please tell me how to proceed further for downloading a file.

A: You can use the fileSend() method
http://www.yiiframework.com/doc-2.0/yii-web-response.html#sendFile()-detail


text:
Q: Animation completes immediately iOS I am creating an app where there is a main view managed by a view controller and a second view for settings managed by another view controller.
I am using a Container View Controller for UI/UX reasons in an app where after touching a button, the view for the settings slides up from the bottom of the screen to about mid-height. The top half of the screen still shows the previous main view.
Everything is working perfectly, after pressing the button or when the user dismisses the View Controller that slid up, I keep one of the view (because it is still visible), I keep the view controller in memory but I remove it from the View Controller hierarchy and switch to the other one.
The problem now is that when I press the button to show the settings view controller, all the very simple animations on the main view, such as animating the frame property of a UILabel, behave unexpectedly. The animation complete almost immediately.
I read an answer on StackOverflow pointing at the fact that changing the transform property makes it impossible to animate using the frame property and requires to animate witht the center property.
Even though I haven't explicitely changed the transform property of any objects (I am not very familiar with this property), I tried to animate using the center property and it still animated too fast.
Here is an example of an animation that completes immediately after the settings button is pressed but works fine otherwise:
            [UIView animateWithDuration:1.4 animations:^{

            self.alarmTimeLabel.center = CGPointMake(self.alarmTimeLabel.center.x, self.alarmTimeLabel.center.y + 200);

        }];

Thanks for any input

A: The animations now work using an older method to achieve the same result.
        [UIView beginAnimations:@"test" context:nil];

        [UIView setAnimationDuration:2.0];

        self.alarmTimeLabel.center = centerAlarmTimeLabel;
        self.amOrPm.center = centerAmOrPm;

        [UIView commitAnimations];

That fixed the bug! I don't know why the newer way to make simple animations doesn't work, even when using the center property.


text:
Q: Need help in solving Vehicle Routing in a production environment I am working on a problem for my startup where I have to assign locations to delivery trucks based on an optimal route from a distribution center.
I am using ortools right now but I am working with gps coordinates unlike given example which is using a grid structure.
Right now I've figured out a way to calculate distance between coordinates and modified their demo python code but as far as I know there is no way to define gps coordinates as home depot and I am struggling there to get optimal routes from my home depot.
Any help would be appreciated.
Thank You

A: Actually, by providing a Distance callback function (cf. https://developers.google.com/optimization/routing/tsp/vehicle_routing#distance_callback) you can provide whatever you want as distance function...
Thus, you could see 2D location as an id (e.g. GPS location of your addresses)  then create a distance callback which calculate the shortest distance between two locations using road etc... (e.g. you can use the GMap Direction API)
For the depot, it's just a node like others (i.e. has a location), then you can set this node as the depot in the RoutingModel Ctor...
note: You should create a Distance cost matrix first then use it as a look up table to return distance in constant time during iteration cf example in the doc


text:
Q: Regexp to check if a string is a javascript function? I want to check if a string is a valid javascript function call.
Could someone help me to write a regex that match to all these:
hello("hello", "world")
greet(1, "mr", "peterson");
run()

But not these:
walk()); // invalid syntax
greet(1?23\) // invalid js characters
say("hi" -) // invalid js characters

Thanks!

A: Answering the implied question from your comment:

I want to use eval() on it. But I want to check its valid js function first because I dont want to run variables or invalid strings.

If this is one of the, oh, three (or fewer) valid places where using eval isn't a bad idea, probably better to go ahead and eval it and handle the resulting Error via a try/catch block — EvalError, SyntaxError, etc. See the spec for details of the various errors — if you care what the error is; mostly I'd think you just want to know whether there was a problem or not, e.g.:
try {
    eval(theString);
}
catch (e) {
    // Something went wrong, report it
}

But: You can (and should) almost always avoid using eval. For instance, if you want to allow someone to give you something to call that may require arguments (your hello("hello", "world")), just have them give you a function you call without arguments, and they would give you a wrapper e.g.:
callTheFunction(function() {
    hello("hello", "world");
});

A: You can define the folloding regexp for a parameter, meaning string or integer or float or variable
string literal : "[^"]"
int : -?\d+
float : -?\d*\.\d+
variable / function name : [\w\d_]+

parameter : ("[^"]"|-?\d+|-?\d*\.\d+|[\w\d_]+)

Then your function is the same as a variable, followed by parenthesis a few parmeters, then closing parenthesis.
rough : function \( (|parameter(,parameter)*\)
adding potential spaces : function\s*\(\s*(|parameter\s$(,\s*parameter\s*)*\)
replacing blocks : [\w\d_]+\s*\(\s*(|("[^"]"|-?\d+|-?\d*\.\d+|[\w\d_]+)\s$(,\s*("[^"]"|-?\d+|-?\d*\.\d+|[\w\d_]+)\s*)*\)

Note that you will want to match multiline and case insensitive. I don't ensure it's error-proof, but at least you can follow the kind of thinking you have to deal with to fine tune it.
EDIT : I thought it was fairly complex (I probably issed some cases), but after your comment, if it's just to run eval, it's pointless...
note that my checks only assume that you use plain variables, no objects (otherwise, deal with the dot which can't be in first position)


text:
Q: Error HRESULT E_FAIL when pasting references in Visual Studio I know this isn't a programming question but it is a programming tool question.
In Visual Studio 2008 Team Edition (version 9.0 with .NET 3.5 SP1) when I copy and paste references from one csproj to another (with the context menu in the 'Solution Explorer' view) I get the following error:

Error HRESULT E_FAIL has been returned from a call to a COM component

This has only just started happening on my machine. I can only find this article about it, and it contains no solution.
Any ideas?

A: This is the #1 hit that shows up on Google for VS 2010 paste reference E_FAIL and the like, so I thought I would share this workaround:
Don't use copy/paste references via the context menu in Solution Explorer.
Instead:

*

*Use the context menu to unload the project to copy references from.

*Edit the project file (.csproj; it's just XML).

*Find the
reference(s) you are interested in and copy the <Reference> XML
node(s).

*Unload the project to copy the reference into.

*Edit the project file (.csproj)

*Paste the reference copied in the previous step into appropriate location. You need to look for
    the <ItemGroup> node containing something like <Reference Include="mscorlib" />, and paste your reference just above it.

*Close both .csproj files, saving the just-modified target one as well.

*Reload both projects via Solution Explorer context-menu.

Your reference is now copied into the target project.
Apparently, at the very minimum, there is a problem with references that use environment variables, as described here (although in my case, I was having a problem with references that did not use environment variables, and in Visual Studio 2010...)

A: Yikes , E_FAIL is the most generic COM error , since it literally means a COM function returned fail. I would guess that somehow , visual studio 2008 has a corrupted COM object somewhere.
Have you tried reinstalling visual studio 2008 just to get it to re-register all its tlb's and objects ?


text:
Q: Finding conditional expected value $E[y|x]$ joint pdf : $ f(x,y) = 3y^2/x^3$ from $0<y<x<1$
I needed marginal probability f(X) which I found to be 1 since I integrated $3y^2/x^3$ from $0$ to $X$
The conditional probability of y given x is then the same as the joint pdf.
So $E[y|x] = \int{x3y^2/x^3dx}$ from $0$ to $1$.
But then my answer is in terms of y while I know it should be a function in terms of X. Where did I go wrong?

A: Simply integrate the $y$-term from $0$ to $1$.
$$\mathbb{E}[Y \mid X] = \int_{0}^{1}yf_{Y \mid X}(y \mid x)\text{ d}y = \int_{0}^{1}y\left(\dfrac{3y^2}{x^3}\right)\text{ d}y = \dfrac{3}{x^3}\int_{0}^{1}y^3\text{ d}y\text{.}$$


text:
Q: Hubbard model within mean-field: three different approaches While reading doi:10.1016/j.carbon.2012.03.009 , the authors mention three types of Hubbard models within mean-field approximation. The first one describes the electron-electron interaction, and to my understanding is the standard way of writting up the model and reads (only interaction term):
$H_{int}=U\sum_{i,\sigma} n_{i\sigma}\langle{n_{i-\sigma}}\rangle$
The second version seems to describe electron-hole interaction and reads:
$H_{int}=U\sum_{i,\sigma}(\langle{n_{i-\sigma}}\rangle-\frac{1}{2})n_{i\sigma}$
And a third one seems to describe moment-moment interaction and reads:
$H_{int}=\frac{U}{2}\sum_{i} n_{i}\langle{n_i}\rangle-U\sum_i 2m_i\langle{m_i}\rangle$
where $n_i=n_{i\uparrow}+n_{i\downarrow}$ and $m_i=\frac{1}{2}(n_{i\uparrow}-n_{i\downarrow})$.
My question is how can I see that the two last 'versions', describe what they are supposed to. To my understanding, all of them are the same version except for a shift on the Fermi level for case 2 which shifts the half-filling below $E=0$, as opposed to $E=U/2$. Case 1 and 3 are the same.

A: To me, the Hubbard interaction per site is defined as $H_{int}=U n_{\uparrow} n_{\downarrow}$. (I suppressed the $i$, and also there is a factor of two because of your spin sum.)
Then, the mean-field approximation is defined as $n_{\uparrow} n_{\downarrow}\to n_{\uparrow} \langle n_{\downarrow}\rangle+n_{\downarrow} \langle n_{\uparrow}\rangle-\langle n_{\uparrow}\rangle \langle n_{\downarrow}\rangle$.
So your version (i) lacks the constant term.
Per site, you have two operators, $n_{\uparrow}$ and $n_{\downarrow}$, i.e. the occupancies for each species of electrons, which, of course, you can trade against total charge, $n=n_{\uparrow}+n_{\downarrow}$ and moment $m=n_{\uparrow}-n_{\downarrow}$ (beware, again a factor of two with your definition). This makes you end up with version (iii).
For version (ii), you need a so-called electron-hole transformation, i.e. for one spin species, say $\downarrow$, you replace the electron destruction operator by a hole creation operator $c_{\downarrow}\to a^{+}_{\downarrow}$, and vice versa. (The $a$-operators satisfy the same fermionic algebra as the original $c$-operators.) So $n_{\downarrow}=c^{+}_{\downarrow}c_{\downarrow}\to a_{\downarrow}a^{+}_{\downarrow} =1-a^{+}_{\downarrow}a_{\downarrow}$. This last guy, $a^{+}_{\downarrow}a_{\downarrow}$, you call it $n_{\downarrow}$ again, but remember, it counts holes now.  And you end up with the electron-hole interaction in (ii).


text:
Q: Show that $S$ is non-orientable
Let $S$ be a regular surface covered by coordinate neighborhoods $V_1$ and $V_2$. Assume that $V_1\cap V_2$ has two connected components, $W_1$, $W_2$, and that the Jacobian of the change of coordinates is positive in $W_1$ and negative in $W_2$. Show that $S$ is non-orientable.

I know that, if a regular surface $S$, can be covered by two coordinate neighborhoods, whose intersection is connected, then the surface is orientable.
Furthermore, if $f:S\subset\mathbb{R}^3\to\mathbb{R}$ is a continuous function, in a connected surface $S$, then $f$ doesn't change of sign on $S$. Can give any hint! Thanks!

A: Rough idea: If you have a loop in a manifold, it can be subdivided such that each segment is contained in a coordinate chart, and such that the initial and final segments lie in the same chart. Then the sign of the product of the Jacobians of successive transition maps is independent of the choice of charts and subdivision.
Now if $S$ is orientable, then the sign for any loop must be positive (by using an oriented atlas). But if $p \in W_1$ and $q \in W_2$, and we consider a loop that starts at $p$, goes to $q$ within $V_1$, and returns to $p$ within $V_2$, then its sign must be negative.
I'm not entirely sure that this is correct or that there isn't a much simpler solution, but it's all I can think of for now.


text:
Q: Missing PID file when using a process manager to start delayed job I am using BluePill to manage processes such as delayed job for Rails.  In the BluePill log, I am getting this message:
W, [2010-09-27T01:23:20.447053 #19441]  WARN -- : [fsg_distro:delayed_job] pid_file /srv/fsg_distro/shared/pids/delayed_job.pid does not exist or cannot be read
W, [2010-09-27T01:23:20.447368 #19441]  WARN -- : [fsg_distro:delayed_job] Executing start command: ruby script/delayed_job -e production start
I, [2010-09-27T01:23:20.469165 #19441]  INFO -- : [fsg_distro:delayed_job] Going from down => starting

So it's claiming that a pid file is missing, which it is, but shouldn't that pid be created when BluePill starts the Delayed Job process?
Update
To be a bit more clear about this error, I can successfully run the command manually but Bluepill fails to run the start command.  When I run it manually, it looks like this:
rails@george:/srv/fsg_distro/current$ /usr/bin/env RAILS_ENV=production /usr/bin/ruby /srv/fsg_distro/current/script/delayed_job start
delayed_job: process with pid 17564 started.

When I run it with Bluepill it looks like this:
W, [2010-10-03T21:24:13.943136 #17326]  WARN -- : [fsg_distro:delayed_job] pid_file /srv/fsg_distro/shared/pids/delayed_job.pid does not exist or cannot be read
W, [2010-10-03T21:24:13.943391 #17326]  WARN -- : [fsg_distro:delayed_job] pid_file /srv/fsg_distro/shared/pids/delayed_job.pid does not exist or cannot be read
I, [2010-10-03T21:24:13.943811 #17326]  INFO -- : [fsg_distro:delayed_job] Going from starting => down
W, [2010-10-03T21:24:14.945274 #17326]  WARN -- : [fsg_distro:delayed_job] pid_file /srv/fsg_distro/shared/pids/delayed_job.pid does not exist or cannot be read
W, [2010-10-03T21:24:14.945495 #17326]  WARN -- : [fsg_distro:delayed_job] pid_file /srv/fsg_distro/shared/pids/delayed_job.pid does not exist or cannot be read
W, [2010-10-03T21:24:14.945826 #17326]  WARN -- : [fsg_distro:delayed_job] Executing start command: /usr/bin/env RAILS_ENV=production /usr/bin/ruby /srv/fsg_distro/current/script/delayed_job start
W, [2010-10-03T21:24:15.049261 #17326]  WARN -- : [fsg_distro:delayed_job] Start command execution returned non-zero exit code:
W, [2010-10-03T21:24:15.049491 #17326]  WARN -- : [fsg_distro:delayed_job] {:stderr=>"", :exit_code=>1, :stdout=>""}
I, [2010-10-03T21:24:15.049947 #17326]  INFO -- : [fsg_distro:delayed_job] Going from down => starting

My pill looks like this:
APP_ROOT='/srv/fsg_distro'
RAILS_ROOT='/srv/fsg_distro/current'
RAILS_ENV='production'
RUBY_EXEC='/usr/bin/ruby'

Bluepill.application("fsg_distro", :log_file => "/srv/fsg_distro/shared/log/bluepill.log") do |app|
  app.process("delayed_job") do |process|
    process.working_dir = RAILS_ROOT

    process.start_grace_time    = 30.seconds
    process.stop_grace_time     = 30.seconds
    process.restart_grace_time  = 30.seconds

    process.start_command = "/usr/bin/env RAILS_ENV=#{RAILS_ENV} #{RUBY_EXEC} #{RAILS_ROOT}/script/delayed_job start"
    process.stop_command  = "/usr/bin/env RAILS_ENV=#{RAILS_ENV} #{RUBY_EXEC} #{RAILS_ROOT}/script/delayed_job stop"

    process.pid_file = "#{APP_ROOT}/shared/pids/delayed_job.pid"
    process.uid = "deploy"
    process.gid = "deploy"
  end
end

And my delayed job script looks like this:
#!/usr/bin/env ruby
ENV['RAILS_ENV'] ||= 'production'

require File.dirname(__FILE__) + '/../config/environment'
require 'delayed/command'
Delayed::Command.new(ARGV).daemonize

A: If you daemonize delayed_job (which you are) then you must generate a pid file for it yourself, or get delayed_job to do it for you, then bluepill expects to find the pid file once grace_start_time has passed.
If you run delayed_job in the foreground, and you tell bluepill to daemonize the process for you, then bluepill will generate the pid file.
You can't both monitor a self-daemonizing process and have bluepill create a pid file.  It's either one or the other.

A: I have no answer, but exactly the same question.
I have tried many, many solutions--including creating a startup script for init.d and calling that from bluepill as described in another monit-based posting (http://stackoverflow.com/questions/1226302/how-to-monitor-delayed-job-with-monit), but nothing has worked. Always there is a permissions issue with the PID file. How could this be the case when running as su?
I own the code, and share it with group www.
Do I need to create a custom user just to run bluepill? If so, with what settings?


text:
Q: How to add hidden product to magento shopping cart? I have a page, where I need to add hidden product to the shopping cart after clicking on a button.
I do not want to show the product, just add it to the cart.
How can I do it?

A: Set the products visibility to "Not visible individually" from admin and in your controller file add the product programatically like this:
<?php
$productId = '123';
$qty = '3';
$product = Mage::getModel('catalog/product')->load($productId);
$cart = Mage::getModel('checkout/cart');
$cart->init();
$cart->addProduct($product, array('qty' => $qty));
$cart->save();
Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
?>

You can call this controller using ajax also.


text:
Q: Converting non-standard date strings I am attempting to import a CSV file that contains a text column (named 'Formatted Date') with dates that look as follows:
Apr 18 '20
I've tried a number of things to convert this to a date field. For example, I created a step that removed the apostrophe and then another step that creates a custom column with this expression:
Date.FromText([Formatted Date],"mmm dd yy")
However this generates an error about an unsupported culture. Is there a way I can do what I want?

A: Your question is a little ambiguous:
Apr 18 '20
What language does your 3 letter month name come from? English, German? What's the next month then: "May" or "Mai"? And how about the apostrophe: Does it stand for 2000, or do you also have data from the 1900's?
If I replace the apostrophe with "20" and then simply convert the text to date format, it works out perfectly fine:
#"Replaced Value" = Table.ReplaceValue(
    Source,"'","20",Replacer.ReplaceText,{"date"}),
#"Changed Type1" = Table.TransformColumnTypes(
    #"Replaced Value",{{"date", type date}})

So your error is most likely caused by your regional settings. However, when transforming the column type you can click on the "ABC" symbol in your column header (Query Editor) and select "Using Locale ...". In the following pop-up window "Change Type with Locale" You select "Data Type" = "Date" plus the proper "Locale". If you don't know it, you can also try different values until it fits.


text:
Q: Как сохранить результат выбранного селекта в массив? Есть два селекта:
<select id="id1" disabled>
  <option value="0">- текст -</option>
  <option value="1">- текст -</option>
  <option value="2">- текст -</option>
</select>

и
<select id="id2" disabled>
  <option value="0">- 1 -</option>
  <option value="1">- 2 -</option>
  <option value="2">- 3 -</option>
</select>

Я создал массив:
var resultId1 = [0, 0, 0];

Например, если выбрать в селекте (id1) первый вариант (value = 0), а затем в селекте (id2), например тоже первый вариант (value = 0). В массиве 3 ячейки, соответствующие количеству вариантов в селекте (id2). Мне нужно как-то записывать сколько раз было выбран тот или иной вариант в селекте (id2) в зависимости от выбранного значения селекта (id1). В Селекте (id1) гораздо больше вариантов будет, а во втором всего три. Я думал сделать через if else, но слишком много их будет, не думаю что это правильно. То есть:
if (выбрано value = 0 в id1) {
  if (выбрано value = 0 в id2) {
      добавить в массив resultId1 в ячейку 0 число 1
   } else if {...}... }

Но такая конструкция слишком большая. Может как-нибудь по-другому можно?

A: Вот пример. Для сохранения выбора жмите выбрать, для того чтобы посмотреть результаты - Вывести лог.

var counter = {};
var options = document.getElementById('id1').options;
for (var i = 0; i < options.length; i++) {
  counter[options[i].value] = [0, 0, 0];
}
document.getElementById("save").onclick = function() {
  var id1 = document.getElementById("id1");
  var value1 = id1.options[id1.selectedIndex].value;
  var id2 = document.getElementById("id2");
  var value2 = id2.options[id2.selectedIndex].value;
  counter[value1][value2]++;
};
document.getElementById("log").onclick = function() {
  console.log(counter);
};
<select id='id1'>
<option value='0'>Нулевой</option>
<option value='1'>Первый</option>
<option value='2'>Второй</option>
<option value='3'>Третий</option>
<option value='4'>Четвертый</option>

</select>
<select id='id2'>
<option value='0'>Нулевой</option>
<option value='1'>Первый</option>
<option value='2'>Второй</option>
</select>
<button id='save'>Выбрать</button>
<button id='log'>Вывести лог</button>

A: Если я понял, то что-то такое должно подойти :

var selected = {};
let select1 = document.getElementById('id1');
let select2 = document.getElementById('id2');

[...select1.options].forEach(o => {
  selected[o.value] = [0, 0, 0];
});
select2.addEventListener('change', function() {
  selected[select1.value][this.value] += 1;
});

function func() {
  document.getElementById("res2").innerHTML = '';
  Object.keys(selected).forEach(k => {
    document.getElementById("res2").innerHTML += `${k} = ${selected[k]}<br/>`;
  });
};
<select id="id1">
  <option value="0">- текст 1 -</option>
  <option value="1">- текст 2 -</option>
  <option value="2">- текст 3 -</option>
</select>

<select id="id2">
  <option value="0">- 1 -</option>
  <option value="1">- 2 -</option>
  <option value="2">- 3 -</option>
</select>

<button onclick="func();">Show</button>


text:
Q: Sorting a list according to natural ordering of elements I want descending sort type of code below:
This is ascending sort:
public static <T extends Vm> void sortByCpuUtilization(List<T> vmList) {
    Collections.sort(vmList, new Comparator<T>() {

        @Override
        public int compare(T a, T b) throws ClassCastException {
            Double aUtilization = a.getTotalUtilizationOfCpuMips(CloudSim.clock());
            Double bUtilization = b.getTotalUtilizationOfCpuMips(CloudSim.clock());
            return bUtilization.compareTo(aUtilization);
        }
    });
}

A: Compare a with b instead:
public static <T extends Vm> void sortByCpuUtilization(List<T> vmList) {
    Collections.sort(vmList, new Comparator<T>() {

        @Override
        public int compare(T a, T b) throws ClassCastException {
            Double aUtilization = a.getTotalUtilizationOfCpuMips(CloudSim.clock());
            Double bUtilization = b.getTotalUtilizationOfCpuMips(CloudSim.clock());
            return aUtilization.compareTo(bUtilization);
        }
    });
}

A: There are several ways of doing this. First, you could just implement a reverse comparator:
public static <T extends Vm> void sortByCpuUtilizationDesc(List<T> vmList) {
    Collections.sort(vmList, new Comparator<T>() {

        @Override
        public int compare(T a, T b) throws ClassCastException {
            Double aUtilization = a.getTotalUtilizationOfCpuMips(CloudSim.clock());
            Double bUtilization = b.getTotalUtilizationOfCpuMips(CloudSim.clock());
            return aUtilization.compareTo(bUtilization); // Note this is reversed
        }
    });
}

But much more elegantly, you could use Collections.reverseOrder:
public static <T extends Vm> void sortByCpuUtilizationDesc(List<T> vmList) {
    // Same comparator as before, should be extracted to a named class.
    Collections.sort(vmList, Collections.reverseOrder(new Comparator<T>() {

        @Override
        public int compare(T a, T b) throws ClassCastException {
            Double aUtilization = a.getTotalUtilizationOfCpuMips(CloudSim.clock());
            Double bUtilization = b.getTotalUtilizationOfCpuMips(CloudSim.clock());
            return aUtilization.compareTo(bUtilization); // Note this is reversed
        }
    }));
}


text:
Q: RSpec test if all models respond_to attribute I'm trying to write an RSpec test for what seems like a relatively simple test, but it's proving pretty tricky (though I am new to RSpec).
In simple terms, I want to test that all models in my application respond_to :owner or :owners.
My first problem is looping through all of the models - how to do this in RSpec? I can normally loop through the models like:
ActiveRecord::Base.descendants.each { |model|
    model.should respond_to :owner
}

But not sure how to do this correctly in RSpec? I can't find much documentation about using loops within tests.
My second question is about an "OR" clause - how can I achieve "responds to owner or owners"? Something like:
model.should respond_to :owner || :owners

But again I can't find much documentation about using or clauses.

A: You can accomplish the OR condition by testing each method and rolling up the answer:
ActiveRecord::Base.descendants.each do |model|
   instance = model.new
   expected = instance.respond_to?(:owner) || instance.respond_to?(:owners)
   expected.should be_true
end

But this smells wrong to me. If the model is going to respond to only one of :owner and :owners, you should test that it responds to the correct one. Even if this means creating a spec for each model (which you should have in any case) and adding a new example, you're better off in the long run by being specific. It also helps future maintainers of your code, who would expect a model spec to be in the spec file for the model itself, not in a catch-all spec.
In this case the example is quite small—for longer ones you might consider using a shared example to DRY things up a bit.

A: When your running Rspec tests you are still using Ruby. So your loop should work, as long as you are in an it block. Your only problem is you have a model object not an instance of the object, so you need to create one. so one solution would be:
it "every model should respond to owners" do

  ActiveRecord::Base.descendants.each { |model|
   model.new.should respond_to :owner
  }

end

I am not sure about the or clause.


text:
Q: Composer user version or dev I im definining a package in my composer. The latest package version has a bug that is solved in the dev release. I want to use the dev branch until the new release is released.
Package current version
- 7.1.4
So I want to use version 7.1.5 or higher (which isn't released yet) and until then dev.
How would I put this in my composer.json ?

A: You could add a @dev flag combined with the 7.1.x patch level version range, while waiting for the v7.1.5 (tag) release: 7.1.x-dev.
{
    "require": {
        "vendor/package": "7.1.*@dev"
    }
}

Or you could skip the range and just use dev-master for a while and drop it, when the next version is out.


text:
Q: Checking JS variable value in another
A: I think you're under the misapprehension that each <script> block is a separate scope.  It isn't.  If your code example above is an accurate reflection of your actual code, it should work, because action is declared globally, so the assignment is changing the global and the test is checking the global.
If it's not working, it's probably because you've established some other scope not shown above, like putting the var action = null bit inside a function.

A: I would use an hidden input in my html to store the value


text:
Q: How to move directory /var/lib/mysql Archlinux, MariaDB 10.1.25
I have working mysql. Now I decided to move directory with data.
I tried to move /var/lib/mysql to /home/srv/mysql. And creat symlink to old path (/var/lib/mysql). But mysqld gives error:
Job for mariadb.service failed because the control process exited with error code.
See "systemctl  status mariadb.service" and "journalctl  -xe" for details.

systemctl  status mariadb.service:
● mariadb.service - MariaDB database server
   Loaded: loaded (/usr/lib/systemd/system/mariadb.service; enabled; vendor preset: disabled)
   Active: failed (Result: exit-code) since Wed 2017-08-02 20:19:17 +10; 7min ago
  Process: 29629 ExecStart=/usr/bin/mysqld $MYSQLD_OPTS $_WSREP_NEW_CLUSTER $_WSREP_START_POSITION (code=exited, status=1/FAILURE)
  Process: 29576 ExecStartPre=/bin/sh -c [ ! -e /usr/bin/galera_recovery ] && VAR= ||   VAR=`/usr/bin/galera_recovery`; [ $? -eq 0 ]   && systemctl set-environment _WSREP_START_POSITION=$VAR || exit 1 (code=exite
  Process: 29575 ExecStartPre=/bin/sh -c systemctl unset-environment _WSREP_START_POSITION (code=exited, status=0/SUCCESS)
 Main PID: 29629 (code=exited, status=1/FAILURE)
   Status: "MariaDB server is down"

Access rights are correct. User mysql, group mysql.
Tell me what I'm doing wrong.

A: Check your my.cnf file, there might be following option set:
symbolic-links = 0

I'm not sure though, if this fixes the problem.
I recommend fixing the issue in another way. Instead of using symbolic links, simply adjust the data dir in your my.cnf with
datadir = /home/srv/mysql


text: Q: Problem with greek letters in latex font (Computer Modern) in Inkscape I use Inkscape for my graphics in my latex document. As the font in the graphics should be the same as the text font (CMR10), I installed computer modern on my computer. Regular letters work fine. Greek letters don't appear, but they are there. When I change the font to a non-CM font (e.g. Arial), they appear. When I change it back to CM, they disappear.


text:
Q: Why is Ruby not available to me after compiling from source? I'm trying to compile Ruby 2.0 from source onto Debian stable. I'm following the steps in the chruby wiki since I'd like to use chruby to manage my ruby versions (installed it prior to this). So, I ran these commands in a subdirectory of my home directory:
wget http://ftp.ruby-lang.org/pub/ruby/2.0/ruby-2.0.0-p247.tar.gz
tar -xzvf ruby-2.0.0-p247.tar.gz
cd ruby-2.0.0-p247
./configure --prefix=/opt/rubies/ruby-2.0.0-p247
make
sudo make install

Afterwards, I ran ruby -v to see if everything went ok, and get a message from the shell: bash: ruby: command not found. Then I ran make check in the ruby directory and received this output:
ruby -v: ruby 2.0.0p247 (2013-06-27 revision 41674) [x86_64-linux]
check succeeded

What went wrong here?

A: Is /opt/rubies/ruby-2.0.0-p247/bin in your $PATH? With a --prefix like that then make install will put all the binaries in $prefix/bin basically.
If you do
$ ls /opt/rubies/ruby-2.0.0-p247

You'll see all your binaries


text:
Q: What is "the inverse side of the association" in a bidirectional JPA OneToMany/ManyToOne association? In the example section of the @OneToMany JPA annotation reference:
Example 1-59 @OneToMany - Customer Class With Generics
@Entity
public class Customer implements Serializable {
    ...
    @OneToMany(cascade=ALL, mappedBy="customer")
    public Set<Order> getOrders() {
        return orders;
    }
    ...
}

Example 1-60 @ManyToOne - Order Class With Generics
@Entity
public class Order implements Serializable {
    ...
    @ManyToOne
    @JoinColumn(name="CUST_ID", nullable=false)
    public Customer getCustomer() {
        return customer;
    }
    ...
}

It seems to me that the Customer entity is the owner of the association. However, in the explanation for the mappedBy attribute in the same document, it is written that:

if the relationship is bidirectional,
  then set the mappedBy element on the
  inverse (non-owning) side of the
  association to the name of the field
  or property that owns the relationship
  as Example 1-60 shows.

However, if I am not wrong, it looks like in the example, the mappedBy is actually specified on the owning side of the association, rather than the non-owning side.
So my question is basically:

*

*In a bidirectional (one-to-many/many-to-one) association, which of the entities is the owner? How can we designate the One side as the owner? How can we designate the Many side as the owner?

*What is meant by "the inverse side of the association"? How can we designate the One side as the inverse? How can we designate the Many side as the inverse?

A: Unbelievably, in 3 years nobody has answered your excellent question with examples of both ways to map the relationship.
As mentioned by others, the "owner" side contains the pointer (foreign key) in the database. You can designate either side as the owner, however, if you designate the One side as the owner, the relationship will not be bidirectional (the inverse aka "many" side will have no knowledge of its "owner"). This can be desirable for encapsulation/loose coupling:
// "One" Customer owns the associated orders by storing them in a customer_orders join table
public class Customer {
    @OneToMany(cascade = CascadeType.ALL)
    private List<Order> orders;
}

// if the Customer owns the orders using the customer_orders table,
// Order has no knowledge of its Customer
public class Order {
    // @ManyToOne annotation has no "mappedBy" attribute to link bidirectionally
}

The only bidirectional mapping solution is to have the "many" side own its pointer to the "one", and use the @OneToMany "mappedBy" attribute. Without the "mappedBy" attribute Hibernate will expect a double mapping (the database would have both the join column and the join table, which is redundant (usually undesirable)).
// "One" Customer as the inverse side of the relationship
public class Customer {
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "customer")
    private List<Order> orders;
}

// "many" orders each own their pointer to a Customer
public class Order {
    @ManyToOne
    private Customer customer;
}

A: For two Entity Classes Customer and Order , hibernate will create two tables.
Possible Cases:

*

*mappedBy is not used in Customer.java and Order.java Class then->
At customer side a new table will be created[name = CUSTOMER_ORDER] which will keep mapping of CUSTOMER_ID and ORDER_ID. These are primary keys of Customer and Order Tables.
At Order side an additional column is required to save the corresponding Customer_ID record mapping.

*mappedBy is used in Customer.java [As given in problem statement]
Now additional table[CUSTOMER_ORDER] is not created. Only one column in Order Table

*mappedby is used in Order.java
Now additional table will be created by hibernate.[name = CUSTOMER_ORDER]
Order Table will not have additional column [Customer_ID ] for mapping.
Any Side can be made Owner of the relationship. But its better to choose xxxToOne side.
Coding effect - > Only Owning side of entity can change relationship status. In below example BoyFriend class is owner of the relationship. even if Girlfriend wants to break-up , she can't.
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;

@Entity
@Table(name = "BoyFriend21")
public class BoyFriend21 {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "Boy_ID")
    @SequenceGenerator(name = "Boy_ID", sequenceName = "Boy_ID_SEQUENCER", initialValue = 10,allocationSize = 1)
    private Integer id;

    @Column(name = "BOY_NAME")
    private String name;

    @OneToOne(cascade = { CascadeType.ALL })
    private GirlFriend21 girlFriend;

    public BoyFriend21(String name) {
        this.name = name;
    }

    public BoyFriend21() {
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public BoyFriend21(String name, GirlFriend21 girlFriend) {
        this.name = name;
        this.girlFriend = girlFriend;
    }

    public GirlFriend21 getGirlFriend() {
        return girlFriend;
    }

    public void setGirlFriend(GirlFriend21 girlFriend) {
        this.girlFriend = girlFriend;
    }
}

import org.hibernate.annotations.*;
import javax.persistence.*;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.ArrayList;
import java.util.List;

@Entity
@Table(name = "GirlFriend21")
public class GirlFriend21 {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "Girl_ID")
    @SequenceGenerator(name = "Girl_ID", sequenceName = "Girl_ID_SEQUENCER", initialValue = 10,allocationSize = 1)
    private Integer id;

    @Column(name = "GIRL_NAME")
    private String name;

    @OneToOne(cascade = {CascadeType.ALL},mappedBy = "girlFriend")
    private BoyFriend21 boyFriends = new BoyFriend21();

    public GirlFriend21() {
    }

    public GirlFriend21(String name) {
        this.name = name;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public GirlFriend21(String name, BoyFriend21 boyFriends) {
        this.name = name;
        this.boyFriends = boyFriends;
    }

    public BoyFriend21 getBoyFriends() {
        return boyFriends;
    }

    public void setBoyFriends(BoyFriend21 boyFriends) {
        this.boyFriends = boyFriends;
    }
}

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import java.util.Arrays;

public class Main578_DS {

    public static void main(String[] args) {
        final Configuration configuration = new Configuration();
         try {
             configuration.configure("hibernate.cfg.xml");
         } catch (HibernateException e) {
             throw new RuntimeException(e);
         }
        final SessionFactory sessionFactory = configuration.buildSessionFactory();
        final Session session = sessionFactory.openSession();
        session.beginTransaction();

        final BoyFriend21 clinton = new BoyFriend21("Bill Clinton");
        final GirlFriend21 monica = new GirlFriend21("monica lewinsky");

        clinton.setGirlFriend(monica);
        session.save(clinton);

        session.getTransaction().commit();
        session.close();
    }
}

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import java.util.List;

public class Main578_Modify {

    public static void main(String[] args) {
        final Configuration configuration = new Configuration();
        try {
            configuration.configure("hibernate.cfg.xml");
        } catch (HibernateException e) {
            throw new RuntimeException(e);
        }
        final SessionFactory sessionFactory = configuration.buildSessionFactory();
        final Session session1 = sessionFactory.openSession();
        session1.beginTransaction();

        GirlFriend21 monica = (GirlFriend21)session1.load(GirlFriend21.class,10);  // Monica lewinsky record has id  10.
        BoyFriend21 boyfriend = monica.getBoyFriends();
        System.out.println(boyfriend.getName()); // It will print  Clinton Name
        monica.setBoyFriends(null); // It will not impact relationship

        session1.getTransaction().commit();
        session1.close();

        final Session session2 = sessionFactory.openSession();
        session2.beginTransaction();

        BoyFriend21 clinton = (BoyFriend21)session2.load(BoyFriend21.class,10);  // Bill clinton record

        GirlFriend21 girlfriend = clinton.getGirlFriend();
        System.out.println(girlfriend.getName()); // It will print Monica name.
        //But if Clinton[Who owns the relationship as per "mappedby" rule can break this]
        clinton.setGirlFriend(null);
        // Now if Monica tries to check BoyFriend Details, she will find Clinton is no more her boyFriend
        session2.getTransaction().commit();
        session2.close();

        final Session session3 = sessionFactory.openSession();
        session1.beginTransaction();

        monica = (GirlFriend21)session3.load(GirlFriend21.class,10);  // Monica lewinsky record has id  10.
        boyfriend = monica.getBoyFriends();

        System.out.println(boyfriend.getName()); // Does not print Clinton Name

        session3.getTransaction().commit();
        session3.close();
    }
}

A: The entity which has the table with foreign key in the database is the owning entity and the other table, being pointed at, is the inverse entity.

A: To understand this, you must take a step back. In OO, the customer owns the orders (orders are a list in the customer object). There can't be an order without a customer. So the customer seems to be the owner of the orders.
But in the SQL world, one item will actually contain a pointer to the other. Since there is 1 customer for N orders, each order contains a foreign key to the customer it belongs to. This is the "connection" and this means the order "owns" (or literally contains) the connection (information). This is exactly the opposite from the OO/model world.
This may help to understand:
public class Customer {
     // This field doesn't exist in the database
     // It is simulated with a SQL query
     // "OO speak": Customer owns the orders
     private List<Order> orders;
}

public class Order {
     // This field actually exists in the DB
     // In a purely OO model, we could omit it
     // "DB speak": Order contains a foreign key to customer
     private Customer customer;
}

The inverse side is the OO "owner" of the object, in this case the customer. The customer has no columns in the table to store the orders, so you must tell it where in the order table it can save this data (which happens via mappedBy).
Another common example are trees with nodes which can be both parents and children. In this case, the two fields are used in one class:
public class Node {
    // Again, this is managed by Hibernate.
    // There is no matching column in the database.
    @OneToMany(cascade = CascadeType.ALL) // mappedBy is only necessary when there are two fields with the type "Node"
    private List<Node> children;

    // This field exists in the database.
    // For the OO model, it's not really necessary and in fact
    // some XML implementations omit it to save memory.
    // Of course, that limits your options to navigate the tree.
    @ManyToOne
    private Node parent;
}

This explains for the "foreign key" many-to-one design works. There is a second approach which uses another table to maintain the relations. That means, for our first example, you have three tables: The one with customers, the one with orders and a two-column table with pairs of primary keys (customerPK, orderPK).
This approach is more flexible than the one above (it can easily handle one-to-one, many-to-one, one-to-many and even many-to-many). The price is that

*

*it's a bit slower (having to maintain another table and joins uses three tables instead of just two),

*the join syntax is more complex (which can be tedious if you have to manually write many queries, for example when you try to debug something)

*it's more error prone because you can suddenly get too many or too few results when something goes wrong in the code which manages the connection table.

That's why I rarely recommend this approach.

A: Table relationships vs. entity relationships
In a relational database system, there can be only three types of table relationships:

*

*one-to-many (via a Foreign Key column)

*one-to-one (via a shared Primary Key)

*many-to-many (via a link table with two Foreign Keys referencing two separate parent tables)

So, a one-to-many table relationship looks as follows:

Note that the relationship is based on the Foreign Key column (e.g., post_id) in the child table.
So, there is a single source of truth when it comes to managing a one-to-many table relationship.
Now, if you take a bidirectional entity relationship that maps on the one-to-many table relationship we saw previously:

If you take a look at the diagram above, you can see that there are two ways to manage this relationship.
In the Post entity, you have the comments collection:
@OneToMany(
    mappedBy = "post",
    cascade = CascadeType.ALL,
    orphanRemoval = true
)
private List<PostComment> comments = new ArrayList<>();

And, in the PostComment, the post association is mapped as follows:
@ManyToOne(
    fetch = FetchType.LAZY
)
@JoinColumn(name = "post_id")
private Post post;

So, you have two sides that can change the entity association:

*

*By adding an entry in the comments child collection, a new post_comment row should be associated with the parent post entity via its post_id column.

*By setting the post property of the PostComment entity, the post_id column should be updated as well.

Because there are two ways to represent the Foreign Key column, you must define which is the source of truth when it comes to translating the association state change into its equivalent Foreign Key column value modification.
MappedBy (a.k.a the inverse side)
The mappedBy attribute tells that the @ManyToOne side is in charge of managing the Foreign Key column, and the collection is used only to fetch the child entities and to cascade parent entity state changes to children (e.g., removing the parent should also remove the child entities).

It's called the inverse side because it references the child entity property that manages this table relationship.

Synchronize both sides of a bidirectional association
Now, even if you defined the mappedBy attribute and the child-side @ManyToOne association manages the Foreign Key column, you still need to synchronize both sides of the bidirectional association.
The best way to do that is to add these two utility methods:
public void addComment(PostComment comment) {
    comments.add(comment);
    comment.setPost(this);
}

public void removeComment(PostComment comment) {
    comments.remove(comment);
    comment.setPost(null);
}

The addComment and removeComment methods ensure that both sides are synchronized. So, if we add a child entity, the child entity needs to point to the parent and the parent entity should have the child contained in the child collection.

A: Simple rules of bidirectional relationships:
1.For many-to-one bidirectional relationships, the many side is always the owning side of the relationship. Example: 1 Room has many Person (a Person belongs one Room only) -> owning side is Person
2.For one-to-one bidirectional relationships, the owning side corresponds to the side that contains the corresponding foreign key.
3.For many-to-many bidirectional relationships, either side may be the owning side.
Hope can help you.


text:
Q: Относительные пути в запускаемом через cron php файле Ubuntu сервер
В директории на сайте есть php файл по адресу:
/var/www/html/site.ru/parser/parse.php

В этом файле, через относительные пути от его расположения, подключены пара других файлов:
require_once  '../../index.php';

require_once('../../vendor/autoload.php');

И если попытаться запустить файл через консоль (cron) командой:
/usr/bin/php /var/www/html/site.ru/parser/parse.php

То получим ошибки на не найденные директории и файлы, которые подключены в запускаемом php файле '../../index.php'; и '../../vendor/autoload.php'
Вопрос: возможно ли как то запустить файл через консоль и заставить прочитать пути к подключенным файлам без указания прямых адресов?

A: Добавьте к запуску команды в кроне переход в директорию вашего скрипта, например:
* * * * * cd /var/www/html/site.ru/parser/ && /usr/bin/php /var/www/html/site.ru/parser/parse.php


text:
Q: Why variadic macros are not supported by the standard? The standard says:

*

*Variadic macros and functions are not supported.

I can understand it could be difficult to inline a variadic function, since the device may not have a call stack. But why not variadic macros? It's just an ability of preprocessor, even cannot be seen by the compiler. Could some one explain why khronos do not support variadic macro, while many OpenCL implements based on LLVM which is already able to process it without any additional modification?
Another doubt,

*

*Predefined identifiers are not supported.

what does they mean Predefined identifiers? Am I prohibited to write things like #define M_PI 3.14?