In R, how to find the location of a word in a string?

Question: How can I find the first location of specific words in a dataframe cell, and save the output in a new column in the same dataframe?
Ideally I want the first match for each of the words in dictionary.
df <- data.frame(text = c("omg coke is so awsme","i always preferred pepsi", "mozart is so overrated by yeah fanta makes my day, always"))

dict <- c("coke", "pepsi", "fanta")

Location can be N of characters or words preceding the dictionary word.
I've been playing around with the code found here, but I can't make it work.
For example, this code does the job, but only for one word, and for one string (rather than a df and dictionary)
my_string = "omg coke is so awsme"
unlist(gregexpr("coke", my_string))[1]

Desired output:
                                                       text  location
1                                      omg coke is so awsme         2
2                                  i always preferred pepsi         4
3 mozart is so overrated by yeah fanta makes my day, always         7

Like I said, the location can also be string rather than word, if that is easier.
Comment: What do you want as the output?
Comment: Do you want to find the first match among all the words in `dict`? Or the first match for each of the words in `dict`? Do you need to keep track of which word the match is?
Comment: I added: Ideally I want the first match for each of the words in dictionary.
Comment: Okay, so you'll probably want a column of output for each entry in `dict` then, right?
Comment: Yes that's right! Sorry for being unclear.
Comment: Why do you claim that code you have works for the first case yet it gives 5? And the output has 2?
Comment: The provided code finds the character location, not word location, although either one works for me.
Answer: Just run
c(regexpr(paste0(dict,collapse = '|'), df$text))

[1]  5 20 32

Edit:
if you want the location of the words:
library(tidyverse)
pat <-  sprintf(".*(%s)", paste0(dict,collapse = '|'))
df %>%
  mutate(loc = str_count(str_extract(text,pat), "\\w+"))

                                                       text loc
1                                      omg coke is so awsme   2
2                                  i always preferred pepsi   4
3 mozart is so overrated by yeah fanta makes my day, always   7

Answer: Here's a simple for loop:
for(i in dict) {
  df[[i]] = stringi::stri_locate_first_fixed(df$text, i)[, 1]
}
df
#                                                        text coke pepsi fanta
# 1                                      omg coke is so awsme    5    NA    NA
# 2                                  i always preferred pepsi   NA    20    NA
# 3 mozart is so overrated by yeah fanta makes my day, always   NA    NA    32

Or with regexpr (part of base, so no dependencies):
for(i in dict) {
  df[[i]] = regexpr(i, df$text, fixed = TRUE)
}
df
#                                                        text coke pepsi fanta
# 1                                      omg coke is so awsme    5    -1    -1
# 2                                  i always preferred pepsi   -1    20    -1
# 3 mozart is so overrated by yeah fanta makes my day, always   -1    -1    32

And here's a solution for word number, though I would recommend deleting all the punctuation before using this:
df$words = strsplit(df$text, split = " ")
for(i in dict) {
  df[[i]] = sapply(df$words, \(x) match(i, unlist(x)))
}
df
#                                                        text coke pepsi fanta
# 1                                      omg coke is so awsme    2    NA    NA
# 2                                  i always preferred pepsi   NA     4    NA
# 3 mozart is so overrated by yeah fanta makes my day, always   NA    NA     7
#                                                                 words
# 1                                            omg, coke, is, so, awsme
# 2                                         i, always, preferred, pepsi
# 3 mozart, is, so, overrated, by, yeah, fanta, makes, my, day,, always

Answer: require(quanteda)
#> Loading required package: quanteda
#> Package version: 3.2.1
#> Unicode version: 13.0
#> ICU version: 69.1
#> Parallel computing: 8 of 8 threads used.
#> See https://quanteda.io for tutorials and examples.

df <- data.frame(text = c("omg coke is so awsme",
                          "i always preferred pepsi",
                          "mozart is so overrated by yeah fanta makes my day, always"))
dict <- c("coke", "pepsi", "fanta")

corp <- corpus(df)
toks <- tokens(corp)
index(toks, dict)
#>   docname from to pattern
#> 1   text1    2  2    coke
#> 2   text2    4  4   pepsi
#> 3   text3    7  7   fanta

Created on 2022-05-27 by the reprex package (v2.0.1)


How can I make JRadioButton transparent in particular case?

Question: I have a couple of JRadioButton: rb1, rb2; which is contained in transparent JPanel p1, and p1 is contained in a colorful panel, named mainPanel.
I want to make these JRadioButton transparent too and here is what I do:
in mainPanel: mainPanel.setBackground(Color.RED);
in p1: p1.setBackground(new Color(0,0,0,0));
and in rb1 and rb2:
rb1.setOpaque(false);
        rb1.setContentAreaFilled(false);
        rb1.setBorderPainted(false);
        rb2.setOpaque(false);
        rb2.setContentAreaFilled(false);
        rb2.setBorderPainted(false);

it's ok if rb1 and rb2 is contained in mainPanel or if p1 isn't a transparent JPanel, but in my case, the outcome is not what i expected:
How can I resolve this problem? Thanks in advance!
Answer: The weird painting artifacts you're seeing are caused by this:
p1.setBackground(new Color(0,0,0,0));

With that the parent container will not be notified to clear it's background and repaint. So if you want the panel to be completely transparent, just use setOpaque(false) instead. You also just need to call this method on the radio buttons and nothing else.
setOpaque will notify the parent to repaint, but if you want a semi-transparent panel, you have to override paintComponent and call super.paintComponent(Graphics) manually.

import java.awt.Color;
import java.awt.EventQueue;

import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;

public class Example {

    public void createAndShowGUI() {
        JRadioButton encryptButton = new JRadioButton("Encrypt");
        encryptButton.setOpaque(false);

        JRadioButton decryptButton = new JRadioButton("Decrypt");
        decryptButton.setOpaque(false);

        ButtonGroup group = new ButtonGroup();
        group.add(encryptButton);
        group.add(decryptButton);

        JPanel subPanel = new JPanel();
        subPanel.setOpaque(false);
        subPanel.add(encryptButton);
        subPanel.add(decryptButton);

        JPanel mainPanel = new JPanel();
        mainPanel.setBackground(Color.CYAN);
        mainPanel.add(subPanel);

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setContentPane(mainPanel);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Example().createAndShowGUI();
            }
        });
    }

}

Comment: (1+) for using `setOpaque(...)`. You can also check out [Backgrounds With Transparency](https://tips4java.wordpress.com/2009/05/31/backgrounds-with-transparency/) for cases where you want semi transparent backgrounds.
Comment: thank u so much. I used to a trick to take a transparent JLabel but it's not a right way. thank u again which all my respect!


How to remove edge cases for string and number expressions

Question: I'm building a rock, paper, scissors game and working on excluding edge cases.
The function is setPlayerMoves(), which is supposed to set previously undefined global variables for player moves and give them a 'value' between 1-99. how do I excluded edge cases like wrong move type (eg. 'rok') or wrong value (eg. 100).
Here is my incorrect code:
function setPlayerMoves(player, moveOneType, moveOneValue, moveTwoType, moveTwoValue, moveThreeType, moveThreeValue) {
    if (player === 'Player One' && (moveOneType && moveTwoType && moveThreeType === 'rock' || 'paper' || 'scissors') && (moveOneValue && moveTwoValue && moveThreeValue === (>= 1 && <= 99))) {
        playerOneMoveOneType = 'rock';
        playerOneMoveTwoType = 'paper';
        playerOneMoveThreeType = 'scissors';
        playerOneMoveOneValue = 11;
        playerOneMoveTwoValue = 33;
        playerOneMoveThreeValue = 55;
    } else if (player === 'Player Two') {
        playerTwoMoveOneType = 'rock';
        playerTwoMoveTwoType = 'paper';
        playerTwoMoveThreeType = 'scissors';
        playerTwoMoveOneValue = 11;
        playerTwoMoveTwoValue = 33;
        playerTwoMoveThreeValue = 55;
    }
}

Comment: Your JavaScript code invalid as-is, for example `moveThreeValue === (>= 1 && <= 99)` will give you a syntax error because `>=` is a binary operator which in your code has no left-hand operand.
Comment: When doing `moveThreeValue === (>= 1 && <= 99)` I suppose you wanted to do `moveThreeValue >= 1 && moveThreeValue <= 99`
Comment: "which is supposed to set previously undefined global variables" - I strongly recommend against setting any global variables! A key tenet of the current JavaScript developer ecosystem is eliminating uses of global variables (and in software-engineering in general: **mutable static state is a bad thing**(TM)).
Comment: Outright invalid values are not "edge cases" because they don't sit along any conceptual "edge" of a domain of acceptable values: on the contrary, they're very much _outside_ the domain. The correct term is "invalid case".
Comment: Thanks, this is a project that requires global variables - I don't really have a choice, but thanks for the comment.

Yes, I know it's invalid. VScode is quite good at telling me this :) How do i make it valid?
Answer: Problem
Code for checking edge cases are wrong.
(player === 'Player One' && (moveOneType && moveTwoType && moveThreeType === 'rock' || 'paper' || 'scissors') && (moveOneValue && moveTwoValue && moveThreeValue === (>= 1 && <= 99)))

Also you are checking the edge cases for only 'player one'
Solution
Check the values seperately before assigning values and create a valid variable
let valid  = false
let states = ['rock','paper','scissors'];
if((states.indexOf(moveOneType) != -1) && (states.indexOf(moveTwoType) != -1) && (states.indexOf(moveThreeType) != -1)){
 // valid state
valid = true;
}else{
valid = false;
}

if((moveOneValue >=1 && moveOneValue <= 99) && (moveTwoValue >=1 && moveTwoValue <= 99) && (moveThreeValue >=1 && moveThreeValue <= 99)){
 //valid value
 valid = true;
}else{
valid = false
}

Then assign the values.
if ((player === 'Player One') && valid) {
        playerOneMoveOneType = moveOneType;
        playerOneMoveTwoType = moveTwoType;
        playerOneMoveThreeType = moveThreeType;
        playerOneMoveOneValue = moveOneValue;
        playerOneMoveTwoValue = moveTwoValue;
        playerOneMoveThreeValue = moveThreeValue;
    } else if ((player === 'Player Two') && valid) {
        playerTwoMoveOneType = moveOneType;
        playerTwoMoveTwoType = moveTwoType;
        playerTwoMoveThreeType = moveThreeType;
        playerTwoMoveOneValue = moveOneValue;
        playerTwoMoveTwoValue = moveTwoValue;
        playerTwoMoveThreeValue = moveThreeValue;
    }

Also if possible
Create an object each for player1 and player2 like below and use.
let player1 = {
  moveOneType:'rock'
  moveTwoType:'paper'
  moveThreeType:'scissors'
  moveOneValue: 23
  moveTwoValue: 33
  moveThreeValue: 98
}

Comment: Don't be sorry. We too have passed through that stage. You can check seperately like how the value is being checked. But it will result in a long line of code. :). eg: `if((moveOneType == 'rock') || (moveOneType == 'scissors') || (moveOneType == 'paper'))`
Comment: Excellent suggestions!
Comment: Thanks, this is great. But I'm not yet familiar with arrays (sorry, very much a beginner). Is there a way to do it roughly the way I've attempted? Or without an array?


Easy python program

Question: The user is prompted for a file, which in this case is 'histogram.txt'. The program takes each score in the text file and makes a histogram out of all the grades in the file, organizing them so that the user can see how many of each range there are. I wrote out a very simple code:
filename = raw_input('Enter filename of grades: ')

histogram10 = 0
histogram9 = 0
histogram8 = 0
histogram7 = 0
histogram6 = 0
histogram5 = 0
histogram4 = 0
histogram3 = 0
histogram2 = 0
histogram1 = 0
histogram0 = 0

for score in open(filename):
    if score >= 100:
        histogram10 = histogram10 + 1
    elif score >= 90:
        histogram9 = histogram9 + 1
    elif score >= 80:
        histogram8 = histogram8 + 1
    elif score >= 70:
        histogram7 = histogram7 + 1
    elif score >= 60:
        histogram6 = histogram6 + 1
    elif score >= 50:
        histogram5 = histogram5 + 1
    elif score >= 40:
        histogram4 = histogram4 + 1
    elif score >= 30:
        histogram3 = histogram3 + 1
    elif score >= 20:
        histogram2 = histogram2 + 1
    elif score >= 10:
        histogram1 = histogram1 + 1
    elif score >= 0:
        histogram0 = histogram0 + 1

print
print 'Grade Distribution'
print '------------------'
print '100     :',('*' * histogram10)
print '90 - 99 :',('*' * histogram9)
print '80 - 89 :',('*' * histogram8)
print '70 - 79 :',('*' * histogram7)
print '60 - 69 :',('*' * histogram6)
print '50 - 59 :',('*' * histogram5)
print '40 - 49 :',('*' * histogram4)
print '30 - 39 :',('*' * histogram3)
print '20 - 29 :',('*' * histogram2)
print '10 - 19 :',('*' * histogram1)
print '00 - 09 :',('*' * histogram0)

however whenever i run the program, all twenty grades get recorded onto the >= 100
like this:
100    : ********************
90-99  :
80-89  :

etc.
... How do I make it so that the program puts the stars in the correct places?
Comment: Always step 1: make sure the data that is getting into the program is correct.
Comment: you are comparing string with numbers...
Comment: A little tip: Instead of having 11 different variables for the histogram, you could use a list and calculate the index, e.g. `histogram[min(100, score) / 10] += 1`. The `min` is to put all scores above 100 in the same slot. For more general data, like counting the number of words in a text, you could use a dictionary.
Comment: [Any number is always less than any string in Python 2.](http://stackoverflow.com/questions/7969552/why-does-4-3-return-true-in-python-2)
Comment: One liner just for fun `any(__import__('sys').stdout.write('<= {} \t {}\n'.format(i * 10 + 10, '*' * num))
    for i, num in ((k, len(list(g)))
        for k, g in __import__('itertools').groupby(
            sorted(int(score.strip())
                for score in open(raw_input('Enter filename of grades: '))),
                    key = lambda score: (score - 1) / 10)))`.
Answer: Data read from a file is a string. Convert it to an integer first by passing it to int().
>>> int('25')
25

Answer: You need to convert score to int before comparing.
score = int(score)  # convert to int
if score >= 100:
    histogram10 = histogram10 + 1
# other cases

If you have blank lines in input file then you have to add necessary check before converting to int. Also instead of ten different variables you can easily use a list.
Comment: Please go through the list tutorial http://docs.python.org/tutorial/introduction.html#lists. For `histogram0` you can use `l[0]`, for `histogram1` you can use `l[1]` and so on.
Comment: thank you for this i also appreciate the advice. im still very new at compsci :P if you don't mind can you explain how to use a list with this?

Easy python program


WoW addon to figure out most profitable jewelcrafting route

Question: I currently have 525 jewelcrafting and 525 leather working. I'm wondering if there is a solid add-on that would be able to perhaps scan the auction house to understand the economy better on my particular server, and then give me a list of the most profitable things to cut/craft? Any tips are welcome for automating the profit route.
Comment: It's been a while since i played wow, but i used to work with Auctioneer, after a few days of scanning the prices you get will be give or take correct.
Answer: As Lyrion said, Auctioneer is probably the most popular auction house tool for gathering information.  But I have found that no one add-on always gives you everything you need.  You may want to check out some other auction/crafting mods, such as Auctionator and TradeSkillMaster, which can help you to optimize your crafting.  Regardless of the convenience of the tools you use, a big part of crafting and playing the market will be the manual tasks of paying attention and recognizing demand.


Prove $G = \{ a + b \hat{i} +c \hat{j} +d \hat{k} : a,b,c,d \in \mathbb{R} \}$ is a locally compact topological group

Question: Let $G = \{ a + b \hat{i} +c \hat{j} +d \hat{k} : a,b,c,d \in \mathbb{R} \}$ be the group of non-null quaternions. I need to prove that $G$ is locally compact topological group by showing that $G$ can be viewed as an open subset of $\mathbb{R^4}$ .
Also can someone please explain how to compute the Haar measure on $G$ ?
Answer: The quaternions are in bijection with $\mathbb{R}^4$ via $a+bi+cj+dk \mapsto (a,b,c,d)$.
The nonzero quaternions are then in bijection with $G = \mathbb{R}^4 \setminus \{(0,0,0,0)\}$.  An open subset of a locally compact topological space is locally compact.
Let's check that multiplication of quaternions is a continuous function.  By the universal property of the product topology, we just need to check that multiplcation $X \times X \rightarrow \mathbb{R}^4$ is a continuous function componentwise into $\mathbb{R}^4$.  For example, if you multiply $(a+bi+cj+dk)(a'+b'i+c'j+d'k)$ and collect the constant term, you get $aa' -bb' - cc' - dd'$, which is definitely continuous as a function of the variables $a,a',b,b'$ etc.
Let's compute the Haar measure on $G$.  Define a positive linear functional $T: C_c(G) \rightarrow \mathbb{C}$ by
$$T(f) = \int_{-\infty}^{\infty}  \int_{-\infty}^{\infty}  \int_{-\infty}^{\infty}  \int_{-\infty}^{\infty} \frac{f(x,y,z,w)}{x^2 + y^2 + z^2 + w^2} dx \space dy \space dz \space dw$$
You have to check that $T$ is well defined on those functions $f: \mathbb{R}^4 \setminus \{(0,0,0,0) \}$ which are continuous and of compact support.  By the Riesz representation theorem, there will exist a unique Radon measure $\mu$ on the Borel sets of $G$ such that $T(f) = \int\limits_G f d\mu$ for all $f \in C_c(G)$.  You also have to check that if $g \in G$, and $f \in C_c(G)$, then $T(L_g(f)) = T(R_g(f)) = T(f)$, where $L_g(f)(x) = f(gx)$ and $R_g(f)(x) = f(xg)$.  This implies that $\mu$ is moreover a left and right Haar measure.


Secret Word Game - Python

Question: I'm starting to study programming now and I have to do a secret word game, but whenever I run the code the result is concatenated and it was supposed to appear only once, where am I going wrong? I'll paste the code and attach a screenshot of the console.
I'm open to other tips and improvements.
print('¨' * 40)
print(f'|{"Secret Word Game":^38}|')
print('¨' * 40)

secret_word = 'believer'
user_input = ''
typed = []
attempts= 0
number_of_letters = '_ ' * len(secret_word)
discovering_secret_word = ''

print('Try to guess the Secret Word!')
print(f'The secret word is: {number_of_letters}')

while discovering_secret_word != secret_word:

    user_input = input('Type a letter: ')
    attempts += 1

    if len(user_input) > 1:
        print('You can´t insert more than one letter!')
        continue

    typed.append(user_input)

    for letter in secret_word:
        if letter in typed:
            discovering_secret_word += letra
        else:
            discovering_secret_word += '_ '
    print(f'The Secret Word is {discovering_secret_word}')
else:
    print('Congratulations, you won!')
    print(f'The Secret Word is {secret_word}.')
    print(f'It took {attempts} attempts.')
`

Console
Comment: Did you mean `discovering_secret_word += letter`?
Comment: I think you need to _reset_ `discovering_secret_word` before the loop..  Set it to an empty string again.
Comment: Did you find the solution useful? If so, upvoting/accepting it would be appreciated.
Answer: The issue occurs because your are not resetting the discovering_secret_word string. You are constantly concatenating into it. Here is what you need to do:
print('¨' * 40)
print(f'|{"Secret Word Game":^38}|')
print('¨' * 40)

secret_word = 'believer'
user_input = ''
typed = []
attempts = 0
number_of_letters = '_ ' * len(secret_word)
discovering_secret_word = ''

print('Try to guess the Secret Word!')
print(f'The secret word is: {number_of_letters}')

while discovering_secret_word != secret_word:

    user_input = input('Type a letter: ')
    attempts += 1

    if len(user_input) > 1:
        print('You can´t insert more than one letter!')
        continue

    typed.append(user_input)

    # reset discovering_secret_word
    discovering_secret_word = ""
    for letter in secret_word:
        if letter in typed:
            discovering_secret_word += letter # Fixed to letter had letra before
        else:
            discovering_secret_word += '_ '
    print(f'The Secret Word is {discovering_secret_word}')
else:
    print('Congratulations, you won!')
    print(f'The Secret Word is {secret_word}.')
    print(f'It took {attempts} attempts.')

This is what my console looked like after I attempted to solve for the secret word:
¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨
|           Secret Word Game           |
¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨
Try to guess the Secret Word!
The secret word is: _ _ _ _ _ _ _ _
Type a letter: b
The Secret Word is b_ _ _ _ _ _ _
Type a letter: b
The Secret Word is b_ _ _ _ _ _ _
Type a letter: e
The Secret Word is be_ _ e_ e_
Type a letter: l
The Secret Word is bel_ e_ e_
Type a letter: i
The Secret Word is belie_ e_
Type a letter: v
The Secret Word is believe_
Type a letter: r
The Secret Word is believer
Congratulations, you won!
The Secret Word is believer.
It took 7 attempts.

Secret Word Game - Python


How do I solve $\lim_{x\to +\infty}\frac {\ln(x-1)^2}{x} $?

Question: I just can't get past the $x-1$. The $2$ I know how to get rid of.
$$\lim_{x\to +∞}\frac {\ln\left((x-1)^2\right)}{x}  $$
Comment: Are you aware of L'Hospital's Rule?
Comment: $$= \lim_{x \to \infty} \frac{\ln(x)^2}{x + 1} = ...$$
Comment: Let $u=x-1.$ then $u\rightarrow\infty.$
Comment: is the numerator $\ln^2(x-1)$ or $\ln ((x-1)^2)$?
Comment: It's the second one, like I put it... I don't think I'm familiar with that rule, haven't learnt it yet.
Comment: $\lim_{x \rightarrow + \infty} \dfrac{\ln((x-1)^2)}{x}=\lim_{x \rightarrow + \infty} \dfrac{2 \ln(x-1)}{x}=0$ since the logarithm grows asymptotically slower than the polynomial.
Comment: That cannot be solved without L'Hôspital. You may copy it wrong.
Comment: @TheodorosMpalis The function itself was just f(x) = ln (x-1)^2 , I didn't copy wrong, just divided by x to find the m for the oblique asymptote, but thank you anyway...
Answer: $$\lim_{x\to \infty} \frac{\ln(x-1)^2}{x}$$
It is not hard to show $\ln x< x$
$\ln(x-1)^2=4\ln\sqrt{x-1}\leq 4\sqrt{x-1}\leq 4\sqrt x$
So the limit is smaller than
$$\lim_{x\to \infty} \frac{4\sqrt{x}}{x}=\lim_{x\to \infty} \frac 4{\sqrt x}=0$$
Now the following is true because square root must be non negative
$-4\sqrt x\leq ln(x-1)^2$
So the limit is bounded by $0$
Answer: Use equivalents:
$(x-1)^2\sim_\infty x^2$ and none of them approach $1$ in a neighbourhood of $+\infty$, hence $\;\ln(x-1)^2\sim_\infty \ln x^2=2\ln x\;$ and finally
$$\frac{\ln(x-1)^2}{x}\sim_\infty2\,\frac{\ln x}x \to 0.$$
Note: In general equivalence of functions is not compatible with composition on the left with another function.
Comment: You probably should be careful introducing this notation to a beginner.  For instance $\exp((x-1)^2)$ is **not** asymptotic to $\exp(x^2)$, but that won't be at all clear to OP.
Comment: @Erick Wong: You're right. I've  added a short caveat.
Answer: By applying L'Hôpital's rule you have:
$$\lim_{x\rightarrow \infty} (\ln(x-1)^2)'=\lim_{x\rightarrow \infty} \frac{2}{x-1}=0$$
and $$\lim_{x\rightarrow \infty}(x)'=1$$
Therefore the limit $$\lim_{x\rightarrow \infty}\frac{(\ln(x-1)^2)'}{x'}=\frac{0}{1}=0$$
exists and it is equal to
$$\lim_{x\to +∞}\frac {ln(x-1)^2}{x}$$
Comment: @TheodorosMpalis Well, it's a good time to look at it then..
Comment: @MathematicianByMistake Thank you anyway!
Comment: She said she hasn't learned L'Hôspital yet
Comment: I understand that principle, it's easy to comprehend, we use derivatives... I'm just not suposed to use it yet..
Comment: @Tatiana So, was this given as an exercise that you are supposed to solve without L'Hospital?
Comment: Yes I mean, since I haven't learned that yet...
The exercise was to find asymptotes for f(x)= ln(x-1)^2 , so to find the oblique asymptote I did the limit of the function divided by x to find the m... That's what got me to that expression....
Comment: @Tatiana I see..Well, check Bububu's answer then. I hope that when you do study L'Hospital's, you will find this more usefull!


StartCoroutine() to fix targetTexture.ReadPixels error

Question: As the title suggests I have a problem with the error occurring at the row
targetTexture.ReadPixels(new Rect(0, 0, cameraResolution.width, cameraResolution.height), 0, 0);

Error:

ReadPixels was called to read pixels from system frame buffer, while
  not inside drawing frame. UnityEngine.Texture2D:ReadPixels(Rect,
  Int32, Int32)

As I have understood from other posts one way to solve this issue is to make a Ienumerator method which yield return new WaitForSeconds or something, and call it like:  StartCoroutine(methodname) so that the frames gets to load in time so that there will be pixels to read-ish.
What I don't get is where in the following code this method would make the most sense. Which part does not get to load in time?
    PhotoCapture photoCaptureObject = null;
    Texture2D targetTexture = null;
    public string path = "";
    CameraParameters cameraParameters = new CameraParameters();

private void Awake()
{

    var cameraResolution = PhotoCapture.SupportedResolutions.OrderByDescending((res) => res.width * res.height).First();
    targetTexture = new Texture2D(cameraResolution.width, cameraResolution.height);

    // Create a PhotoCapture object
    PhotoCapture.CreateAsync(false, captureObject =>
    {
        photoCaptureObject = captureObject;
        cameraParameters.hologramOpacity = 0.0f;
        cameraParameters.cameraResolutionWidth = cameraResolution.width;
        cameraParameters.cameraResolutionHeight = cameraResolution.height;
        cameraParameters.pixelFormat = CapturePixelFormat.BGRA32;
    });
}

private void Update()
{
    // if not initialized yet don't take input
    if (photoCaptureObject == null) return;

    if (Input.GetKey("k") || Input.GetKey("k"))
    {
        Debug.Log("k was pressed");

        VuforiaBehaviour.Instance.gameObject.SetActive(false);

        // Activate the camera
        photoCaptureObject.StartPhotoModeAsync(cameraParameters, result =>
        {
            if (result.success)
            {
                // Take a picture
                photoCaptureObject.TakePhotoAsync(OnCapturedPhotoToMemory);
            }
            else
            {
                Debug.LogError("Couldn't start photo mode!", this);
            }
        });
    }
}

private static string FileName(int width, int height)
{
    return $"screen_{width}x{height}_{DateTime.Now:yyyy-MM-dd_HH-mm-ss}.png";
}

private void OnCapturedPhotoToMemory(PhotoCapture.PhotoCaptureResult result, PhotoCaptureFrame photoCaptureFrame)
{
    // Copy the raw image data into the target texture
    photoCaptureFrame.UploadImageDataToTexture(targetTexture);

    Resolution cameraResolution = PhotoCapture.SupportedResolutions.OrderByDescending((res) => res.width * res.height).First();

    targetTexture.ReadPixels(new Rect(0, 0, cameraResolution.width, cameraResolution.height), 0, 0);
    targetTexture.Apply();

    byte[] bytes = targetTexture.EncodeToPNG();

    string filename = FileName(Convert.ToInt32(targetTexture.width), Convert.ToInt32(targetTexture.height));
    //save to folder under assets
    File.WriteAllBytes(Application.streamingAssetsPath + "/Snapshots/" + filename, bytes);
    Debug.Log("The picture was uploaded");

    // Deactivate the camera
    photoCaptureObject.StopPhotoModeAsync(OnStoppedPhotoMode);
}

private void OnStoppedPhotoMode(PhotoCapture.PhotoCaptureResult result)
{
    // Shutdown the photo capture resource
    VuforiaBehaviour.Instance.gameObject.SetActive(true);
    photoCaptureObject.Dispose();
    photoCaptureObject = null;

}

Sorry if this counts as a duplicate to this for example.

Edit
And this one might be useful when I get to that point.
Is it so that I don't need these three lines at all?
Resolution cameraResolution = PhotoCapture.SupportedResolutions.OrderByDescending((res) => res.width * res.height).First();
targetTexture.ReadPixels(new Rect(0, 0, cameraResolution.width, cameraResolution.height), 0, 0);
targetTexture.Apply();

As written in the comments the difference between using these three lines and not is that the photo saved has a black background + the AR-GUI. Without the second line of code above is a photo with the AR-GUI but with the background is a live stream of my computer webcam. And really I don't wanna see the computer webcam but what the HoloLens sees.
Comment: wait what are you going to do there? `targetTexture.ReadPixels(new Rect(0, 0, cameraResolution.width, cameraResolution.height), 0, 0);` (tries to) makes a **Screenshot** .. therefore you have to wait until the end of the frame so everything is already rendered ... do you really want to make a screenshot and overwrite your texture right after taking a picture with the photocapture?
Comment: No, my point was the 3 code lines `Resolution cameraResolution = PhotoCapture.SupportedResolutions.OrderByDescending((res) => res.width * res.height).First();

    targetTexture.ReadPixels(new Rect(0, 0, cameraResolution.width, cameraResolution.height), 0, 0);
    targetTexture.Apply();` make no sense to me ... you try to overwrite the just received texture from the photocapture with a screenshot ... (and cameraResolution also is the resolution of the device's camera not the screen resolution btw). What exactly do you need to crop the texture for?
Comment: @FearlessFox I don't know but I guess you can but it's probably really complex. The HoloLens has it's device portal which provides an access to the devices camera (but including holograms). Also I don't know if it allows you access it via sockets or maybe [Serial Port](https://assetstore.unity.com/packages/tools/utilities/serial-port-utility-pro-125863). However best would be you deploy and test on the device directly and on a PC use a webcam instead.
Comment: umm, @derHugo well that sounds kinda unnecessary, is that the row above the readPixels row setting the `cameraResolution`? (and honestly I would like to crop the captured photo from the center in the end and am thinking that maybe that is possible with this code row? Beginning the new rect at other pixels than 0, 0)
Comment: Possible duplicate of [How To Crop Captured Image? --C#](https://stackoverflow.com/questions/43822132/how-to-crop-captured-image-c)
Comment: So I don't need any of these for my purpose really? O.o

When capturing a photo with this (redundant) code the photo saved has a black background and the AR-GUI I've added and without the code is the AR-GUI but with the background is a live stream of my computer webcam. And really I don't wanna see the computer webcam but what the HoloLens sees. (@derHugo sorry man for me being all over the place)
Comment: @derHugo for being anymore annoying I also have trouble taking more than one photo. The pressed key only registers once (if at all, have had some problems with that too...) and does not react at all when pushed a second time when the `OnStoppedPhotoMode` is done running.
Comment: @derhugo This is not a duplicate since the question involves an XR camera rather than a web camera so the solutions vary.  Plus, no cropping.
Comment: @ickydime it is the same since the duplicate isn't about how to crop an image specifically for a we come but a `Texture2D` in general... What do you think is the difference between a webcam and the XR devices camera?
Comment: @derhugo They are different APIs. Sure, they both are similar concepts in that you capture a byte array and apply that array to a texture.  But a webcam does not capture the mixed reality so it would be useless in this use case.  The author needs to use the XR code here: https://docs.unity3d.com/ScriptReference/XR.WSA.WebCam.PhotoCaptureFrame.CopyRawImageDataIntoBuffer.html
Comment: @fearlessFox When you say are you seeing your live stream of your computer... are you running on your computer?  Have you tried running this on the Hololens?  The Hololens shouldn't have access to your computer's webcam.
Comment: @ickydime the code from [PhotoCapture](https://docs.unity3d.com/2017.3/Documentation/ScriptReference/XR.WSA.WebCam.PhotoCapture.html) is exactly the same for a webcam or the HoloLens camera .. Unity makes no difference. If you are using it with a webcam on a PC the Holograms simply will be the ones visiable in the Game the moment you take the picture. However as you can see OP used `PhotoCapture.Create(false, ...` so holograms will not be included anyway. and he should stay with `UploadImageDataToTexture` to directly get a `Texture2D` instead of calculate it.
Comment: @ickydime now thinking about it I don't really think we have to see the ar in the photo itself, only when using the app.
Comment: @derHugo Do you know if it is possible to use the hololens camera and not the webcam when trying out app in unity (before building). also asked: https://developer.vuforia.com/forum/hololens/display-project-hololens-not-computer-webcam
Comment: @derHugo Ah okay, I like it easy so I guess I'll try it with deploy :) Also really big thanks to you for all the help you provided!
Answer: Your three lines
Resolution cameraResolution = PhotoCapture.SupportedResolutions.OrderByDescending((res) => res.width * res.height).First();

targetTexture.ReadPixels(new Rect(0, 0, cameraResolution.width, cameraResolution.height), 0, 0);
targetTexture.Apply();

make not much sense to me. Texture2D.ReadPixels is for creating a Screenshot so you would overwrite the texture you just received from PhotoCapture with a screenshot? (Also with incorrect dimensions since camera resolution very probably != screen resolution.)
That's also the reason for

As written in the comments the difference between using these three lines and not is that the photo saved has a black background + the AR-GUI.

After doing
photoCaptureFrame.UploadImageDataToTexture(targetTexture);

you already have the Texture2D received from the PhotoCapture in the targetTexture.
I think you probably confused it with Texture2D.GetPixels which is used to get the pixel data of a given Texture2D.

I would like to crop the captured photo from the center in the end and am thinking that maybe that is possible with this code row? Beginning the new rect at other pixels than 0, 0)

What you actually want is cropping the received Texture2D from the center as you mentioned in the comments. You can do that using GetPixels(int x, int y, int blockWidth, int blockHeight, int miplevel) which is used to cut out a certain area of a given Texture2D
public static Texture2D CropAroundCenter(Texture2D input, Vector2Int newSize)
{
    if(input.width < newSize.x || input.height < newSize.y)
    {
        Debug.LogError("You can't cut out an area of an image which is bigger than the image itself!", this);
        return null;
    }

    // get the pixel coordinate of the center of the input texture
    var center = new Vector2Int(input.width / 2, input.height / 2);

    // Get pixels around center
    // Get Pixels starts width 0,0 in the bottom left corner
    // so as the name says, center.x,center.y would get the pixel in the center
    // we want to start getting pixels from center - half of the newSize
    //
    // than from starting there we want to read newSize pixels in both dimensions
    var pixels = input.GetPixels(center.x - newSize.x / 2, center.y - newSize.y / 2, newSize.x, newSize.y, 0);

    // Create a new texture with newSize
    var output = new Texture2D(newSize.x, newSize.y);

    output.SetPixels(pixels);
    output.Apply();

    return output;
}

for (hopefully) better understanding this is an illustration what that GetPixels overload with the given values does here:

and than use it in
private void OnCapturedPhotoToMemory(PhotoCapture.PhotoCaptureResult result, PhotoCaptureFrame photoCaptureFrame)
{
    // Copy the raw image data into the target texture
    photoCaptureFrame.UploadImageDataToTexture(targetTexture);

    // for example take only half of the textures width and height
    targetTexture = CropAroundCenter(targetTexture, new Vector2Int(targetTexture.width / 2, targetTexture.height / 2);

    byte[] bytes = targetTexture.EncodeToPNG();

    string filename = FileName(Convert.ToInt32(targetTexture.width), Convert.ToInt32(targetTexture.height));
    //save to folder under assets
    File.WriteAllBytes(Application.streamingAssetsPath + "/Snapshots/" + filename, bytes);
    Debug.Log("The picture was uploaded");

    // Deactivate the camera
    photoCaptureObject.StopPhotoModeAsync(OnStoppedPhotoMode);
}

Or you could make it an extension method in an apart static class like
public static class Texture2DExtensions
{
    public static void CropAroundCenter(this Texture2D input, Vector2Int newSize)
    {
        if (input.width < newSize.x || input.height < newSize.y)
        {
            Debug.LogError("You can't cut out an area of an image which is bigger than the image itself!");
            return;
        }

        // get the pixel coordinate of the center of the input texture
        var center = new Vector2Int(input.width / 2, input.height / 2);

        // Get pixels around center
        // Get Pixels starts width 0,0 in the bottom left corner
        // so as the name says, center.x,center.y would get the pixel in the center
        // we want to start getting pixels from center - half of the newSize
        //
        // than from starting there we want to read newSize pixels in both dimensions
        var pixels = input.GetPixels(center.x - newSize.x / 2, center.y - newSize.y / 2, newSize.x, newSize.y, 0);

        // Resize the texture (creating a new one didn't work)
        input.Resize(newSize.x, newSize.y);

        input.SetPixels(pixels);
        input.Apply(true);
    }
}

and use it instead like
targetTexture.CropAroundCenter(new Vector2Int(targetTexture.width / 2, targetTexture.height / 2));

Note:

UploadImageDataToTexture: You may only use this method if you specified the BGRA32 format in your CameraParameters.

Luckily you use that anyway ;)

Keep in mind that this operation will happen on the main thread and therefore be slow.

However the only alternative would be CopyRawImageDataIntoBuffer and generate the texture in another thread or external, so I'ld say it is ok to stay with UploadImageDataToTexture ;)
and

The captured image will also appear flipped on the HoloLens. You can reorient the image by using a custom shader.

by flipped they actually mean that the Y-Axis of the texture is upside down.  X-Axis is correct.
For flipping the Texture vertically you can use a second extension method:
public static class Texture2DExtensions
{
    public static void CropAroundCenter(){....}

    public static void FlipVertically(this Texture2D texture)
    {
        var pixels = texture.GetPixels();
        var flippedPixels = new Color[pixels.Length];

        // These for loops are for running through each individual pixel and
        // write them with inverted Y coordinates into the flippedPixels
        for (var x = 0; x < texture.width; x++)
        {
            for (var y = 0; y < texture.height; y++)
            {
                var pixelIndex = x + y * texture.width;
                var flippedIndex = x  + (texture.height - 1 - y) * texture.width;

                flippedPixels[flippedIndex] = pixels[pixelIndex];
            }
        }

        texture.SetPixels(flippedPixels);
        texture.Apply();
    }
}

and use it like
targetTexture.FlipVertically();

Result: (I used FlipVertically and cropp to the half of size every second for this example and a given Texture but it should work the same for a taken picture.)

Image source: http://developer.vuforia.com/sites/default/files/sample-apps/targets/imagetargets_targets.pdf

Update
To your button problem:
Don't use
if (Input.GetKey("k") || Input.GetKey("k"))

First of all you are checking the exact same condition twice. And than GetKey fires every frame while the key stays pressed. Instead rather use
if (Input.GetKeyDown("k"))

which fires only a single time. I guess there was an issue with Vuforia and PhotoCapture since your original version fired so often and maybe you had some concurrent PhotoCapture processes...
Comment: Yes as far as I remember! For some reason afaik the Camera in the HoloLens is actually always flipped on Y. Sometimes while Vuforia was initializing I could even notice that all displayed holograms where also flipped vertically for a short moment. ^^ The reason I don't know but it might have to do something that Unity starts the Textrue Y coordinates at the bottom instead of the top. Simplest way would be just test it ;)
Comment: well the thing is there might be a lot of pixels (e.g. `1280×720 = 921600 pixels` and VS might have some trouble to load and display that array correctly). The second issue did you make sure you have `targetTexture.Apply();` after you cropped it? Otherwise yes it should be overwritten.
Comment: ok I don't know why but ... forget about the Extension Method version .. just use the normal `public static Texture2D CropAroundCenter ...` apparently I lied and you can't overwrite the input texture inside an extension method using `new Texture2D(...)`. I'll update my answer
Comment: and here I am once again .. I figured out how you still can do it as an extension method :)
Comment: Also this last part about the flip: I'm not gonna show the photo in hololens but send it further to an API (I got the code just haven't implemented it yet ^^),  does the photo taken also get affected by this flip?
Comment: When debugging I try to see what `pixels` has for a value but visual studio and unity just buggs out leaving a `StackoverflowException` :S
Comment: And it does not seem to give `targetTexture` new value after calling `CropAroundCenter` but that is what is supposed to happen right? So that the image getting saved is the cropped one?
Comment: hahah! I just got it to work with the other one hah! But really great answers Hugo! Today actually feels lika productive day thanks to you :)

Another problem though is why am I only able to activate `Input.GetKeydown("k")` once? It does not register the second time around.. (maybe I should make a new question)
Comment: You're welcome :) You should re check that `GetKeyDown` thing again ... in the code you posted you used `GetKey("k")` instead which fires every frame
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/190848/discussion-between-fearlessfox-and-derhugo).


Air compressor makes LEDs flicker

Question: About 2 years ago I converted an automotive shop from florescent to LED T8(120 volt). They worked great until we changed the compressor today to a new more efficient and more powerful one (both 240 volt. the old was 20 amp, new 32 amp). 200 amp service.
The lights flicker like crazy while the compressor is running. An unacceptable amount. This is probably from the large inductive startup load? I have checked many things. Loose connections, voltage drop. everything seems to be wired correctly. I have even discussed with knowledgeable electricians.
It seems this is a not so common problem surfacing with the new LED technology. The solutions I have come up with are, 1. have power company supply dedicated service just for compressor. 2. change the size of pulley to reduce the demand of the motor(may or may not fix the problem).
Can anyone provide any input?
Thanks
Kenny
Comment: There was a great part of "Hunt for Red October" where an Alfa sub was sprinting, running the reactor's turbines and cooling pumps so hard the whole reactor was shaking.  The operator noticed the pressure gauge jiggling and figured it was shaking just like the rest of the ship.  In fact it was *not* shaking, it was  accurately indicating pressure variations.  I wonder if this larger compressor is exposing real problems in your electrical panel or service lateral which are causing your line voltage to actually vary, and the LEDs are faithfully reflecting that.
Comment: The best way to see what is going on, is to do measurements. If you don't have the equipment to do that, hire a professional. Is that 240V split phase? What kind of LED lamp do you have? Most good LED lamps are fed by SMPS which do not really care about voltage variations unless its really really bad.
Comment: Is this shop on a separate sub panel?  You said automotive shop so that makes me think commercial with its own service. 32 amps should not be a problem unless the main panel is very small like a 60 amp panel then I could see possible issues with loading and emf noise generated by the compressor, if the voltage is good I would verify the grounding especially if the ballast are still in use modern ballast start having problems if the neutral to ground voltage goes over .5v and some will not work at all at 2v or this is what I have found and sometimes requires an additional ground rod.
Comment: I think you answered your own question OP, You said "more powerful one" and I'm guessing it wasn't previously like that with the old compressor, have you checked the amp draw of the compressor while the light and everything on the circuit are on.
Answer: I believe I may be experiencing the inverse of your situation
My ceiling fan power is separate from the LED lights in the fan. If the fan isn't powered up to 100%, the lights flicker like crazy. Once it's turned up all the way... they're fine.
... so my theory is... you don't have enough juice any more. Assuming these are bulbs, if you unscrew a few, and run the compressor, do the remaining still flicker?
I think the dedicated service for the compressor is a good train of thought. I only question sustainability over the long term and future growth. You may want to look into your current wiring set up for a possible more permanent fix.
Answer: When you changed the compressor did you verify the wire is heavy enough for the larger load?  Pulling half again more current on the same size wire would cause more voltage drop. A common voltmeter may not respond fast enough to show the pulsating voltage. At the very least, put the lights on a separate circuit from the compressor.
I like your idea of changing to a smaller pulley to reduce the torque load on the motor (hence, the motor current) but that'll reduce your compressor output volume, and it's probably easiest to change the light wiring if needed.
Answer: It could be an enormous variety of factors that are all compounding into what you're seeing or just one or two major issues, the only thing you can do is call in an electrician to actually determine the causative factors here. Not discussions, physically in the building and checking and measuring things.
If the supply from the service provider is rapidly dropping when the inrush of the compressor starts then you need to deal with the utility or upgrade the wiring to the compressor. You didn't indicate you did this during the updates so I'm suspicious of the branch circuit supplying the power to the new higher load compressor.
If the supply from the service provider isn't fluctuating severely then you have cheap lights that can't compensate for minor voltage fluctuation and your only recourse is to either scrap them for better units or find someone to upgrade the power supplies inside them with better capacitors.
Cheap chineseium electronics have a bad tendency to be poorly engineered and the power supplies are terrible, the only way to fix that is to buy better equipment or have someone that knows about electrical engineering reverse engineer the design to determine the faults. Then they can advise you to either purchase better power supplies or modify the existing components with better materials.

Air compressor makes LEDs flicker


Does Ubuntu have a Kernel Splash Screen? If so, how to enable it?

Question: Hi I am creating a custom distro based off of Ubuntu 19.04 server.
I am looking for a way to enable a custom kernel splash screen.
Please let me know if this is possible, thanks.
Comment: You meant a boot splash screen? That is done with "plymouth" https://askubuntu.com/questions/1046370/how-to-change-boot-splash-screen-in-18-04 as an example
Comment: So it can be done in Manjaro. https://youtu.be/2Mb3gb7wspI
Comment: No I mean a kernel splash screen, not plymouth. https://youtu.be/2Mb3gb7wspI there is an example of what I mean. Here is a link to the manjaro forum for the kernel splash screen. https://forum.manjaro.org/t/bootsplash-provided-by-the-kernel/34467/170
Comment: I only saw a `plymouth` screen also called 'boot splash' on the youtube video you linked. You use `splash` on the kernel line [in grub] to make the plymouth screen show on booting.
Answer: Grub Theme
What you are looking for is a Grub Theme that runs before the kernel loads with Plymouth splash screen:
Here's my Grub Theme which is a spin on Tux theme referenced in your links:
Comment: No that's not what I am looking for.


Transpose a dataframe

Question: I have a dataframe like this:
df = data.frame (Gender = c ("F", "M", "M", "F"),
  cat_age = c ("] 10-15]", "] 10, 15]", "] 20 -25] ","] 55-60] "),
  frequency = c (2, 6, 8, 7))

I would like to transform it like this:
F; M; cat_age
2; 6; ] 10, 15]
0; 8; ] 20, 25]
7; 0; ] 55, 60]

Answer: There's something weird with your data.frame, if "] 10-15]" and "] 10, 15]" are supposed to be the same category, you need to make it so in the data.frame. For example:
df = data.frame (Gender = c ("F", "M", "M", "F"),
cat_age = c ("] 10-15]", "] 10-15]", "] 20 -25] ","] 55-60] "), frequency = c (2, 6, 8, 7))

Then you can use pivot_wider() from tidyr:
library(tidyr)

pivot_wider(df,values_from=frequency,names_from=Gender,values_fill=0)
# A tibble: 3 x 3
  cat_age          F     M
  <fct>        <dbl> <dbl>
1 "] 10-15]"       2     6
2 "] 20 -25] "     0     8
3 "] 55-60] "      7     0

Comment: you could `%>% select(F, M, cat_age)` if you want to re-order the columns as shown in the example ...
Answer: Here is a base R option using reshape
dfout <- reshape(
  transform(df,
    cat_age = sapply(
      regmatches(cat_age, gregexpr("\\d+", cat_age)),
      function(x) paste0("]", paste0(x, collapse = ","), "]")
    )
  ),
  direction = "wide",
  idvar = "cat_age",
  timevar = "Gender"
)

which gives
> dfout
  cat_age frequency.F frequency.M
1 ]10,15]           2           6
3 ]20,25]          NA           8
4 ]55,60]           7          NA

If you want to replace NA by 0, you can add one more line
replace(df,is.na(df),0)

such that
> replace(dfout,is.na(dfout),0)
  cat_age frequency.F frequency.M
1 ]10,15]           2           6
3 ]20,25]           0           8
4 ]55,60]           7           0

Transpose a dataframe


Merge multiple Point Clouds into a single 3D object

Question: I am testing the Intel RealSense D435 camera and have been able to create multiple Point Clouds (.ply) of a certain object. Each Point Cloud is taken in a different viewing angle of the object.
Now I wish to merge all these point clouds into a single, 3D Object. I have tried CloudCompare but this requires manual cropping of outliers and noisy data, as well as translating each Point cloud.
I wonder if there is a piece of code that can merge point clouds together and remove noisy data in order to have a rough 3D Object?
Answer: CloudCompare has statistical outlier removal (called SOR) function that can eliminate all lonely points for you. I would filter each *.ply first and then try to carry out a cloud to cloud registration. For registration, you can use MeshLab or use 30 days trails of commercially available software such as Faro Scene. Scene won't accept *.ply file though, so you need to convert your files to *.e57 first. Good luck.


return unix-timestamp format for datetime formatted field in laravel

Question: I have a Message model like this :
class Message extends Model
{
    protected $primaryKey = 'message_id';
    protected $dates      = ['created_at', 'updated_at', 'receiver_deleted_at', 'sender_deleted_at', 'sender_read_at', 'receiver_read_at'];
}

As you can see there are some date fields that hold dates as DATETIME(YYYY-MM-DD HH:MM:SS) format.
But I want when get an instance of model all date fields convert to unix-timestamp format and then return.
I know that can use accessor like this for every field :
public function getCreatedAtAttribute()
{
    dd(strtotime($this->attributes['created_at']));
    return strtotime($this->attributes['created_at']);
}

But in this case I must define a function like above for each field.
But I want an easier way that force model to return date fields as unix-timestamp format.
Comment: Accessors take care of the conversion to a Carbon instance which is an extension of default DateTime. So, `$this->created_at->format('U');` should work.
Comment: @TomLank., I want when call an instance of model converted format returned
Answer: protected $casts = [
    'created_at' => 'timestamp',
    'updated_at' => 'timestamp'
];

In model just add these cast to get unix timestamp
Answer: You can override the :
protected function getDateFormat()
{
 return 'U';
}

OR
Use timestamp property for each column:
$model->created_at->timestamp

Reference: https://laravel.com/docs/4.2/eloquent#timestamps
Comment: I added `getDateFormat` function but got this error : `Trailing data`


R: How to code new variable based on grouped variable and conditioned on earlier row

Question: I have a dataset from organ transplants.  The data are organized by donor and I'm looking at lungs - so each donor has two lungs.  The data are arranged as follows:
library(tidyverse)

data <- tribble(
  ~donor_id, ~sequence, ~organ_placed,
  1, 5, "L",
  1, 10, "R",
  2, 13, "B",
  3, 4, "L",
  3,69,NA,
  3,70,NA,
  3,71,NA,
  3, 72, NA,
)

donor_id = the donor id

sequence = the number of the donor offer.  I.e. it goes to person 1, then 2, then 3...and so on.

organ_placed = if the organ is a match, the organ placed is listed. E.g. for donor 1, the left lung was placed on the 5th offer and the right was placed on the 10th offer.

I'm trying to figure out how to code the case for donor 3:  the left lung is placed on the 3rd offer, but the right is never placed - the match offers continue through 72 offers then just stop.
I'd like the new data to look like:
desired_data <- tribble(
  ~donor_id, ~sequence, ~organ_placed,~outcome,
  1, 5, "L","Left Single",
  1, 10, "R","Right Single",
  2, 13, "B","Bilateral",
  3, 4, "L","Left Single",
  3,69,NA,NA,
  3,70,NA,NA,
  3,71,NA,NA,
  3, 72, NA,"Right Discarded"
)

I'm thinking it's something like group_by(donor_id) and then slice_max of sequence has NA for organ_placed, but I need it to code that it's the right lung that's discarded.
data <- data %>%
  mutate(outcome = case_when(
    organ_placed=="L" ~ "Left Single",
    organ_placed=="R" ~ "Right Single",
    organ_placed=="B" ~ "Bilateral",
    **what would go here? to group by donor id and find the maxslice has an NA,
      and L (or R) already occurred in that donor?**
  ))

Thanks for any help!
Comment: donor 3 left lung is placed on 4th offer?
Answer: We could do something like this:
Basically in this approach we go simple through all conditions using case_when:
library(dplyr)
data %>%
  group_by(donor_id) %>%
  mutate(outcome = case_when(organ_placed == "L" ~ "Left Single",
                            organ_placed == "R" ~ "Right Single",
                            organ_placed == "B" ~ "Bilateral",
                            (is.na(organ_placed) &
                              row_number() == max(row_number())) &
                              first(organ_placed) == "L" ~ "Right Discarded",
                            (is.na(organ_placed) &
                               row_number() == max(row_number())) &
                              first(organ_placed) == "R" ~ "Left Discarded",
                            TRUE ~ NA_character_))

  donor_id sequence organ_placed outcome
     <dbl>    <dbl> <chr>        <chr>
1        1        5 L            Left Single
2        1       10 R            Right Single
3        2       13 B            Bilateral
4        3        4 L            Left Single
5        3       69 NA           NA
6        3       70 NA           NA
7        3       71 NA           NA
8        3       72 NA           Right Discarded

Answer:
If in some donor_id, only L(R) appears, then find the position with the maximum sequence and fill in RD(LD).

Recode LD to "Left Discarded" and RD to "Right Discarded".

library(dplyr)

data %>%
  mutate(.by = donor_id,
         outcome = ifelse(sum(c('L', 'R') %in% organ_placed) == 1 & sequence == max(sequence),
                          paste0(c('L', 'R')[!c('L', 'R') %in% organ_placed], 'D'),
                          organ_placed) %>%
                   case_match("L" ~ "Left Single",
                              "R" ~ "Right Single",
                              "B" ~ "Bilateral",
                              "LD" ~ "Left Discarded",
                              "RD" ~ "Right Discarded"))

# # A tibble: 8 × 4
#   donor_id sequence organ_placed outcome
#      <dbl>    <dbl> <chr>        <chr>
# 1        1        5 L            Left Single
# 2        1       10 R            Right Single
# 3        2       13 B            Bilateral
# 4        3        4 L            Left Single
# 5        3       69 NA           NA
# 6        3       70 NA           NA
# 7        3       71 NA           NA
# 8        3       72 NA           Right Discarded

Note: Setting .by = donor_id in mutate is equivalent to group_by(donor_id) before mutate if your dplyr version is up to date.


Extracting Dates from xts object based on vaule

Question: I want to extract the dates of an xts object on which a change in value appears, i.e. the dates on which the value of A changes from one to zero or from zero to one:
require(xts)
A <- xts(c(1,1,0,0,1,1,0,0,1,1), Sys.Date()-10:1)
colnames(A) <- c("A")

> A
           A
2014-12-27 1
2014-12-28 1
2014-12-29 0
2014-12-30 0
2014-12-31 1
2015-01-01 1
2015-01-02 0
2015-01-03 0
2015-01-04 1
2015-01-05 1

The desired result Looks like this
> from.one.to.zero
[1] "2014-12-29" "2015-01-02"

> from.zero.to.one
[1] "2014-12-31" "2015-01-04"

Comment: There is a typo in the title: vaule <--> value.
Answer: You could try
index(A[diff(A)<0])
#[1] "2014-12-31" "2015-01-04"

index(A[diff(A)==1])
#[1] "2014-12-29" "2015-01-02"


resizing image so it fits into slide perfectly, still the issue is replacing css code with my image with for-loop

Question: I'm using owl carousel, and the default code I have has nice color background. but instead of the colored background, I want to use different images for each slide. I inserted an image as I have inserted the text, but the image is too big the whole thing collapses. Can you please help me with this one?
Here;s the carousel code

{% for import in mustSee %}

{{import.title}}

{% endfor %}

The text gets displayed but the problem is the image, the image needs to be the background of the div tag. But thing is I'm using for loop to display different images for each slide, I can't directly change background like I would do in css.
And In css,
#owl-demo .owl-item > div{
  background : #42bdc2;
  text-align: center;
  padding:50px 0px;
  margin:3px;
  color: white;
  font-size:32px;
  border:1px white;
}

Instead of
 background : #42bdc2;

I want this to be  of course, because I'm using for loop, I need to consider that too as well. how do I replace colored background with this image?
Answer: If I understood your question right, this is you wanna do in short:

Use img-src as div's bg

You can do it easily using jquery
$(".your-div").each(function(){
  var imgSrc = $(this).find(".your-img-tag").attr("src");
  $(this).css("background","url('"+imgSrc+"')");
});

And if you dont want to show-up your image in img tag, you can either hide it or to have a clean code do put that img-url into data-src attr of your div and use the following code
$(".your-div").each(function(){
  $(this).css("background","url('"+$(this).attr("data-src")+"')");
});

Comment: however, looking at your question's title, there are many ways to achieve what you want. Some prefer the [centerCrop](http://jonathannicol.com/blog/2014/06/16/centre-crop-thumbnails-with-css/) way on the img tag itself rather than assigning that as div bg
Comment: oh shoot, I'm really bad at jquery...I kinda understand your code but not perfectly.  I'm trying to replace background : #42bdc2; with
Comment: yep, this is what you want then. What i do is, take the img-url and assign it as div bg using jquery
Comment: so I need to replace your-img-tag with   ??
Comment: Yep, thats correct, you need to make jquery select/locate your img tag within the div. thats done by adding a class name to your img tag.
Comment: hmm, not sure how to do it I tried it like this; http://dpaste.com/3SXSXDV but won't work can you please help me
Answer: You could possibly use inline css to change the background-image property.

Make sure to set your background properties as well. Something like this, but taking into account your elements and image dimensions:
div {
  background: transparent url('fallback.jpg') no-repeat scroll center center / cover;
}

UPDATED to reflect your specific elements.
In your css doc you will want your background rules and your fallback image (I am assuming .owl is your class name):
.owl {
    background: #42bdc2 url('path/tp/fallback.jpg') no-repeat scroll center center / cover;
    text-align: center;
    padding:50px 0px;
    margin:3px;
    color: white;
    font-size:32px;
    border:1px white;
}

Now, for your inline styling (note: you don't want to use  for a css rule you just want to updated background-image as you normally would):

Note the syntax - background-image: url("url-goes-here");; you'd obviously replace url-goes-here with {{import.get_image_url}} as shown in the example.
Comment: actually that's really good idea hmm not sure how I can do it tho, ??
Comment: @mikebraa I've updated my answer to show specific examples in regards to your code


Vue JS transition using in v for

Question: Im new to vuejs and I have problem. look my code
Template:

            <transition name="show">

{{game.name}}

{{game.demo}}

                        OPEN LINK

            </transition>

Script:
// Library
import {ref} from "vue";

// Export
export default {
    name: "GameBar",
    setup()
    {
        let isHover=ref(false)
        const games=ref([
            {
                name: 'RAINBOW SIX',
                demo: 'Some Text Some Text Some Text Some Text Some Text Some Text',
                poster: 'assets/home/media/game/3.jpg',
            },{
                name: 'PUBG',
                demo: 'Some Text Some Text Some Text Some Text Some Text Some Text',
                poster: 'assets/home/media/game/6.jpg',
            }
        ])
        return {
            isHover,games
        }
    }
}

Style:
.component{

    // Animation
    .show-enter-active,.show-leave-active{
        transition: all 0.2s ease;
    }
    .show-enter-to,.show-leave-from{
        opacity: 1;
    }
    .show-enter-from,.show-leave-to{
        opacity: 0;
        top: 5px !important;
    }
}

Now my problem is when mouse enter on li, all li transition work and show information class. I know its because of isHover variable. but I don`t know how can I handle this like JQuery when using $(this).find(CHILD). I searched a lot but no solution found...
Answer: Defined a property in the components data function, for example hoveredItem, and then change @moueseenter and @mouseleave handlers to set this.hoveredItem accordingly. Here's the code:
  data() {
    return {
      hoveredItem: '',
    };
  },

Vue JS transition using in v for


Installing IRAF problem

Question: I've installed iraf v216 on my desktop computer without any difficulties but installing it on laptop(HP pavilion g6) is giving me a lots of trouble.
I can't solve this particular problem, and I don't know what to do, I'm new to linux, but I can follow your steps easily. ;)
Here is the problem:
Iraf installation passed, x11IRAF too, ds9 also passed but when I try to run it it says bash: /usr/local/bin/xgterm: No such file or directory
and xgterm is located in "/usr/local/bin/".
I have no idea what to do from here.
Answer: I ran into this problem yesterday while trying to install IRAF 2.14 and x11IRAF 1.3.1 on Xubuntu 12.10.  From this helpful post, I realized that the issue was that xgterm needs the following 32bit libraries that were not by default installed on my system:
libx11-dev
ia32-libs
These libraries are in the Ubuntu repositories, so an apt-get should do the trick.

Installing IRAF problem


How to set data in fillInIntent

Question: I have a list view in my home screen widget and I want to launch a pending intent when the item is clicked. I referred to this and set a fillInIntent for every list item and then set a pending intent template which triggers the broadcast receiver of the widget:
class WidgetProvider : HomeWidgetProvider() {
    override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray, widgetData: SharedPreferences) {

        appWidgetIds.forEach { widgetId ->
            val views = RemoteViews(context.packageName, R.layout.widget_layout).apply {

                val todosStr  = widgetData.getString("todos", "null")
                val todos = ArrayList<HashMap<String, Any>>()
                val todosRemoteView = RemoteViews.RemoteCollectionItems.Builder()
                if(todosStr != "null"){
                    val jObj = JSONObject(todosStr)
                    val jsonArry = jObj.getJSONArray("todos")
                    for (i in 0 until jsonArry.length()) {
                        val todo = HashMap<String, Any>()
                        val obj = jsonArry.getJSONObject(i)
                        todo["id"] = obj.getInt("id")
                        todos.add(todo)

                        val view = RemoteViews(context.packageName, R.layout.each_todo).apply {
                            setTextViewText(R.id.each_todo_container_text, todo["taskName"].toString())

                            val fillInIntent = Intent().apply {
                                Bundle().also { extras ->
                                    extras.putInt("todo_id", todo["id"].toString().toInt())//this isn't working for some reason
                                    putExtras(extras)
                                }
                            }
                            Log.d("debugging",  "id received is ${todo["id"].toString()}" )
                            setOnClickFillInIntent(R.id.each_todo_container_text, fillInIntent)
                        }

                        todosRemoteView.addItem(todo["id"].toString().toInt().toLong(), view)
                    }
                }

                setRemoteAdapter(
                        R.id.todos_list,
                        todosRemoteView
                    .build()
                )

                val pendingIntentx: PendingIntent = Intent(
                        context,
                        WidgetProvider::class.java
                ).run {
                    PendingIntent.getBroadcast(context, 0, this, PendingIntent.FLAG_IMMUTABLE or Intent.FILL_IN_COMPONENT)
                }
                setPendingIntentTemplate(R.id.todos_list, pendingIntentx)
            }

            appWidgetManager.updateAppWidget(widgetId, views)
    }

    }

    override fun onReceive(context: Context?, intent: Intent?) {
        val viewIndex: Int = intent!!.getIntExtra("todo_id", 0)
        Log.d("debugging", "an item is clicked $viewIndex")
        //the default value gets used, which means that the receiver isn't receiving the intent data

        super.onReceive(context, intent)
    }
}

The problem is that the receiver isn't receiving the data which was put in the fillInIntent, the default  value 0 is getting printed by the last statement. I also tried setting the FILL_IN_COMPONENT flag as suggested here, but that didn't work. Where am I going wrong?
Answer: Just replace PendingIntent.FLAG_IMMUTABLE or Intent.FILL_IN_COMPONENT with PendingIntent.FLAG_MUTABLE. I think it is the IMMUTABLE that makes the intent can't be changed. As a result, you can't get the extra.

How to set data in fillInIntent


insertSlidesFromBase64 Working on Client Powerpoint, But not on Powerpoint for the web

Question: Here is the Code i Used
async function insertPptxFromBase64String(chosenFileBase64) {
   Office.context.document.getSelectedDataAsync(Office.CoercionType.SlideRange, function (asyncResult) {
       try {
         if (asyncResult.status === Office.AsyncResultStatus.Failed) {``
             console.log(asyncResult.error.message);
          } else {
            const selectedSlideID = asyncResult.value.slides[0].id;
            PowerPoint.run(async function(context) {
                context.presentation.insertSlidesFromBase64(chosenFileBase64, {
                    formatting: "UseDestinationTheme",
                    targetSlideId: selectedSlideID + "#"
                 });
                await context.sync();
            });
          }
        }
        catch (error) {
          reject(console.log(error));
        }
      });
}

This code selects the slide id of the current selected slide, and inserts a presentation after that.
It was running perfectly on both platforms, but around a month back, it stopped working for Powerpoint online(powerpoint on the web).It still runs smoothly on Client Powerpoint(Offline Powerpoint)
Here is the error it shows in console
powerpoint-web-16.00.js:26 Uncaught (in promise) RichApi.Error: Cannot read property 'invokePropertySet' of null
    at new n (powerpoint-web-16.00.js:26)
    at n.i.processRequestExecutorResponseMessage (powerpoint-web-16.00.js:26)
    at powerpoint-web-16.00.js:26

Answer: Thanks for reporting this - this issue has now been fixed.
Related Github post: https://github.com/OfficeDev/office-js/issues/2071


Using getJSON in for loop, why do I have to assign a function to hold the value of counter?

Question: Here is the code somebody else posted as a solution:
for (var i = 0; i < array.length; i++) {
(function(i) { // protects i in an immediately called function
  $.getJSON('/api.php?action=query&list=querypage&qppage=' + array[i] + '&format=json', function (data) {
    $('#' + array[i]).text(data.query.querypage.results.length);
  });
})(i);
}

Specifically, what does the (i) do at the end of the function?
Comment: [JavaScript closure inside loops – simple practical example](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example)
Comment: You're passing in the loop index to the IIFE as an argument so it's scoped locally to that function.
Comment: Because it's asynchronous
Comment: `$.getJSON` is asynchronous. This means that by the time you receive a response from the server and the callback function is executed, the loop will have ended long ago, and `i` will be `array.length-1` for all your calls. To save it for each call, you can use a JS closure like that. (Another name for this specific implementation: IIFE = Immediately-invoked function expression)
Comment: If you use `let` (ES6) instead of `var` you can do away with the IIFE altogether.
Answer: The short answer is, if you don't, the value of i will not be as you expect it to be for later function calls. Removing the closure (the (i)) will make it always the maximum value for all calls, as they all happen instantaneously (such is the nature of asynchronous programming).
You create a function around this call, then call that function with the value of i that you want to preserve the value for when the getJSON finishes. Note also, if you were using ES2015, you could use for(let i = 0; ...) and it would handle the scoping for you.


Error in class.phpmailer.php

Question: I am using the phpmailer api to send mails in a joomla site with the RSForm! Pro 1.52.9 component.
All was working ok but today I start to getting the following error when summiting a form build with the RSForm component:
<code>   PHP Fatal error:  Only variables can be passed by reference in .../libraries/vendor/phpmailer/phpmailer/class.phpmailer.php on line 1182
</code>
I am using joomla 3.6 and my php version is php 5.3
Comment: the error describes your issue, however you need to put your code which is related with that error
Answer: The problem was resolved by changing the php version to 5.6.

Error in class.phpmailer.php


Which programming language(s) is Ulteo OVD written in?

Question: I am doing on an academic project Virtual Desktop Infrastructure. I want to work with Ulteo OVD 4.0.2 which is an open source virtual desktop software. But I am not aware in which language is Ulteo coded. Can you please tell me?
Answer: Look inside their git repository: it is mostly C, with some Python & Java (client side ...), configured by autoconf
A general hint about free software is to download the source code and look inside it.


How can I set the zone like I want?

Question: Suppose that I have 2 roads like those below and I want to zone ONE residential with an entrance (^) on east/west road ( the house is on a field of 3 squares)
+++...++++++++
..............
..............
+++...++++++++
^ +...+
^ +...+
^ +...+
But the computer does not let me build the way I want. It set 3 residential zones of one sqare each on north/south road instead.
+++...++++++++
..............
..............
+++...++++++++
> +...+
> +...+
> +...+
How can I set the zone the way I want ?
Am not suppose to act like god ?  :-)
Answer: When zoning you can hold the following keys (or any combination) to adjust how it will configure the plots:

Shift:   Temporarily disables automatic street placement
Alt:   Rotates zone to face perpendicular road
Ctrl:   Forces a specific plot size

It sounds like you would want to use the Alt key.
Check this post for additional useful hotkeys
Comment: Wow. 10 years on and off playing this game, and I'm just learning this now.
Comment: @Paystey be sure to upvote the question too if it's good, Q's need love too ;P

How can I set the zone like I want?


Is it good programming to have lots of singleton classes in a project?

Question: I have a few classes in a project that should be created only once.
What is the best way to do that?,

They can be created as static object.
Can be created as singleton
Can be created as global.

What is the best design pattern to implement this?
I am thinking of creating all classes as singleton, but that would create lot of singletons. Is it good programming practice to have lot of singletons?
What are the pros and cons for using singletons?
Comment: You should then pass them as pointers to those threads. If they don't *have* to be global, don't make them singletons.
Comment: Check out http://stackoverflow.com/questions/137975/what-is-so-bad-about-singletons
Comment: why should they be created only once?
Comment: @jalf, what of this class? `struct uhoh { uhoh(){static bool firstTime = true; if (!firstTime) make_computer_splode(); firstTime = false; } };` :)
Comment: alot of singletons can sometimes be an indication of poor design;  otherwise known as a 'code smell'
Comment: These classes store some state information also that can be accessed between all threads in application.
Comment: and if they have to be global, make them global, but without the "can only be instantiated once" nonsense of singletons. Globals have their uses occasionally. But I've yet to encounter a situation where it was actually justified to make it **impossible** to ever instantiate an object more than once.
Comment: Things about design patterns should probably go to [programmers.SE](http://programmers.stackexchange.com/) since it is about {software requirements, software architecture and design, algorithms and data structures, **development methodologies** and processes, software engineering management, quality assurance and testing, software licensing}. In contrast, StackOverflow should be about {Specific programming problems, Software algorithms, Coding techniques, and Software development tools} (both lists come from the Tour page of the two sites).
Comment: Check out [the same question in Programmers.SE](http://programmers.stackexchange.com/q/252) and [its duplicate](http://programmers.stackexchange.com/q/37249) for more opinion.
Comment: @FranklinYu this question is a  poor fit for Programmers - it would be quickly voted down and closed over there, see [What is the problem with "Pros and Cons"?](http://meta.programmers.stackexchange.com/q/6758/31260) Recommended reading: **[What goes on Programmers.SE? A guide for Stack Overflow](http://meta.programmers.stackexchange.com/q/7182/31260)**
Comment: @gnat Then I am totally confused. Does it suits StackOverflow then? If yes, then why? If not, then where should they go? Or should I ask this in StackOverflow Meta?
Answer: Take a look at Steve Yegge's blog post about this - Singleton Considered Stupid
Comment: Okay I just gone through the blog..I am facing similare kind of problem having classes like RegistryManager,FileManager,DataBaseManager etc and each class shoud be initiliazed only once and different threads can set states of these classes which should be visible to all of them.
Comment: Thank you for the link. Thats a nice summary, and saved me quite a few words. Singletons at times are a unavoidable evil, but they should be avoided when possible, especially if they are mutable.
Answer: If they only need to be created once, that doesn't mandate they should be singletons.

If X is a singleton, it's implied there is one instance.
If X has one instance, that doesn't mean it should be a singleton.

Use a singleton if you require there be only one instance of the class, and that it be globally accessible. In your case, simply only needing one isn't reason enough. Globals are bad, singletons are glorified globals.
Most often, you don't need them. You'll see it a lot in bad code because of the very mentality: I only need one, that must mean I should make it singleton! (Wrong) For example, I've finished the technical design of the most powerful game engine I've ever done to date. It has 2 singletons, for memory and threading. A very large project, and I only have two!
More context would help us give you better information.
Comment: Agreed, although I wouldn't call singletons "glorified globals". They're globals with an additional unnecessary, and often crippling, design problem thrown in. If you need something to be globally accessible, make it a global, not a singleton.
Comment: The problem a singleton has over a global is that *you can only create one instance*. What when you want to test it? Good luck instantiating it in your test case setup. What when you find out that oops, you *did* need two after all. It's a silly and premature constraint to put on your code that "only one instance can ever be created". If you want lazily instantiated globals, then implement those, nothing is stopping you. But don't bother preventing multiple (non-global) instantiations of the class.
Comment: @jalf: I don't think I agree with that. Singletons can be lazily created, to avoid the static fiasco.
Comment: And then you're left with a much more complicated implementation to achieve exactly the functionality that a plain global would've provided. Just because it is possible to work around the problems a singleton creates doesn't mean that it's a better solution than not creating the problems in the first place. What benefit does a singleton have over a global?
Comment: @jalf, Like above, globals don't have a set initialization order. Singletons are also classes, which have private details and functions. (A global would mean more global variables, while a singleton is technically just one variable.) I'm not sure I understand what problems a singleton has over a global. :) My singleton is simple: `singleton::reference().foo_bar();`, and is non-intrusive.
Comment: @jalf, But if I need to test it, I just create an instance: `foo f;` It's non-instrusive. In my two cases, there *must* be only one and globally accessible instances of those classes, because they are system-wide., not a premature constraint. The thing is, in my case (so maybe not relevant to , I need to be able to change where the instance of my singleton(s) come from, because I have different "processes" (dynamic-libraries) that would normally make their own. It's easy: `singleton::instance(some_pointer)`, so any further accesses use that instance of `foo` instead.
Comment: Though that would be easy to implement as a global function too... FUU- now my fairness bit is kicking in. I think sometime I shall switch singleton->global and see what the differences are.
Comment: If you can just create an instance, it's not really a singleton though. If you remove that constraint and make it possible to instantiate the object at will, then it's not a singleton, just a global, and we agree. ;)
Comment: As for the system-wide constraint, that's not true. You have a constraint that exactly one instance is globally accessible, and represents the "official" system-wide state. But that doesn't in itself mean that other, local instances can not be meaningful. It is premature to prevent instantiation of other instances.
Comment: @jalf, I should mention I'd have to comment a parameter out of the constructor and make it copyable to just make an instance, but ok-ok I see. So then what I want then is a globally accessible instance of a certain class... a global variable. :O Since `singleton` *does* already handle the "make it global part", would it be worthwhile to just take out the non-copyable and single-instance stuff and change `singleton` to `global`? :) To help out with my per-process instance changing and initialization. Good-bye, singleton.
Comment: "I've finished the technical design of the most powerful game engine I've ever done to date." Care to elaborate? Or have a link?
Comment: @Stacked: It's all private, sorry. :S
Comment: @GMan I have such a singleton class too. I suppose yours, like mine, has a static T in its function instance(). I found that in multithreaded applications, this may explode (and actually does, sometimes) without mutex/lock/critical section/whatever. To avoid the double initialization of that T while not using locks, you have to initialize your singletons at the beginning of your main, or whenever you know there will be no other thread calling instance().
Answer: I suggest you look at some of the videos and articles that Miško Hevery of Google has done. First a video: "Clean Code Talks: Global State and Singletons" and his blog.
The general concensus is that Singletons are OK in a few rare instances, for example logging, but in most other situations you want to use dependency injection. Singletons make it harder to test your code and they hide dependencies so that your classes cannot be instantiated easily in isolation.
Answer: Singletons have a few problems -- they're hard to test, hard to replace, and hard to extend.  There's usually a better way.
Answer: One of my favourite articles on the singleton is Singletons are Pathological Liars by Miško Hevery. Essentially, they encourage "hidden" behaviour that is very hard to learn and test.
Answer: A singleton is effectively global state.  If you're going to create lots of singletons you're going to create lots of global state, only in won't necessarily look like global state.
This makes it hard to do things like build unit tests, provide mock classes and reuse code because its really easy to
couple the current state to a function.  i.e. function foo is only valid when class X is in state Z, otherwise it doesn't work.
It's also problematic to build a thread safe singleton correctly.
Singletons can be good for coordinating access to a resource, particularly one that doesn't have much state and is expensive to construct.
So why do you think you need lots of singletons? you may get better responses if you ask about your problem domain and what issue you are hitting.
Answer: There are projects where you can't practically avoid using globals. All kinds of service locators or dependency-injection frameworks still rely on global (not always static variable, but always global of some sort) storage of objects.
However, singletons are a sign of a problem:

First, singleton as a canonical pattern doesn't go well with interfaces and abstraction. It can be fixed though - accessing it through factory.
Worse, singletons are inflexible - they don't have any means of identifying object beyond its type. ( Well, in C++ they do through templates, but it's a different story). In that sense they are actually worse than static variables. In the long run it pays off using a framework where many instances of the same type can be accessed.
And most importantly, lots of singletons means lots of distant relationships between objects. Which means your system is probably more complex than it needs to be and will be much harder to develop, test and manage. Simply switching to locators or DI won't help there, it's a matter of underlying design principles.
Comment: DI is perpendicular to this issue. DI is exactly that - injecting dependencies into objects through factories. It tells nothing about nature of those dependencies. The confusion in other answers here is probably from the fact that most all DI frameworks include dynamic configuration and service locator. Both of those can be used without DI, and DI technically can be used without them.
Comment: Think of DependencyManager.Register(Singleton::Instance())
Answer: In programming there are no silver bullets. Making every class a singleton will not magically make your code "better". Singletons are a tool for that solve a specific problem I studying  more about singletons.
Answer: To use singleton pattern in your project should be a well thought out and careful design decision, because its a one way track with very little scope for backtracking. I have practically used it in one of my project for a commercial product in a multithreading environment and faced multitude of problems. But this doesn't mean it's an untouchable pattern. The point is anything which can be achieved with singleton can be achieved without it, with less hassles and complexity. For more on this you can track this question I asked some months back. It has interesting links and insight into the singleton pattern


SQL - How to find the closest date match for each record from two tables without matching the same date for 2 rows

Question: Suppose I have Table1 and Table2 with the below data. I want to find the next closest date match for JoiningDt (column of Table1) that is available in Table2 column ClosestDt for each ID. Note: Closest match from Table2 should be greater than the the date of Table1 and no two IDs can have the same closest match, e.g. ID 2 should take the value 08-Apr-2024 even though 07-Apr-2024 is the nearest one because it is already taken by ID 1.
Table1:

ID
JoiningDt
DocNum

1
05-Apr-2024
A123

2
06-Apr-2024
A123

3
04-Apr-2024
B123

Table2:

DocNum
ClosestDt

A123
03-Apr-2024

A123
04-Apr-2024

A123
07-Apr-2024

A123
08-Apr-2024

B123
02-Apr-2024

B123
05-Apr-2024

My Expected output is:

ID
JoiningDt
DocNum
ClosestDt

1
05-Apr-2024
A123
07-Apr-2024

2
06-Apr-2024
A123
08-Apr-2024

3
04-Apr-2024
B123
05-Apr-2024

When I tried an left outer join, I get:

ID
JoiningDt
DocNum
ClosestDt

1
2024-04-05
A123
2024-04-07

1
2024-04-05
A123
2024-04-08

2
2024-04-06
A123
2024-04-07

2
2024-04-06
A123
2024-04-08

3
2024-04-04
B123
2024-04-05

select t1.ID
      ,t1.JoiningDt
      ,t1.DocNum
      ,(t2.ClosestDt)
 from #Table1 t1
 left join #Table2 t2
   on t1.DocNum = t2.DocNum and t2.ClosestDt > t1.JoiningDt

I tried using rownum also but the challenging part is getting the next match, i.e. 8-apr and not 7-apr, for ID 2 because 07-Apr is already taken by ID 1. Please assist.
Comment: [Why should I "tag my RDBMS"?](https://meta.stackoverflow.com/questions/388759/why-should-i-tag-my-rdbms)
Comment: What is the data type of column `JoiningDt` (in `Table1`) and column `ClosestDt` (in `Table2`) ?
Answer: This query ensures each "joining date" has a unique next "closest date" match.
Query:
WITH
  table_a AS (
  SELECT
    *
  FROM
    `optimal-weft-418017.78206957.78206957_01` ),
  table_b AS (
  SELECT
    *
  FROM
    `optimal-weft-418017.78206957.78206957_02`
  ORDER BY
    docnum,
    ClosestDt ),
  merged AS (
  SELECT
    id,
    JoiningDt,
    a.DocNum,
    ClosestDt
  FROM
    table_a a
  LEFT JOIN
    table_b b
  ON
    JoiningDt<ClosestDt
    AND a.docnum=b.docnum ),
  filtered AS (
  SELECT
    *,
    ROW_NUMBER() OVER(PARTITION BY id, docnum ORDER BY JoiningDt) ROW
  FROM
    merged
  ORDER BY
    id,
    docnum,
    JoiningDt ),
  unique_docnum AS (
  SELECT
    DISTINCT id,
    joiningdt,
    docnum
  FROM
    filtered ),
  filtered_rows AS (
  SELECT
    *,
    ROW_NUMBER() OVER(PARTITION BY docnum ORDER BY joiningdt) AS ROW
  FROM
    unique_docnum ),
  final AS (
  SELECT
    DISTINCT a.id,
    a.joiningdt,
    a.docnum,
    a.closestdt
  FROM
    filtered a
  INNER JOIN
    filtered_rows b
  ON
    a.row=b.row
    AND a.docnum=b.docnum
    AND a.id=b.id)
SELECT
  *
FROM
  final
ORDER BY
  id


Why P(x V y) and Px V Py are not logically equivalent?

Question: I'm struggling to understand why the following sentence of a predicate language
$P(x\lor y)$
is not logically equivalent to the sentence
$Px\lor Py$
If this is indeed the case (i.e. the two sentences are not equivalent) could someone explain why (in terms, for instance, of satisfaction of assignments in a model?)
Comment: In order for us to show why something isn't the case, you have to tell us why you think it is.  We can't correct a wrong argument that you are keeping secret.
Comment: What is $P$? Why do you have two variables with a disjunction between? The top expression doesn't even look like a well formed formula.
Comment: P could be any predicate (such as "knowing", "being sad") etc. However, I was also wondering whether the top expression actually is a well-formed formula. Would it be if there were individual constants instead of variables? I don't think so, because synctactically the formula would be the same...
Comment: Actually what made me ask this question is the answer I received to this other question (in fact, I don't think the answer I received is a good one; I'm very confused now!): https://math.stackexchange.com/questions/2963518/basic-logic-how-to-formalize-it-is-important-that-alf-comes-or-that-betty-come/2963524?noredirect=1#comment6118500_2963524
Comment: It looks like the person in that post is using "it's important that" not as a predicate, but as a modal operator (something that takes propositions as inputs and outputs a new proposition). Which is a non-standard thing to have in predicate logic.
Comment: ["predicate language"](https://en.wikipedia.org/wiki/First-order_logic) can mean either first order logic or higher order logic: in the first case, $x$ and $y$ are usually used to denote "objects" (individuals) and the $\lor$ is a propositional connective, acting on frmulas and not objects.
Answer: If $P$ acts on propositions, $P(x\lor y)$ is well-formed because $x\lor y$ is well-defined. But in general, $P(x\lor y)$ doesn't imply $Px\lor Py$. For example, suppose $Px$ means $x$ is a theorem. Then $P(x\lor y)$ means you can prove $x\lor y$, as for example is possible if $y=\neg x$. But in that case: if you can't prove or disprove $x$, the former fact implies $\neg Px$ while the latter implies $\neg Py$.
Comment: @Mijito In $Px$, what kind of thing is $x$ meant to be? That's what $P$ acts on. If it's propositions, $x\lor y$ exists, so can be taken as an argument of the same unary predicate. The parentheses are just for clarity.
Comment: But I mean, P(x∨y) is not a well-formed formula of predicate logic! As far as I know, concepts such as "well-defined" do not intervene there...
Comment: Also, in predicate logic textbooks I never encountered formulations like "P acts on propositions"...
Comment: In fact, I should have specified from the beginning that my question concerns PREDICATE logic.
Comment: I know that x∨y exists but I don't think that's enough for P(x∨y) to be a well-formed formula?? Actually, I never encountered a formula like that one in logic textbooks...
Answer: In ordinary language 'or' can conjoin expressions of various types, sentences, names, verbs, adverbs, etc. ('Romeo loves Rosalind or he loves Juliet', 'Romeo loves Rosalind or Juliet', 'Romeo loves or hates Juliet', 'Romeo loves Juliet wisely or unwisely', etc.)
But in the standard language of the predicate calculus, $\lor$ remains always and only a sentential connective -- i.e. it can only connect complete wffs (open or closed sentences).
So if $x$, $y$ are individual variables, and $P$ a predicate, $Px$ and $Py$ are wffs, and $(Px \lor Py)$ is a wff. But $(x \lor y)$ is simply ill-formed, and hence $P(x \lor y)$ is ill-formed too. Such are the rules of the game.
[Ah, you might say, couldn't we add a non-standard rule to the effect that $\varphi(x \lor y)$ is equivalent to $(\varphi x \lor \varphi y)$? But applied generally to simple or complex predicates, this could cause havoc. For then e.g. $\neg P(x \lor y)$ would have two different and non-equivalent readings depending on the order we apply the negation and the non-standard rule.]
Comment: Thanks a lot for this clear answer; this is exactly what I was looking for. So, concerning this question: https://math.stackexchange.com/questions/2963518/predicate-logic-how-to-formalize-it-is-important-that-alf-comes-or-that-betty/2963524#2963524 I guess my attempt is correct?
Comment: See my response to that other question.
Answer: It seems you're having some confusion about the use of symbols. You seem to be talking about first order logic, in which $x$, $y$, and similar variables are taken to represent objects. $\vee$ means "or", and importantly does not mean what we typically mean by "or" in English. It is much more limited; $\vee$ is an operation that produces a sentence which may be true or false. "Apple or orange" has no truth value, so it doesn't make sense to replace that "or" with $\vee$ - even though in English we commonly say things like "would you like apple or orange juice?"
$P(x \vee y)$ is itself nonsense, because it doesn't mean what you think it means when you read it - it looks like it's saying "$P$ holds of either $x$ or $y$". But that isn't what $\vee$ means; $P(x \vee y)$ would be more accurately read as "$P$ holds of the phrase '$x$ or $y$'". That's nonsense, unless $P$ is a predicate that acts on sentences and $x$ and $y$ are themselves sentences (see J.G.'s answer) in which case you're working in second order logic.
By contrast, $Px \vee Py$ is read as "Either $P$ holds of $x$ or $P$ holds of $y$" - which seems a bit long-winded, but is a correct translation of $\vee$, because the result is a sentence which may be either true or false.


How can I implement .prettify() (BS4) into my function

Question: I have a function which returns a list like below:
['Title 1', 'Title 2', 'Title 3', 'Title 4']

I have tried numerous ways of implementing the soup.prettify() function to pretty print my list. However can't figure out the exact arrangement to make this work.
Below is my function:
def get_titles(html):
    soup = BeautifulSoup(html,'html.parser')
    outcome = soup.div.find_all(text=True)
    return(outcome)

Calling the function:
html = '#the example html'
print(get_titles(html))

Again, the current outcome (not exact, just an example of the list):
['Title 1', 'Title 2', 'Title 3', 'Title 4']

For clarity, i'm looking to utilise .prettify() to make the outcome list easier to read and therefore 'prettier'.
Comment: `pretiffy` needs `bs4 object`, not `list`. With `list` you have to use standard function to format data - like `"\n".join(list)`  or module `pprint` (PrettyPrint) and `pprint.pprint(list)`
Comment: something like print('\n'.join(get_titles(html)))?
Comment: you pretiffy a `bs4.Tag` (like your `soup`)  object not a list
Comment: I tried to print using the following  " print(soup.prettify(get_event_titles(html)) " but receive the error "SyntaxError: unexpected EOF while parsing"
Comment: 12 years old question: [How to print a list in Python "nicely" - Stack Overflow](https://stackoverflow.com/questions/1523660/how-to-print-a-list-in-python-nicely)
Comment: Please add your desired output format to your question
Answer: .pretiffy() needs bs4 object, not list.
Standard method to make list more readable is to convert to string using .join() with \n between elements.
print("\n".join(['Title 1', 'Title 2', 'Title 3', 'Title 4']))

Result:
Title 1
Title 2
Title 3
Title 4

There is also standard module pprint (PrettyPrint) which can format some data
import pprint

pprint.pprint(['Title 1', 'Title 2', 'Title 3', 'Title 4'], width=20)

Result:
['Title 1',
 'Title 2',
 'Title 3',
 'Title 4']

You may also use standard module json to format data
(but this works only with standard data types - like list, dict, but not class)
import json

print(json.dumps(['Title 1', 'Title 2', 'Title 3', 'Title 4'], indent=2))

Result:
[
  "Title 1",
  "Title 2",
  "Title 3",
  "Title 4"
]

EDIT:
Of course you can also write own function to display list
(but this will not prettify nested elements/lists/dictionares)
def show_list(data):
    print('[')
    print('  ' + ",\n  ".join(f'"{x}"' for x in data) + ',')
    print(']')

data = ['Title 1', 'Title 2', 'Title 3', 'Title 4']
show_list(data)

Result:
[
  "Title 1",
  "Title 2",
  "Title 3",
  "Title 4",
]

EDIT:
There is also nice module Rich which also has function pprint() and it can use colors to display different type of data
from rich.pretty import pprint

data = ['Title 1', 'Title 2', 'Title 3', 'Title 4',
        1234, {'A':'Hello', 'B':'World', 'C':'Python'}]

pprint(data, expand_all=True)

Result:

Image from page Rich: