How do I check if a pandas DataFrame is empty?

Question: How do I check if a pandas DataFrame is empty? I'd like to print some message in the terminal if the DataFrame is empty.
Comment: len() doesn't work? It should return 0 for empty dataframe.
Answer: You can use the attribute df.empty to check whether it's empty or not:
if df.empty:
    print('DataFrame is empty!')

Source: Pandas Documentation
Comment: @Quant - The documentation has a discussion on why __bool__ raises an error for a dataframe here: [link](http://pandas.pydata.org/pandas-docs/dev/gotchas.html#gotchas-truth).  Quote: "Should it be True because it's not zero-length? False because there are False values? It is unclear, so instead, pandas raises a ValueError"
Comment: This seems like a shame, since you need to know that df is a pd.DataFrame. I'd like to know the motivation for not implementing bool() on pd.DataFrame.
Comment: This method would not work in all of the cases, as in some cases empty dataframe might be of NoneType.
Comment: @AnishJain To be clear, we are dealing with emptiness here, not nullity; if we want to find out whether a data frame is empty, we need to have a data frame object first; testing nullity is a different matter. If your data frame is NoneType to start with, you are not testing emptiness, you want to know whether you have an object or not.
Comment: Much more faster approach is `df.shape[0] == 0` to check if dataframe is empty. You can test it.
Answer: I use the len function. It's much faster than empty. len(df.index) is even faster.
import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randn(10000, 4), columns=list('ABCD'))

def empty(df):
    return df.empty

def lenz(df):
    return len(df) == 0

def lenzi(df):
    return len(df.index) == 0

'''
%timeit empty(df)
%timeit lenz(df)
%timeit lenzi(df)

10000 loops, best of 3: 13.9 µs per loop
100000 loops, best of 3: 2.34 µs per loop
1000000 loops, best of 3: 695 ns per loop

len on index seems to be faster
'''

Comment: A DataFrame can be empty due either len(df.index) == 0 or len(df.columns) == 0 as well.
Comment: No, a data frame can contain columns but still be empty. len(df.index) == 0 is the best solution
Answer: To see if a dataframe is empty, I argue that one should test for the length of a dataframe's columns index:
if len(df.columns) == 0: 1

Reason:
According to the Pandas Reference API, there is a distinction between:

an empty dataframe with 0 rows and 0 columns
an empty dataframe with rows containing NaN hence at least 1 column

Arguably, they are not the same. The other answers are imprecise in that df.empty, len(df), or len(df.index) make no distinction and return index is 0 and empty is True in both cases.
Examples
Example 1: An empty dataframe with 0 rows and 0 columns
In [1]: import pandas as pd
        df1 = pd.DataFrame()
        df1
Out[1]: Empty DataFrame
        Columns: []
        Index: []

In [2]: len(df1.index)  # or len(df1)
Out[2]: 0

In [3]: df1.empty
Out[3]: True

Example 2: A dataframe which is emptied to 0 rows but still retains n columns
In [4]: df2 = pd.DataFrame({'AA' : [1, 2, 3], 'BB' : [11, 22, 33]})
        df2
Out[4]:    AA  BB
        0   1  11
        1   2  22
        2   3  33

In [5]: df2 = df2[df2['AA'] == 5]
        df2
Out[5]: Empty DataFrame
        Columns: [AA, BB]
        Index: []

In [6]: len(df2.index)  # or len(df2)
Out[6]: 0

In [7]: df2.empty
Out[7]: True

Now, building on the previous examples, in which the index is 0 and empty is True. When reading the length of the columns index for the first loaded dataframe df1, it returns 0 columns to prove that it is indeed empty.
In [8]: len(df1.columns)
Out[8]: 0

In [9]: len(df2.columns)
Out[9]: 2

Critically, while the second dataframe df2 contains no data, it is not completely empty because it returns the amount of empty columns that persist.
Why it matters
Let's add a new column to these dataframes to understand the implications:
# As expected, the empty column displays 1 series
In [10]: df1['CC'] = [111, 222, 333]
         df1
Out[10]:    CC
         0 111
         1 222
         2 333
In [11]: len(df1.columns)
Out[11]: 1

# Note the persisting series with rows containing `NaN` values in df2
In [12]: df2['CC'] = [111, 222, 333]
         df2
Out[12]:    AA  BB   CC
         0 NaN NaN  111
         1 NaN NaN  222
         2 NaN NaN  333
In [13]: len(df2.columns)
Out[13]: 3

It is evident that the original columns in df2 have re-surfaced. Therefore, it is prudent to instead read the length of the columns index with len(pandas.core.frame.DataFrame.columns) to see if a dataframe is empty.
Practical solution
# New dataframe df
In [1]: df = pd.DataFrame({'AA' : [1, 2, 3], 'BB' : [11, 22, 33]})
        df
Out[1]:    AA  BB
        0   1  11
        1   2  22
        2   3  33

# This data manipulation approach results in an empty df
# because of a subset of values that are not available (`NaN`)
In [2]: df = df[df['AA'] == 5]
        df
Out[2]: Empty DataFrame
        Columns: [AA, BB]
        Index: []

# NOTE: the df is empty, BUT the columns are persistent
In [3]: len(df.columns)
Out[3]: 2

# And accordingly, the other answers on this page
In [4]: len(df.index)  # or len(df)
Out[4]: 0

In [5]: df.empty
Out[5]: True

# SOLUTION: conditionally check for empty columns
In [6]: if len(df.columns) != 0:  # <--- here
            # Do something, e.g.
            # drop any columns containing rows with `NaN`
            # to make the df really empty
            df = df.dropna(how='all', axis=1)
        df
Out[6]: Empty DataFrame
        Columns: []
        Index: []

# Testing shows it is indeed empty now
In [7]: len(df.columns)
Out[7]: 0

Adding a new data series works as expected without the re-surfacing of empty columns (factually, without any series that were containing rows with only NaN):
In [8]: df['CC'] = [111, 222, 333]
         df
Out[8]:    CC
         0 111
         1 222
         2 333
In [9]: len(df.columns)
Out[9]: 1

Answer: I prefer going the long route. These are the checks I follow to avoid using a try-except clause -

check if variable is not None
then check if its a dataframe and
make sure its not empty

Here, DATA is the suspect variable -
DATA is not None and isinstance(DATA, pd.DataFrame) and not DATA.empty

Comment: This is redundant and bad practice if it's expected that the variable will be a DataFrame (which is what the OP implies) that is either empty or has rows. If it's not a DF (or if it's none), an exception should be thrown since something went wrong somewhere.
Comment: In Python, `try/except` is cheap and `if` is expensive. Python is neither Java nor C; here it's [Easier to Ask Forgiveness than Permission](https://docs.python.org/3/glossary.html#term-eafp)
Answer:
If a DataFrame has got Nan and Non Null values and you want to find whether the DataFrame
is empty or not then try this code.

when this situation can happen?
This situation happens when a single function is used to plot more than one DataFrame
which are passed as parameter.In such a situation the function try to plot the data even
when a DataFrame is empty and thus plot an empty figure!.
It will make sense if simply display 'DataFrame has no data' message.

why?
if a DataFrame is empty(i.e. contain no data at all.Mind you DataFrame with Nan values
is considered non empty) then it is desirable not to plot but put out a message :
Suppose we have two DataFrames df1 and df2.
The function myfunc takes any DataFrame(df1 and df2 in this case) and print a message
if a DataFrame is empty(instead of plotting):
df1                     df2
col1 col2           col1 col2
Nan   2              Nan  Nan
2     Nan            Nan  Nan

and the function:
def myfunc(df):
  if (df.count().sum())>0: ##count the total number of non Nan values.Equal to 0 if DataFrame is empty
     print('not empty')
     df.plot(kind='barh')
  else:
     display a message instead of plotting if it is empty
     print('empty')

Answer: I guess it depends on what the use case is but if you want to check if a dataframe is truly empty (so that you can assign whatever you want to it), then check it's shape:
if df.shape == (0, 0):
    print('DataFrame is empty!')

df.empty checks whether one of the axes (index or columns) is of length 0. In other words, it does the following check:
len(df.index) == 0 or len(df.columns) == 0

@Zero's suggestion only checks if the index is of length 0, while Sven's suggestion only checks if the columns are of length 0.

I'll show examples where it may be relevant:

Case len(df.index) == 0: As explained in Sven's answer, just checking if a dataframe has 0 length is not sufficient, as there may be some columns already defined and when actual values are assigned to a column, the previously defined column may show up. Note that df.empty is True in this case.
df = pd.DataFrame(columns=['A', 'B', 'C'])
df.empty                     # True
len(df.index) == 0           # True
len(df.columns) == 0         # False
df.shape == (0,0)            # False

df['D'] = [1]

     A    B    C  D
0  NaN  NaN  NaN  1

Case len(df.columns) == 0: Checking if there are no columns defined is also insufficient as there may already be indices defined and assigning values that don't match the already defined length will raise an error. Note that df.empty is also True in this case.
df = pd.DataFrame(index=[0, 1, 2])
df.empty                     # True
len(df.index) == 0           # False
len(df.columns) == 0         # True
df.shape == (0,0)            # False

df['D'] = [1]                # <--- ValueError: Length ... does not match ...

As you can see, in both cases above, df.shape == (0,0) is False; in other words, if that check returned True, we could've done both tasks without problems.


How can I find the maximum equal-split flow of a network

Question: I am working on a program currently that works out the maximum flow through a network using the Ford-Fulkerson algorithm, and that works fine, however, I need the final flow to meet the constraint that all edges that share a source node must also share the same flow value. (or flow splits evenly between edges from a common vertex). I am not mathematically literate when it comes to describing network flows, I only studied it for a brief period in high school so if people could try and explain simply I would really appreciate it! Am I missing another more simple way of working this out, my assignment says that this constraint simplifies the problem but I am at a loss as to how to do this.
TLDR: How can I find the maximum flow in a network if flow has to split evenly between all edges that share a source node
Answer: So I figured it out.
Assign the initial flow into the network a value of x, and then split the flow evenly under the constraints:

All flow into a vertex must leave that vertex
All edges that share a source must also share a flow

Then once each edge has been assigned a flow, for each edge set the flow equal to the capacity of that edge, and find the value of x. the smallest value of x will be the maximum initial flow allowed under the constraints.

Here is an example I drew up in ms paint to get the point across:
Answer: You are looking for an $st$-flow vector $x \in \mathbb{R}^A$ in the directed graph $G = (V,A)$ (I will assume that $\delta^+(t) = \delta^-(s) = \{ts\}$ for convenience), with the constraints
$\sum_{e \in \delta^-(v)} x_e - \sum_{e \in \delta^+(v)} x_e = 0 \qquad (\forall v \in V)$
$0 \leq x_e \leq c_e \qquad(\forall e \in A)$
(up to now this is the usual max-flow problem), and the additional constraints
$x_e = x_f \qquad (\forall v \in V, e,f \in \delta^+(v))$
that say that the the flow is split evenly on outgoing arcs at each vertex. The goal is to maximize $x_{ts}$.
As for the usual max-flow problem, this is a linear program, so you can use any linear programming solver to get a solution, it should work very well in practice.
But we can do better, by using one variable on each vertex, encoding how much flow leaves that vertex on each outgoing arcs. It is equivalent to simplifying our first LP using the equality constraints to eliminate the variables. We get:
$\begin{align}
&\max \; y_t \; \textrm{s.t.}\\
&\quad d^+(v) y_v - \sum_{u \in N^-(v)} y_u = 0  \qquad(\forall v \in V)\\
&\quad 0 \leq y_v \leq \min_{e \in \delta^+(v)} c(e) \qquad(\forall v \in V)
\end{align}$
(using $c(ts) = +\infty$). The first family of constraints defines $|V|$ constraints on $|V|$ variables, and given that your graph is strongly connected, it is not hard to check that the rank of that family is $|V| - 1$. Hence there is a vector $x^\star$ such that the solutions to the first family of constraints are $\{\lambda x^\star : \lambda \in \mathbb{R}\}$. If we find such an $x^\star$, then we can later use the capacity constraints to find the optimal solution $\lambda x_0$. So we focus on those constraints:
$d^+(v) y_v - \sum_{u \in N^-(v)} y_u = 0  \qquad(\forall v \in V)$
Setting $p_v = d^+(v)y_v$, this is equivalent to:
$p_v = \sum_{u \in N^-(u)} \frac{p_u}{d^+(u)}$.
We recognize the equations defining the stationary distribution of a Markov Chain on $G$, for which many algorithms exists. So we can take $p^\star$ to be the stationary distribution, compute $x^\star$ from it, and scale it until some arc reaches its capacity, and this gives the maximum flow that you are looking for.


Why won't my camera detect an external (ring) flash?

Question: I have a Nikon D5200 and Metz 15 MS-1 wireless digital macro flash. It used to work perfectly, but now my camera can't detect it :(
Any suggestions/solutions?
Comment: Can you think of anything that might have changed in between when it was working and now?
Comment: Are you using it with a PC sync cable (hotshoe adapter?), or wirelessly via CLS (with another flash)? What are you using to "master" the flash?
Answer:
Any suggestions/solution?

Test fire the flash to make sure that it's able to fire at all.
Replace the batteries in the flash with fresh ones.
Check both the hot shoe and the foot of the flash for dirt or corrosion. Even if you find none, you can rub the contacts with a pencil eraser to clean them a bit.
Check the fit: is the flash fully seated in the hot shoe? Is there anything that could prevent proper contact? When you lock the flash connector on the shoe, does it lock smoothly and seem secure?
Check camera settings to make sure you haven't made a change that could disable the flash.
Confirm that the flash works by testing it on a different camera.
Confirm that the camera works by testing it with a different flash.

Update: Having looked more closely at the flash in question, it's apparently not a hot shoe flash. Here are a few more things to check that are more specific to that flash:

Check the IR clip: if you're using the IR clip over the built-in flash to trigger the ring flash, make sure that the flash's IR sensor isn't covered and that there's a clear path from the clip to the sensor.
Check the sync cord: as with the hot shoe advice above, check for dirt or corrosion on the ends of the sync cable and in the terminal it connects to. Test the sync cord with a different flash to make sure that it works, or try a different cord. Sometimes the wires inside a cable can break.
Update the flash's firmware: it's hard to see why existing firmware would prevent the flash from working at all, but it wouldn't hurt to make sure it's up to date.
Comment: Upvoted for the last two suggestions especially
Comment: Um... I don't think it uses the hotshoe. I think it uses only a PC connection or CLS to connect to the camera.
Comment: Good point @inkista -- I assumed that the "clip" that goes on the built-in flash was actually a hot shoe connector.


Implementing Knowledge in Salesforce Communities

Question: I have a Salesforce Developer Edition Account. I have set up Knowledge(Articles) and a simple Community which implements Cases. The knowledge tab, even after adding it in the Community Tabs section does not show up in a live Community. Why is this so?
Answer: I ran into a similar issue. You need to grant at least READ access on one of the Article Types for your Community users.
I had trouble finding it under the new style of the Profile look/feel, but reverting to the old style Profile they show up under the Object CRUD settings.
Answer: Setting up Knowledge is extremely complicated. Please do a Google search for Knowledge Setup (https://www.google.com/search?q=knowledge+setup+salesforce) and see the first entry. Follow the instructions and read all the documentation, then come back here with any specific questions.


Wiring bathroom light and fan 3 black wires

Question: I was replacing an old Leviton 15 Amp Single Pole Dual Switch and noticed all wires were black. This was for a bathroom that one switch would power the light and the bottom switch would just power the fan.
Instead of wiring the same way as they were which was, the hot from the source was on the common side and the other two were on the hot side. (I used a voltmeter and read which one was hot), I decided to try to put the hot wire from the source to the brass hot screw and the other two black on the common screws.
Obviously this did not work and only the top switch worked to power both fan and light and the bottom switch did nothing. I am trying to figure out why this is … why would I put the hot from the breaker panel to the common and the other two black wires on the hot side?
Comment: Share a picture of how you've got it wired now and one of how it was wired originally. Put pieces of different colored tape on each wire so we can tell them apart.
Comment: I always wonder why folks try to change what works and wire things differently then wonder why it doesn't work. You probably do not have a complete understanding of the circuit without that in the forms of a schematic and or all the connections in both locations we won't have enough information.
Answer: We start with a simple single switch. Two screws - one used for line (incoming power) and one for load (switched hot). It does not actually make any difference whatsoever which wire goes on which screw. You could make an arbitrary convention such as "switch is flipped up to turn on, so use the top screw for load and the bottom screw for line" but it makes no difference whatsoever.
Next we have the 3-way switch. Which is actually a pair of switches. (And possibly 4-way switches in between, but we'll ignore that for now). With a 3-way switch, it is not exactly line and load. Instead, one switch is line and 2 travelers and the other switch is load and 2 travelers. So while functionally the common screw means something, that depends on where/how the switch is installed. The only thing you can really do is call it common. And, in fact, that screw must be truly common - i.e., a single screw on one side (electrically, physically the screws could be located in any arrangement, e.g., common on left, travelers on right, common on top, travelers on bottom, etc.) because you must have a single incoming hot line wire on one switch and you must have a single outgoing switched hot load wire on the other switch or the circuit won't work properly.
Which brings us finally to the "2 switches in 1" which you have. These switches can actually be set up, potentially, 3 different ways:

2 line, 2 load
1 line ("common"), 2 load
2 line with a removable jumper, 2 load

The first choice lets you have two switches on separate circuits. Why? If they are high power devices (not much of an issue for residential lighting in the age of LEDs, but still important for bathroom heat fans and occasionally other things) then this lets you use more power than you can use with an ordinary single 15A or 20A circuit. Note that there may be additional restrictions - I know this OK (if done properly) with an MWBC with a double-breaker (or handle-tied), but it is not an MWBC it may be against code.
The second choice matches your description. It forces you to use only one circuit, but for typical lights and fans, and even a heat fan if it is sized appropriately, this works great.
The last choice is actually quite common too. It is really the same setup as a typical duplex receptacle where a removable tab lets you separate the two receptacles for switching purposes (not applicable here - you are installing switches!) or for more power using an MWBC, but the manufacturer only has to supply one device to serve both applications.
The end result is that the common screw is splitting internally to provide power to one side of both switches. Unlike the single switch, this means it must be line, not load. The other screws are, by definition (as opposed to by installation/usage) load, and therefore separate for each of two switched devices.
Another way to look at it: If you replaced the double switch with two single switches, you would add two pigtails to the incoming line wire and put one on each of the single switches, and put the load wires on the other screws of the single switches. The common screw is in place of the two pigtails.


What's with the timing of the OP and ED in Minami-ke?

Question: I've seen other anime where opening sequences are placed much later in the episode, sometimes as far as halfway through. Rarely endings begin a bit early, with a short (cliffhanger) scene following. In Minami-ke Okaeri endings are placed a good third of the episode away from the actual end, acting like a scene breaker. What's up with that? Why such odd timing?
Answer: I'd say the late opening is to grab attention and open the viewers mind as to what's going to follow in the rest of the episode without showing an opening which some people may immediately skip if it doesn't seem like their kind of show.
As to the show having more after the ending, I believe its put there as scheme or reward for sticking through the credits, and give people a bit more of the show to finish off.


Why are my mint plants getting brown weak stem feels they are dying

Question: I planted my mint plant from a stem and within 15 days new leaves were seen for which I was happy but in next 7 days the stems started turning brown and seems falling toward earth. What's the reason for the same? The plant get around 30 min sunlight in the day which is the limitation for me at the place I m staying.
Comment: How much water has the mint gotten? It sounds to me like a combination of too much water and too little sunlight. Does it really get only 30 minutes a day?
Comment: Ya just 30 min a day. But it grew in that much sunlight only where as I gave around 150 to 200 ml of water. However I would like to say that the water holding capacity of the soil is good. Should I mix some sand in the potting mix?
Answer: Too big of a pot for starting seeds.  In the garden this is very different.  You've got capillary action to spread the water out quickly in a lateral fashion which means there is AIR in the soil versus total saturation.  The soil drys out more quickly and is able to hold heat (better for germinating seed). You aren't using seeds just a stem of mint that is subjected to constant moisture and no air.  Mint is so tough and hardy, you are probably loving it to death, grins.
Any pot larger than a 2" by 2" peat pot will drown your seeds.  Also a bit of fungal rot to be expected because of this moisture. Propagating by vegetative means is the same but depending on the size of the leaf or stem/node chunk the pot is still proportional.  A 2" chunk, or a 1-2" leaf with a chunk of stem/node will be good in a 4" pot.  Just a leaf and petiole, 2" is better.  Moist not wet. Potting soil not garden soil.  Real grow lights.
You've used garden soil in a pot.  Big no no.  Always use bagged, sterilized potting soil for any plant in a pot.  Have you put rocks or gravel at the bottom of the pot below the soil?  This actually makes the drainage as bad as having no drain hole at all.
If these are grown from seed or are separate; get potting soil, little peat pots and a tray to hold them upright, fill 1/3 full, tamp down lightly or knock the bottom of the little pot a few times on a hard surface.  Using a teaspoon spoon soil and roots out of the 'soup' in the big pot, go very slowly so that you are able to pull as many of the long roots completely out of that soil.  You pull too fast and you'll rip valuable possibly viable roots.  Whatever you pull out is what you'll have and just continue to the new peat pot with 1/3 potting soil (dry).  Gently land your little plant into the peat pot.  With one hand support the little plant with a feather touch to keep it upright more or less.  The other hand grabs a handfull of potting soil, drop it around the little plant, gently press the soil down around the plant, shake it gently or pop gently on a hard surface to get rid of air pockets.  Do this until the soil is 1/4" from the rim.
If these plants are from a single chunk of mint stem, use a 4" peat pot with potting soil.  Knock as much soil off the stem that you can, leave the roots alone.
Put your plants under grow lights (minimum 400 watts) get the fixtures close enough to add heat but not burn or touch...4 or 6" above depending on the strength of your light source.  You could use those compact fluorescents that replaced our incandescent light bulbs...for a week or so, so that you can go find a real grow light. If you want to grow herbs inside, you have to have light. When starting seeds light isn't necessary (for most plants) WARMTH, moisture, air are critical.  When plants start showing green leaves then LIGHT is important.
Plants are designed to deal with night not constant light. They need to 'reset'.  A window is fine but still not as reliable and efficient as a properly placed grow light fixture.  Also needs air movement. A little fan would really help to make the environment as unfriendly as possible to fungus, there is already a wet environment you've transplanted with a teaspoon that is full of fungal spores. Water sparingly and allow to dry a bit before watering again.
When these plants become vigorous you will then want to think about fertilizer be very sparing, less is better than more (Osmocote extended release 14-14-14 works well and you don't have to worry about fertilizing more than 3 or 4 times per YEAR). When you see the roots growing out of the bottom and sides of the peat pots, up pot them to 4" peat pots.  Take the peat pot off the root ball, gently pulling it off without ripping roots too much.  Yeah, those pots are meant to be planted right in the soil in the garden but they still inhibit root growth into the new medium whether it is up potting in fresh potting soil or in the garden soil...
If these little plants don't make it, throw all the pots, soil and the diseased little dying plants in the compost pile.  The fungus they have is common and found in all non-sterilized soils anyway.
Get clean little peat pots with fresh potting or germination soil or you can use the expanding 'discs' that come with a tray made to hold each little 'pot' in place.  One seed per pot. Domes really help keep the environment moist, warm.  I always use fans, night and day for ventilation.  Proper light.  Warmth. Moist, not wet.


Approving tokens after flash loan

Question: I'm creating a smart contract that can both make flash loans and swap tokens via 0x. I can call the flash loan and token swap functions just fine, but when I try to call the token swap within the flash loan callback, I get the error: execution reverted: SafeERC20: low-level call failed.
If I understand this error correctly, I believe this means I'm not approving the tokens properly. Here's the gist of what my code looks like:
/// Make a flash loan.
function makeFlashLoan(...) {
    IERC20(borrowedTokenAddress).approve(zrxSpender, uint256(-1));
    lendingPool.flashLoan(...);
}

/// Callback for flash loan.
function executeOperation(...) {
    IERC20(borrowedTokenAddress).approve(lendingPoolAddress, uint256(-1));
    swapOnZrx(...);
}

/// Swap a token on 0x.
function swapOnZrx(...) {
    IERC20(fromToken).approve(zrxSpender, uint256(-1));
    ...
    (bool success,) = _swapTarget.call(_swapCallData);
    ...
}

If I make a transaction to just call swapOnZrx, the transaction succeeds. Similarly, if I make a transaction to just call makeFlashLoan with swapOnZrx commented out, the transaction also succeeds. However, When I call makeFlashLoan with the call to swapOnZrx, I keep getting the SafeERC20 error.
Any help would be greatly appreciated as I've been struggling with this error for almost an entire day :(
Answer: Yikes. Turns out this was happening since I wasn't paying back my flashloan.

Approving tokens after flash loan


SPSecurityTrimmedControl on Surveys overview.aspx

Question: I really need an expert advice.
I have been created classic Survey on Sharepoint Foundation 2013 and set all needed permission.
And this is great for my HR department except one thing.  They want me to hide "Show a graphical summary of responses" and "show all responses" links for end user, just Admin (HR department) can see those links.  After hours of googling I found (perfect solution for me) SPSecurityTrimmedControl.
But I dont know where to place this, because when I open my survey in designer I do not see any div or tr tag. So, my question is....where I need to insert this and how? This is picture of my overview.aspx of my survey.

Answer: The SPSecurityTrimmedControl is nothing more than a container that works by stopping its Render event when the specified permissions aren't meet. It doesn't enforce security of links - it just make them not rendered: anyone who knows the url can still input it manually. This also means that in order to use it, you need to wrap the content that you want it to remove. This is a problem in your case: from what I can understand from your question and screenshot, the content you want to secure is "dynamically" generated by a web part, and as such you cannot wrap it in a SPSecurityTrimmedControl instance - you would have to wrap all the web part, but that would remove all the content, not just the two links you need too.
That said, I was wondering. Any chance you may just work your way by re-configuring the permissions on the survey? I remember there is an option to make it so users can only read their own answer, and this post seem to confirm it. I don't remember if this will also remove the links, but may provide a starting point anyway. Otherwise, I fear you will have to resort to a Javascript/JQuery based solution to remove them on client side - but remember, you want to remove the permissions too, or the users could just write the url manually.
Comment: Hi, thank you for your explanation, I inderstand now. Yes, I was set permission for user that ther could see only their answer instead of all answer but my department is not statisfied with only that solution. But you know what, I don't care any more, because this level od Sharepoint is not in my domain to do this. Really really thank you :)
Comment: My pleasure, if you need something else fell free to ask another question. I wonder what made your department think that using actual permissions isn't a good solution: removing just the links fells like an attempt at "**security by obscurity**" and that is never good.


DNS name of virtual machine

Question: I need to reliably access the SqlServer running on my Windows 7 VM. I've tried setting a static ip and reserving that ip for the machine in VMWare's Nat config but that cuts off WAN access from the VM. Right now I am just editing my database url every time I restart the VM. Does anyone have a complete set of instructions on how to configure an internal NAT static IP in VMWare Fusion 5.0?
Answer: You'll have to manually edit VMware's network preferences and add static hosts to get this working. The file necessary can be found at /Library/Application Support/VMware Fusion/vmnet8/dhcpd.conf. The file is read-only so chmod it writeable first.
For each static host you'll have to add the following and change the hostname, MAC address and IP to your VMs:
host yourhosthere {
    hardware ethernet 11:22:33:44:55:66;
    fixed-address 192.168.87.100;
}

I'd recommend selecting the IP from outside the DHCP range, which is defined in the same file on the row starting with range.
After this you have to restart VMware services with sudo "/Library/Application Support/VMware Fusion/boot.sh" --restart
As for the DNS name, after you have a static IP you can add it to your /etc/hosts file using the following syntax:
192.168.87.100 yourhosthere

Comment: This worked for me with yourhosthere=the host name from the operating system not the VMWare name of the machine. Some of the paths are different in Mavericks. Thanks

DNS name of virtual machine


Is it OK to just replace the first 4 frets instead of all 24 on an Ibanez SR-300, because the first 4 were the only ones damaged by my negligence?

Question: Ibanez SR-300 4 String bass guitar re-fretIbanez 4-String Bassneck DR-300
Comment: Your link seems to be dead (I get an "invalid" message). Can you perhaps describe the damage? That might get you better feedback.
Answer: Absolutely. There's no point at all in replacing something that doesn't need replacing. Unless you want a set of fatter frets or suchlike.
You've checked all the fretwires, and only the first four are worn/damaged. All the others are o.k. So just replace those four, which may well need linishing to match the others.
Comment: Wow somebody answered my question here!! I'm going to like this site already!! Thanks a lot Tim
Answer: It's certainly possible to replace only some frets, and doing so is even common in some scenarios - for instance, on an instrument with Gibson-style binding where nubs of binding material are left at the end of each fret, it's a pretty major effort to replace all frets, so if only a few are damaged, it would be typical to only address those.
However, before you proceed, you may want to consider a few points. These concerns are somewhat subjective, if it's just a "player" you may not care versus if it's an important instrument that you want to preserve from an integrity perspective:

Outside of some well known brands/guitars with well known fret specs, it can sometimes be harder than it sounds to get a good match on the profile and size of the old fretwire. Even when people use standard-sounding names for wire (i.e. "Jumbo" or "medium") those names mean very different things to different manufacturers in terms of size, shape, and sometimes even the alloy used.
Depending on the condition of the other frets, even if you are able to match the wire, it may be difficult to get a completely un-noticable repair. At best, you may end up with nice shiny newly polished new frets, next to dull old frets. At worst, even with "matching" fretwire, you may need to do more work than usual to level and profile the new wire to match, especially if the old frets have been re-leveled in the past (which will give them less height and a different profile than when new).

When I approach a repair like this, I first consider if I can get a good match to the profile and dimensions of the wire. Some mainstream instruments (i.e. Fender, Gibson) have well known wire profiles, and even shorter versions of those profiles available to match existing frets that have been leveled. If I can get a good match, I consider the condition of the existing frets. If there's any question at all about their condition, I replace them all. Leveling new frets to match old ones usually involves "feathering" in to the old frets anyways, so in many cases it's not substantially less labor to leave them versus replacing them all.
You can get an idea on the wire specs needed by carefully measuring the existing frets. You can check width with calipers. Height can be a little more tricky, what I usually do is lay a straightedge across two adjacent frets, and then slip feeler gauges under the straightedge right next to one fret to measure the height of the straightedge above the fretboard. Unless you know your instrument is fretted with something non standard (i.e. stainless frets) you should aim for an 18% nickel alloy.
In the cases where I've only replaced some frets, I've always gone back over the existing frets and touched them up where needed, as well as polishing all frets from scratch so the sheen and brightness of the wire is all matched.


How to make fields available to users in Drupal 7?

Question: I want users to participate in creating some content. I allowed them (people/permissions)  to create own content on particular content type. The question is: how to provide them access to fields of content type, that are available to me as administrator? In other words, I can put content in fields through my admin panel, but how to make users possible to meet that fields, how to make fields  public?
Thanks in advance!
Comment: I didn't get the meaning of - 'but how to make users possible to meet that fields'. Considering, the content type is 'Hotel' & you want say, all the authenticated users be able to create content of type 'Hotel' and so associate data with the various fields, then you need to add permission 'Hotel: Create new content' by visiting 'admin/people/permissions'. If you need some role based permissioning, that you can control accordingly.
Answer: Give "Create content" permission to the user type who can create content at your instance.
There is the Field Permission module which lets you specify permissions for each field in a entity. You can set permission for each field by help of this module.
Answer: By default, all the fields added to an entity are visible to every user who has permission to create or edit entities of that type. (In the case of nodes, the users needs the permission to create or edit nodes of that content type.) field_access() is the function that determines which users have access to a field, but Drupal doesn't implement hook_field_access().
If the field is not visible to the other users, check you don't have a module that implements hook_field_access(), such as the Field Permissions module. If you have one of those modules, check their settings.
Alternatively, there is a module that makes the field not visible to the users. Also in this case, check its settings or temporary disable it to see if the field is visible to any other user.
Comment: Thanks, bit still I don't see how to display empty field box to user. It should be like webform field. One page with empty fields, that users populate with information. How to make page that displays empty fields?
Comment: For example, as administrator I can create Content type, and if I want to add some content, I have to go to content/add content, then choose content type, and empty fields appears. My question is: how to make page page that displays empty fields for users to type into?


Credit score drop

Question: I went into Regions Bank and opened a c.d. , a small one. After leaving I checked my credit score and it had fell by 75 points. I have been working on it for about 3 years and had it up to 725. This dropped me back into poor credit. What the hell happened, does anyone know. I have been back to the bank, call the numbers they gave me to inquire but get no answer. Anyone clue me in on the possibilities?
Comment: Opening a CD does not require a credit check. Are you sure they did it? You can check your credit and see who the inquiry is from then go from there, their contact information would be listed as well. And 75 points is unrealistic and more than a simple inquiry would ding you. Check to make sure someone hasn't reported a missed payment, or collection or something, that would hurt more.
Answer: Opening a CD in and of itself should't harm your credit rating but if you provided them with application details like reduced income, that could harm your credit. Also different credit scoring systems are used for different reasons so your score that would be used in you applying for a loan at bank X could be totally different from the score you're seeing.
Also for a credit score to update right after you leave the bank, your bank must have reported something to the major credit bureaus. Or someone else did something to your credit that coincidentally got updated at that time.
Answer: It is highly unlikely that opening a CD caused your credit score to drop.
Keep in mind credit score algorithms change somewhat over time.  Something may have changed in the calculation that caused your score to change.  It may have nothing to do with you.   One of the goals of the calculation is to prevent people from gaming the system.
For example, many years ago just opening a American Express card greatly increased your score.  You didn't have to use it but by staying in good standing with the old AMEX (that had to be paid off every month) made you seem like a good risk.  Never mind the fact that some people only had to pay off the annual fee.  That loophole has long since closed.
For my own score I see small changes when my monthly credit card statements come out.  If the statement balance is higher than last month, then my score drops.  I pay off the balance every month so it shouldn't matter, but evidentially it does.
Just as an editorial comment, you are far better off buying CDs through you brokerage account.  Fidelity, Vanguard, and Schwab all offer them.  They most certainly offer better deals and are typically sold in $1k increments.  You can pick the maturity that suits you best and it is done with a few clicks rather than going into a bank and possibly opening an account.

Credit score drop


How to search for an NFT asset name?

Question: Let's say, I have created an asset with name 'xyz' and I want to search for all the nfts with this asset name on the chain. How and where do I do that ?
Answer: May I ask why you'd want to do this?
It will be much easier for you to store the name of your NFT's in a database somewhere and query that instead of the blockchain. The blockchain is very quick at looking up NFT's under a given policy_id or asset string. Custom metadata? Not so much.

How to search for an NFT asset name?


I staked ZRX through Metamask on OX Protocol and it was an account linked to my Exodus Wallet. now I can't link to my staking

Question: ok connected metamask to stake ZRX on OX protocol.  imported OX keys from my exodus wallet to a new account in metamask. seemed to work for a bit then one day i tried to check on things and it wouldn't connect or log in to my imported account on metamask.  won't load tokens either.  you can see on etherscan the wallet
https://0x.org/zrx/account  this says loading gathering data for your wallet
metamask says connected but won't load any balances
etherscan shows all balances in exodus
also shows address is on 2 other chains. polygon and rinkeby testnet
tried to re import the wallet on the imported account not linking properly and it says it's a duplicate so metamask is reading it  don't know what to do
Answer: ok found out the settings for allowance of metamask to read your internet were off and when allowing it to connect to all sites the balances appeared in the account again and were accurate.  still cannot log into the ox protocol which is scary cause that's where my coins are and commented on etherscan of pool activity but nothing back yet


Getting information from a GBM model

Question: I built a gbm model (using caret package) in order to predict the probability of someone buy or not a car. However as this kind of model act as a black box my issue is to replicate the "profile" of the group who has higher probability to buy.
 There is any way to discover the values of the predictors that generate high prob?
Comment: You may be using sledgehammer where a normal hammer may do better for your problem domain.  Is extreme predictive accuracy actually important for your application, or just good enough accuracy?  You may want to consider using a good decision tree algorithm alone, as it is easy to derive the kind of information you are after from a tree.
Comment: Actually, based on my data this is a kind of a "hard" problem to solve with the "regulars" algorithms, this kind of algortihms(trees,logreg...) didn't give me a "good" accuracy and because of this I perfomed the gbm, and I can't figure out a simple way to discover this profiles
Comment: That's kind of the fundamental trade off.  If you want to get better accuracy, you have to use a model that can assume a more complex shape so it can fit the data.  But by assuming a more complex shape, it becomes drastically more difficult to meaningfully derive simple information from it.  Also, if you *need* a complex algorithm to get good predictive power, that goes some way to saying that there may be no simple profile that is meaningful at all.
Answer: I'd suggest starting with "partial dependence" plots which essentially show the effect of each feature (or set of features) with all other effects averaged out. A gbm can capture complex multivariate feature interactions so this won't tell the whole story but it is a good place to start.
Assuming you used the gbm package via carret the gbm.plot function can be used to make such plots.
Comment: I thought about it, however I don't know how to acces this plot on the caret object (gbm_fit)
Comment: I found how to access the gbm object: plot(GBM_FIT_FINA$finalModel, i.var = 1)
Answer: Assuming you're using R, the function is relative.influence(..). But you don't need it because summary(mod) would give you the same thing.
Comment: It is unclear to me how this answers the poster's question.

Getting information from a GBM model


Rails Active Record translation: Auto capitalize/downcase?

Question: Taking the default wording it self, in some case, user model will be displayed as 'user' (lowercase) as in "3 errors prohibited this user from being saved" and in some case as 'User' (capitalized) (as in nested-model form: User name can't be blank). That should be applied to other Latin-based language, right? How can I specify a model name translation so that Rails (Active Record?) display it in lowercase or in capitalized depends on the context (as pointed above)?
Answer: See https://github.com/rails/rails/blob/master/activerecord/lib/active_record/locale/en.yml. There are answers for both your doubts.
Comment: So the answer is: It's currently not supported?


How can I compel alphanumeric entries for username textbox on woocommerce registration form

Question: I am having a bit of a challenge with Woocommerce registration form. Currently, users are able to register using all numeric characters as their usernames. I can't think of a way to enforce that they use only alphanumeric combinations. Not only numbers. I can't seem to find any answers anywhere.
Answer: You can use the woocommerce_registration_errors hook to validate the username & set an error if your conditions aren't met - WooCommerce will bail and pass the error back to the UI for the user:
add_filter( 'woocommerce_registration_errors', function ( WP_Error $errors, $username ) {
    if ( ! preg_match( '/[a-z]/i', $username ) ) {
        $errors->add( 'username', 'Username must contain alphabetic characters.' );
    }

    return $errors;
}, 10, 2 );

Comment: Hi! Thank you for your response. forgive me, but I am relatively intermediate with programming. Does this code chunk go into functions.php?
Comment: Yes you can pop it in your functions.php. If you want to get a bit more "fancy", pop it in a [MU plugin](https://codex.wordpress.org/Must_Use_Plugins) - this helps keep your logic separated from your theme.


Is it OK to use a lower voltage to operate a relay coil than rated coil voltage?

Question: I want to know if I used a lower voltage than what was labeled on the relay was OK. The relay was a 24V relay.
I check that the relay turns on when the voltage when the voltage was 13.5v.
If I apply that voltage is it reliable?.
EDIT: I do not have a datasheet but here is the part number: HTCA024V
Comment: Data sheet required.
Comment: Find a data sheet for it - the number you gave in your edit does not show any results.
Answer: Electromechanical relays are really current operated devices. The relay pulls in when the current is sufficient. The current is determined by the operating voltage and the coil resistance. But the plot thickens - the coil resistance is a function of temperature- the coil temperature- increasing by about 0.4% for every degree C. The coil is heated by the current through it, as well as by the ambient conditions. It is also heated by resistive losses when the contacts are carrying current. The temperature rise above ambient might be 35 C so if the temperature outside your box is 45 C, and the temperature inside is 70 C the coil could easily be running above 100 C. That means the pull in voltage will increase by 1/3. In fact high temperature versions of relays have less tolerance than the usual ones.
Bottom line is that the relay engineers designed the relay to be reliable at the nominal voltage (with a bit of tolerance for unregulated supply voltage) over a reasonable temperature range, and with rated current flowing, and to account for manufacturing variations (friction, spring constant, magnetic properties).
If you know that those assumptions are somehow conservative in your situation (say you have a tightly regulated supply) you may be able to shave a bit off, but you if you are wrong the relay operation may not be assured or contact life may be compromised due to more arcing from sluggish operation. For example the relay may not pull back in on a hot day immediately after it has been on for a while.
Holding current is less than operating current (and contact pressure is not compromised in most relay designs) so it's sometimes possible to give a higher voltage pulse to operate the relay then back off to a lower voltage, but that's seldom worth the trouble.
Comment: When I apply 24V I get a harder click than the 13.5 V click
Comment: The resulting lower contact pressure results in a higher contact resistance which can result in the contacts overheating and this results in damage to the contacts which shortens the life of the contacts.
Comment: @Spoon This is not generally true, as I said above. The armature is fully in contact with the pole piece so the contact pressure is set by the contact over-travel and the spring constant. The relay will take longer to close- and if the supply is dodgy and sags chattering is possible.
Comment: It's the quality of the relay that makes the difference. If it does fail look at the contacts to see if they are damaged welded. Of course cheap relays may be a worse problem.
Answer: It depends on the application.
You will find that the relay switches much more quickly when powered at the rated voltage. This results in clean switching with minimum arcing and contact bounce. For a low current application it may be fine. For a high-current application you will probably burn out the contacts fairly quickly.
Note that as the relay armature pulls in that the magnetic circuit air-gap reduces and this increases the magnetic field strength even further, etc. You should find that if you can pick from fully open at 13.5 V that it should hold on until the voltage drops to maybe 2/3 of that.
When the armature gap is closing it is working against the springiness of the contacts. If you can get the cover off the relay you could energise the relay and then press the armature with your finger to confirm that it is fully closed. If not then you might find that it stops when the first contact closes and the second contact doesn't make.
Answer: You must meet at least the operate voltage of the relay as given in the datasheet. If you do not then it is very possible that the relay will not switch.
Comment: Or not switch correctly, switch slowly or switch unpredictably.
Answer: The voltage value that is specified for a relay is the value at which the manufacturer guarantees the operation.
From experience, I know that usually the relay is activated with lower voltage on and off with a much less than the activation voltage.
However, to ensure the functioning of the circuit, you must respect the nominal voltage, as specified by the manufacturer.
Answer: Most relays have a range of voltage specified in their datasheet in which the relay can operate. The minimum voltage of that range is only needed to reliably switch the relay to its new state, and is sometimes called the "must operate voltage".
After switching, a voltage significantly lower than the "must operate voltage" could be applied to keep the relay activated.
Take a look at a snippet from this this answer:

12 V relay at 5 V
Here we get to the Real Savings™. First we'll have to explain the 5 V operation. We already saw that we can operate the relay at 9 V, since the "must operate voltage" was 8.4 V. But 5 V is considerably lower than that, so it won't activate the relay. It appears, however, that the "must operate voltage" is only needed to activate the relay; once it's activated it will remain active even at much lower voltages. You can easily try this. Open the relay and place 5 V across the coil, and you'll see it doesn't activate. Now close the contact with the tip of a pencil and you'll see that it remains closed. Great.
Comment: Is it possible to use a capacitor or something to get the higher initial voltage, and then maintain the closed with a lower current? I'm looking for a DPST relay that can handle 15 Amps AC, and the switching voltage seems to be higher for those.


I can't find my other HDD

Question: New Ubuntu user here... I have Ubuntu on my 250GB SSD and I have another 500GB on my laptop that Ubuntu can't find. I'm not sure where or how to start finding it.
Comment: Typing `lsblk` in a terminal window should return a list of all the partitions on your system, including ones that are not mounted.
Answer: You might need to edit your /etc/fstab to mount your extra drive. Here's how you can check.
Type lsblk into a terminal like Organic Marble suggested. Devices named like sda, sdb, and sdc are going to be distinct drives, while sda1, sda2, etc are partitions of that drive.
If your drive isn't showing up in lsblk, then someone more experienced than I will need to answer your question. I'd guess it means that your drive isn't connected properly, but I don't know for sure.
However, if you do see a drive that's showing up in lsblk, but doesn't have a  MOUNTPOINT, then we can likely assume that it's your drive, and we can follow a few simple steps to get it set up. Let's assume that your device is sdb.
First, figure out which partition of your 500gb drive you want to mount. If you have multiple partitions, then you'll need to do this for each partition. Let's assume you want sdb1.
Next, you need to figure out where you want to mount the partition to. I usually end up mounting all of my drives in the /media directory, with a subdirectory for the partition. for example, my local network share is mounted in /media/fileshare. Either way, decide where you want to mount this partition, and create a folder for it, like this: sudo mkdir -p /path/to/mount/directory.
Next you need to figure out the filesystem type. Type sudo parted -l to get a list of all drives connected to the computer. Find the drive in the list that matches your drive. The partitions will be listed starting at 1; note the column for 'file system'. Let's assume yours is ext4.
Now, open your /etc/fstab file with root permissions using your favorite text editor. Nano is pretty easy to use: sudo nano /etc/fstab. The fstab file contains information about all the drives that get mounted to your computer and tells the OS how and where to mount them. You should see a couple lines in there which correlate to your main drive as well as your swap space. You want to add a new line sort of like this one, but with whatever the values you came up with are:
# partition   mount location  filesystem  options   dump   pass
/dev/sdb1    /media/fileshare    ext4    defaults,     0    2

Where the defaults refers to all of the default options found here. I'm no expert on fstab options, but someone else might be able to help you more here.
Now, save and quit whatever text editor you used, and run the command sudo mount -a; this re-mounts all partitions found in fstab. Assuming you did everything right, your partition should be mounted, and you should be able to access your files from whatever mount point you specified in the fstab file.
Comment: Hey here's a screen shot of my terminal [https://i.imgur.com/YTboM8t.png]. I think "sdb" is the 500 gb hardrive with "core" (idk what that is). Oh on "loop1" I have the Atom that I can't run when I click the icon but runs when I 'sudo atom' in the terminal.
Comment: Looks like `sdb1` is the partition you want to mount. For `sudo parted`, you want to use `-l` (lowercase L), not `-1` (the numeral one).
Comment: @NotThatGood, did you get this working?

I can't find my other HDD


i want to change pop up for paypal on checkout after click continue to paypal

Question: i want to open pop up in new tab rather just showing in pop up.Can i change the width of Pop up.Plz help
https://ibb.co/iGMBPk
Answer: Edit you PayPal setting:
Log into your Magento 2 Backend
Goto  Stores -> configuration -> sales -> payment methods ->  PayPal express checkout -> required PayPal settings -> express checkout  and search for the "enable in-context checkout experience" set it to "No"
After doing this possible clear your cache(I don't think you need to redeploy static content).
Customers should now be redirected to the PayPal website instead of seeing a pop-up. Keep in mind that this might not work or be legal in all regions as stated below the field "enable in-context checkout experience"
And have a nice day!
Further information:
Magento 2 documentation
http://docs.magento.com/m2/ce/user_guide/payment/paypal-in-context-checkout.html
PayPal documentation for in-context checkout
https://developer.paypal.com/docs/classic/express-checkout/
Answer: Go to
magento admin panel-> store-> configuration-> sales-> payments methods-> paypal-> configure

Now required
paypal setting-> express checkout-> Enable In-Context Checkout Experience (select no).

and you get what you want...!!!!


Callable interface

Question: I have a c++ program that generates large numbers of small graphs (millions). I would like to remove graphs that are isomorphic to each other so I am thinking about trying to use the callable interface to mathematica to do this.
I see there is something called WSTP with essentially string interfaces. I see mentions here of MathLink but that isn't in the list of topics when I look in help so maybe that's an older interface.
I am wondering if it's realistic to call mathematica a large number of times via the WSTP interface to essentially just check if two small graphs are isomorphic.
My graphs are acyclic multi-digraphs with a single source and sink. My notion of isomorphic is a path-edge incidence matrix that is a row and column permutation of another path-edge incidence matrix. So I will generate a kind of line graph that has a vertex for an edge and a vertex for a path and a directed edge if the edge is in the path and test these for isomorphism. Maybe ~100 paths and ~10 edges.
A naive isomorphism test like in boost or my own code is too slow.
Comment: WSTP and MathLink are the exact same thing.
Answer: You should not test pairs of graphs for isomorphism, as that is quadratic in the number of graphs, and it's hopeless. You should compute a canonical labelling of each graph with a suitable library (bliss, nauty, traces, etc.—not Boost which only has VF2 for testing pairs of graphs), then use a set data structure to remove duplicates.
I do not recommend trying to call Mathematica to do this. It will be very slow. I know this as I created IGraph/M and suffered plenty of frustration due to Mathematica's lack of performant facilities to convert a Graph to/from some format that is friendly to C++. They didn't add this even after years of requests.
Just use a C or a C++ library from your C++ program. It'll be faster than what Mathematica has anyway. I believe Mathematica may be using an old version of nauty.
Comment: Thanks for this. I am familiar with the concept of a canonical labeling. Since I am currently running on Windows I thought mathematica might be the path of least resistance but that doesn't seem likely now. I'll shift to trying to get my program running in the linux subsystem.
Comment: @NeillClift why do you think that running in Linus will improve the difficulty of what you are trying to do now?
Comment: I am not exactly sure what your asking. My thinking is that since mathematica doesn't seem to offer functionality I can use for this problem I should probably try and get nauty working. As far as I can see this only runs in unix.
Comment: @NeillClift It's not Unix-specific. If you are going to use an automorphism finder from C++ code, I would recommend Bliss over Nauty: it has an easier to use API.
Comment: Szabolcs, thanks for that suggestion. I got bliss working quite quickly and doing the isomorphism test on my graphs. Looks fast enough for my experiments.

Callable interface


Are these the same " In five of the six disciplines" and "in five out of the six diciplines"

Question: As in the title mentioned above
Are these are the same?

In five of the six disciplines

and

In five out of the six disciplines

Are these of the same meaning? Otherwise, which phrase is correct?
Answer: Both mean the same thing, and I don't believe there would be any reason to use one rather than the other.  One might say that the first version is a bit more "efficient" than the second, but that's about all.


How to Cite With Inconsistent Use of Initials

Question: There is a paper I want to cite where, on the title page of the article, the authors names appear without any middle initials (i.e., one of the authors is Mark Smith).  However, this one author frequently publishes using his middle initials (i.e., Mark E. Smith).  What is the appropriate way to cite this-with the name as it appears in the article, or the name as the author typically uses it?  For what it's worth, the source article appear in a mathematical journal, and I want to cite it in a paper that will eventually appear in a mathematical journal.
Answer: You should use the exact information which is provided on the published paper, not the real or current information of the author; even if his name or affiliation1 is change at the present time.
Moreover, the correct way of citation of each paper is provided in the webpage of its publisher and you can check how they have mentioned the author's name in the citation example (you may also download the bibtex or other outputs to be used in citation manager softwares). At least, by checking the publisher website, you will be sure how they prefer their published paper to be cited (even if other possibilities/doubts for correct citation exists).
1I know that affiliation is not mentioned in citation, but if somebody wants the affiliation of the author at the time of publishing the paper, the best source is the information written on the paper and is provided in its publisher's website.
Comment: I've never seen a citation to a paper that included the affiliation of any of the authors.
Comment: @DavidRicherby Me either, but I wanted to say that the correct affiliation of the author *at the time of publishing* the paper is mentioned in the webpage of the paper in the publisher's website; besides to his correct name which is mentioned on the paper and an example of citation which publisher prefers to be used in other sources.
Answer: You need to cite articles the way the name is expressed in each article. The purpose of the reference if for others to be able to locate the source you have used and so making the reference accurate is essential. It may seem like nit-picking since most of the reference will be correct except for one initial but it is better to simply follow the the generic rule to follow the article in all details than to modify it. One instance where this may matter is when article references are listed in, for example, Web of Science. There an article may end up as two entries if there is a difference in the way it is referenced. I have seen and personally have articles that have multiple entries because of this and because people wrote the wrong year, volume etc. Still, the importance lies in being able to trace your sources and being correct makes that easier.
Comment: I'd recommend to use the DOI in any case, especially if the journal you publish in converts DOIs to clickable links, which should fully address Peter's utterly valid point (+1).
Comment: I strongly disagree; see the upvoted answer in the duplicated question. Citation practice should not depend on bugs in Web of Science's software.
Comment: What if the journal/conference paper does not have a DOI?
Comment: @JeffE, that is not my main point either. I can remove that part if it irritates you.


Stationary states in Schrödinger's equation

Question: I was following my book's analysis on a free particle possessing potential energy and it got to the point where $(\psi(x,t))^2$ no longer depended on time. Maybe I'm misunderstanding but does this imply that the particle is not moving? If this is the case, how? Doesn't Schrödinger's equation also include kinetic energy?
Answer: The short answer: Not necessarily.
The long answer: Suppose you have a ring rotating, so that if you look from far away the ring appears ''stationary''. However, each part of the ring is still moving, despite the fact that the mass distribution is constant.
It is the same with stationary states. Take the free particle as an example. The stationary states are of the form $\psi\sim e^{i (-\omega t+kx)}$. So, graphing this wave function, you will see that it is indeed moving.
The measure for the moving of particles is the "current" $j=\frac{\hbar}{2mi}(\psi^*\partial_x\psi-\psi\partial_x\psi^*)$. You can try calculating this on the free particle, and it should be a nonzero number.
Answer: What book are you reading? It's helpful to know so that I know what formalism you're familiar with. Examing Schrodinger's equation,
$$ i\hbar \frac{\partial}{\partial t} \Psi(x,t) = H \Psi(x,t) = (K + V) \Psi$$
where $H$ is the Hamiltonian, $K$ the kinetic energy, and $V$ the potential energy, we see that in the "free particle" case, when $V = 0$, the energy is determined only by the kinetic energy. In nature, potentials can be very complicated, so textbooks of course begin with simple examples, i.e. infinite square well, finite steps, harmonic oscillator, etc...
To find the state of the system, represented by the wavefunction $\Psi(x,t)$, we need to solve Schrodinger's equation. Some potentials are simple enough that they are "separable" meaning they can be separated into a product of functions of their respective variables. In intro quantum mechanics, the Schrodinger equation is a separable differential equation $\underline{when}$ the potential is independent of time. All (or most) of the examples in your textbook have potentials that are independent of time, and they are all probably solved by the method of separation of variables, thus they all have solutions called "stationary states."
They are called stationary because they do not depend on time, rather they depend on position, and they are eigenstates of the Hamiltonian (they satisfy the eigenvalue equation for $H$). What does this mean? Stationary states are nice because they 1) provide time independent probability densities and expectation values, 2) they are states of definite total energy, 3) the general solution of this separable Schrodinger equation is a linear combination of the stationary states.
So then, since stationary states form a complete orthonormal basis, we may write,
$$ \Psi(x) = \sum_{n = 0}^{\inf} c_{n} \psi(x).$$
where the $c_{n}$ are constants determined from an orthonormality condition.
To obtain the full time dependent solution, we simply multiply the stationary states above by the time dependent factor obtained by solving the time dependent part of the Schrodinger equation:
$$ \Psi(x,t) = \sum_{n = 0}^{\inf} c_{n} \psi(x) e^{\frac{-iE_{n}}{\hbar}t}.$$
The classical notion of the particle "moving" is nonsense in quantum mechanics. There is a probability density that it will be found somewhere, and it will have an expectation value (the average over a large amount of identically prepared systems) of position from which you can obtain an expectation value of velocity, but if it pleases you, one may of course consider the particle as moving between states that it's measured to be in at various times, or the more traditional attitude is that it's nowhere - it's just a probability density - until it's measured. Examine a stationary state as it evolves in time here: since $\rho$ is constant in time, the area under the curve is constant.
For the correspondence between the classical notions of velocity and momentum to quantum mechanics, see Ehrenfest's Theorem.
Comment: Awesome! So I assume in some instances that the expected value of x can change over time. If so, if you were to take the derivative of the expected value with respect to time, would this be the expected value of the velocity? I am reading "Modern Physics" by Randy Harris, pretty intro stuff.
Comment: If you are taking an expectation value of some observable using a stationary state, then the expectation value is constant in time. Period. However, if you are taking an expectation value of some observable using a linear combination of stationary states, then the expectation value will depend on time (due to cross term). So, the general solution I wrote above (with the sum) does produce time dependent expectation values. Griffith's intro to quantum mechanics book is a great place to start, and in it he talks about Ehrenfest theorem, for which i added a link in my answer at the bottom.


$form_state['redirect'] vs drupal_goto() in Drupal 6

Question: What is different between $form_state['redirect'] and drupal_goto() to redirect user to a step in multi step forms in Drupal 6 ? I used $form_state['redirect'] but no redirection happend so I use drupal_goto() .
Answer: $form_state['redirect'] is not well documented in 6, but my understanding is that when it's populated it will not always work (see the part about exceptions), so although that's documentation for 7, check that other elements of your $form_state are not interfering. If you are working with a multi-step form, it might be that you need to unset $form_state['storage'] first.
drupal_goto() is simply a function will take the user away from the current page to whatever path you specify, and has a bunch of extra features for doing extra things (see the documentation). It is actually called anyway when your form redirects.
When a Drupal form is submitted,$form_state['redirect'] overrides the default form redirect (which will take you to the form you've just submitted) and thus is calling drupal_goto() on your behalf. By putting it in a variable, you can ensure that Drupal handles, in the background, when to do the redirect, rather than you having to specify drupal_goto() directly and getting it wrong.


NIST's Methods for Key Wrapping?

Question: NIST has specified a full Mode of Operation for Key wrapping. What are the pros and cons of key wrapping mode of operation as compared to CBC, CTR or authenticated encryption mode?
Answer: There are the differences (whether they're con's vs pro's depends somewhat on what you're using it for):

Performance; the NIST key wrap is much slower than anything else on your list (and can't be parallized; some algorithms on your list can be).  On one hand, if you're using it for key wrap, well, we typically don't wrap/unwrap keys so frequently that it really matters.  On the other hand, you probably don't want to try to use it to encrypt packets on your 10Gbps link...
Integrity; if the attacker modifies a key wrapped ciphertext, there is a probability circa $2^{-64}$ that, on unwrap, it would be a valid (and effectively random) key; this probability is considerably higher than an authenticated encryption mode (but better than CBC or CTR without any integrity protection whatsoever).
Determinism; the key wrap algorithm is deterministic (based on the wrapping key and the plaintext); hence, if you wrap the same key twice with the same wrapping key, an attacker can detect that; the other modes you have listed are randomized.  On the plus side, this means that the key wrap mechanism is not subject to 'algorithm substition attacks' (where the attacker doesn't use a truly random randomizer, but instead selects values that leak some information).  In addition, you can make the key wrap randomized by the simple expedient of including some random data along with the key (and which is discarded after the unwrap).
Ciphertext overhead; the key wrap adds 64 bits to the plaintext length (assuming that the key you're wrapping is a multiple of 64 bits in length); this is less overhead than the other algorithms.

You might be wondering about differences in cryptographic strength.  There is effectively no difference; as long as the wrapping key is secure, and everything is done properly, any of these methods listed is essentially immune to cryptanalysis.
Comment: Please explain the "Determinism" point. i couldn't understand it. also the algorithm substitution attack?
Comment: @Raza: determinism means "if you encrypt the same plaintext with the same key, you'll always get the same ciphertext"; for (say) CBC or GCM, you include an IV; using different IVs generated different ciphertexts.  As for algorithm substitution attacks (IMHO, lousy terminology, but it's what people use), we assume that the encryption engine is what's trying to leak data, and so instead of running the standard algorithm, it selects nonrandom IVs; you can show that it can always select IVs in a way to leak data; you can decrypt properly, but data is still leaked.
Comment: determinism i am clear now, ECB is deterministic and sementically not secure. but algorithm substitution attacks still not, any example or paper?
Comment: @Raza: https://eprint.iacr.org/2014/438.pdf

NIST's Methods for Key Wrapping?


What would someone who has seen too much of something be called? Or is there no word for this?

Question: Like when someone discovers something about their government that was suppose to be hidden & they get eliminated because they found out about it.
Comment: In addition to "liability" there is "a loose end" as well as "witness"
Answer: A person who's seen too much or knows too much - that's the usual idiom.
The single word that comes closest is liability, but that's more generic and you need to put it in the right context, for instance:
"You just know too much about our operation, Mr Quinn. You've become a liability, and as much as it personally pains me, you have to be eliminated."
(That could be a cliched line from any cheesy espionage thriller).
Answer: Witness at risk--See NYTimes story 'With Witnesses at Risk, Murder Suspects Go Free', March 1 2007


How long to wait after completing reasoning test?

Question: I completed a reasoning test for job on Sunday (May 16),
and was wondering how long it would take for HR to reply?
The job offer is new though and only listed since May 9.
PS I probably got around ~60% of questions right?
Comment: Unlikely you're going to get the job so stop worrying about it.
Comment: Depends on the company,  how quick the job is progressing,  and how interested they are in you.   We can't tell you.
Comment: Varies from Company to Company
Comment: Possible duplicate of [Following up after technical test (duplicate)](http://workplace.stackexchange.com/questions/62274/following-up-after-technical-test)
Answer: Once you have given your post-interview feedback to the person interviewing you, any further or repeated inquiry will send a message of neediness and desperation.
The time frame you've outlined would dictate that there is a strong possibility that they are still interviewing people, and still compiling a list of more possible candidates. You are unlikely to hear back from them immediately unless you've nailed the interview, to the point of them not wanting to hear from anyone else. Which, from your own assessment of the reasoning test, you did not.
My advice would be to always continue the job hunt until you have an offer; the last thing you want to do is pass up an opportunity because you suspect someone is getting back to you about another. And think of this interview as a learning experience.
Comment: That last paragraph is always true : go on hunting until you've signed something you like.


Gaussian Process Regression Variance

Question: While doing regression using Gaussian Processes, isn't the variance of the posterior supposed to be low where training data has already been observed?
Answer: Yes, that is the idea. We are confident when we see data and less confident where we have not seen data. However if you are not finding this, here are some potential reasons:
Poor Model: If you use a kernel (perhaps periodic) you may find that the variance is small where no data is present. This is because the kernel thinks that the data is 'close' to data it has already seen.
Poor (Hyper-)Parameters: If you have not optimised over (hyper-)parameters, or your optimisation has fallen into a local minima, you may find that the variance of points close to data is large. For example if the length scale of a RBF kernel is tiny, or you are adding iid noise to your observed data ($K^+=K + \sigma I$) and the noise is very large.
Numerical Errors: Attempting to perform $K^{-1}$ without cholesky sometimes give really weird results on poorly conditioned data.
Silly Mistakes: This often happens when you code up your first few GPs. You scale your x-axis and forget to recompensate or something of this nature. This can be hard to spot initially but you do become more confident after debugging and finding your own mistakes.

Gaussian Process Regression Variance


Making a better Engineer

Question: I have an Engineer which doesn't look very good. How can I make him better organized?  What about good practices?
Interface:
public interface Engineer {
    String HOMELESS = "homeless";
    String ENGINEER = "engineer";
    String SOFTWARE_ENGINEER = "softwareEngineer";
    String TEST_ENGINEER = "testEngineer";
    String TEST_AUTOMATION_ENIGNEER = "testAutomationEngineer";

    static final int WORK = 1;
    static final int LOOKING_FOR_NEW_JOB = 2;
    static final int BUSY = 3;
    static final int FREE = 4;
    static final int SLEEP = 5;

    boolean isHappy();
    String getEmployer();
    String getType();

    String makeOffer(int salary, String employer);

    void fire();
    void setView(EngineerImpl.View view);
    /**
     * Sets employer
     * @param name
     * @return
     */
    void setEmployer(String name);
    String getName();
    void startWork(long time);

    /**
     * Stops {@link Engineer}
     * @return
     */
    int stopWork(long time);

    /**
     * Sets {@link Engineer} into hibernate mode for {@code seconds}
     * @param seconds
     */
    void sleep(int seconds);
    boolean eatPizza(int pieces);
}

Implementation:
public class EngineerImpl implements Engineer {

    private View view;

    static class EngineersFactory {
        public static Engineer getEngineer(String name, String type) {
            return new EngineerImpl(name, type);
        }

        public static Engineer getEngineer(String name) {
            return getEngineer(name, ENGINEER);
        }

        public static Engineer getSoftwareEngineer(String name) {
            return getEngineer(name, SOFTWARE_ENGINEER);
        }

        public static Engineer getTestEngineer(String name) {
            return getEngineer(name, TEST_ENGINEER);
        }

        public static Engineer getTestAutomationEngineer(String name) {
            return getEngineer(name, TEST_AUTOMATION_ENIGNEER);
        }
    }

    interface View {
        void showSmile();
    }

    private boolean isHappy = false;
    private String employer;
    private int salary;
    private String name;
    private int status;
    private long workStartedAt;
    private int previousStatus;
    private final String type;

    public EngineerImpl(String name, String type) {
        isHappy = true;
        this.name = name;
        status = WORK;
        this.type = type;
    }

    @Override
    public String getType() {
        return type;
    }

    @Override
    public void setView(View view) {
        this.view = view;
    }

    @Override
    public boolean isHappy() {
        return isHappy;
    }

    @Override
    public String getEmployer() {
        return employer;
    }

    @Override
    public String makeOffer(int salary, String employer) {
        if (shouldIAcceptNewOffer(salary, employer)) {
            acceptOffer(salary, employer);
            return employer;
        }
        return this.employer;
    }

    @Override
    public void fire() {
        this.salary = 0;
        this.employer = HOMELESS;
        isHappy = false;
        status = LOOKING_FOR_NEW_JOB;
    }

    @Override
    public void setEmployer(String name) {
        this.employer = name;
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public void startWork(long time) {
        status = BUSY;
        workStartedAt = time;
    }

    @Override
    public int stopWork(long time) {
        status = FREE;
        view.showSmile();
        return (int) (time - workStartedAt);
    }

    @Override
    public void sleep(int seconds) {
        previousStatus = status;
        status = SLEEP;
        try {
            Thread.sleep(seconds);
        } catch (InterruptedException e) {
            // ...
        }
        status = previousStatus;
    }

    @Override
    public boolean eatPizza(int pieces) {
        isHappy = ((pieces % 2) == 0 && status == FREE);
        if (isHappy) {
            view.showSmile();
        } else {
            sleep(10);
        }
        return isHappy;
    }

    @Override
    public boolean equals(Object engineer) {
        if (this == engineer) {
            return true;
        }
        Engineer e = (Engineer) engineer;
        return this.isHappy == e.isHappy() && hashCode() == e.hashCode();
    }

    @Override
    public int hashCode() {
        return getName().hashCode()
                + getEmployer().hashCode()
                + getType().hashCode();
    }

    private boolean shouldIAcceptNewOffer(int salary, String employer) {
        return salary > this.salary && employer.equals(this.employer);
    }

    private void acceptOffer(int salary, String employer) {
        this.salary = salary;
        this.employer = employer;
        isHappy = true;
        view.showSmile();
    }
}

Some explicit questions:

Is it OK to put constants to interface and use them in the implementation?
Should I make constants static final if they are defined in an interface? Which constants should I prefer, int or String?
Can I make some additional actions in setters?
When should I write a JavaDoc?
Answer: This code is, depending on your point of view, either over-engineered or just wrong.
The whole point of separating the interface from the implementation would be to make the interface independent of the implementation.  Yet, your interface mentions EngineerImpl.View, which defeats the whole purpose of that separation.
The fix, if you consider the code to be over-engineered, is to forget about splitting the interface and implementation, and just make an Engineer class.  If you don't intend to write any other implementations of the interface, that would be the way to go.  Alternatively, you could fix it by moving EngineerImpl.View to Engineer.View.

In addition, the EngineersFactory is in a weird place.  A factory could be useful if you want the caller not to instantiate objects directly — for example, if the caller doesn't know what class to instantiate.  Putting the factory as an inner class of EngineerImpl seems to suggest that the factory is meant to only produce EngineerImpl objects, though.
The naming of the methods in the factory is also off.  "Get" implies fetching an existing instance (like a singleton), not creating a new one.  For a factory, names like createEngineer(), makeEngineer(), newEngineer(), or just engineer(…) would be more appropriate.
Again, I'm not sure what value the factory adds.  The EngineerImpl(name, type) constructor is already public, as are the string constants for the types.  If you abandon the interface-implementation separation, then you would be better off eliminating the factory as well.  Alternatively, keep the factory, but make the EngineerImpl constructor private so that there is one right way to instantiate objects.
Comment: Nice caught on factory issue and View interface placement.
Comment: This code is just collection of common places I see daily.
Answer: static final int WORK = 1;
static final int LOOKING_FOR_NEW_JOB = 2;
static final int BUSY = 3;
static final int FREE = 4;
static final int SLEEP = 5;

A few things specific to this
First, using int is a bad idea.  Allow me to demonstrate
engineer.sleep(LOOKING_FOR_NEW_JOB);

I don't think engineer.getSpouse() is going to buy the notion that napping counts has job hunting.
engineer.eatPizza(FREE);

The poor schmuck trying to debug things later is likely to get many confused -- where did the engineer find free pizza?
It looks very much like what you are trying to describe is the "state" of the engineer.  Enums are a good tool to use for that.
public enum EngineerState {
    WORK, LOOKING_FOR_NEW_JOB, BUSY, FREE, SLEEP
}

Second point to make is that these look a lot like implementation details; notice that no part of your interface uses these ideas at all.  That being the case, they shouldn't be defined in the interface.
You might also consider that if you are trying to track state, then you should have a state machine (somewhere).  Make that explicit -- state machines are a very powerful idea, and if you aren't familiar with them you should correct that.  I happen to think stateless4j is a good library for that.
Turning the over-engineering up to "11": right now your Engineer interface seems to be serving two different roles.
void startWork(long time);
int stopWork(long time);

void sleep(int seconds);
boolean eatPizza(int pieces);

These methods all look like they are part of an Engineer model; they are a bunch of methods that tell your in memory representation of an engineer how to change to match the real world.
String makeOffer(int salary, String employer);
void setEmployer(String name);
void fire();

These also look like methods in a model; but the spelling of the method names is wrong.  makeOffer and fire are things the boss does.  For a model of an engineer, they should probably be receiveOffer and loseJob, or something similar.  setEmployer is a weak name -- in a model, we don't touch properties, but instead mimic behavior.  acceptJob is the verb that causes the employer to change.
boolean isHappy();
String getEmployer();
String getType();
String getName();

These methods all look like an Engineer projection - a bunch of questions you might ask about the engineer at a particular point in time.  These shouldn't be part of the same interface, because they serve a completely different role.
(It would, of course, be reasonable for the EngineerImpl to implement both interfaces in a simple program.)
Answer: The makeOffer() method could be cleaned up. Since the shouldIAcceptNewOffer() and acceptOffer(), both are only used once for this single method it would make more sense to handle all the logic in one method.
Like so;
 public String decideOnOffer(int salary, String employer) {
    if (salary > this.salary && employer.equals(this.employer)) {
        this.salary = salary;
        this.employer = employer;
        isHappy = true;
        view.showSmile();
    }
}

This method saves passing through the parameters salary and employer again unnecessarily and is a more neater/conventional approach.
Answer: In addition to all the other excellent answers...
Seeking new employment
@Override
public void fire() {
    this.salary = 0;
    this.employer = HOMELESS;
    isHappy = false;
    status = LOOKING_FOR_NEW_JOB;
}

I'm pretty sure HOMLESS can't be an employer. Also, does calling this method imply the engineer is fired, or the engineer has decided to fire the employer? Should there be a difference between resign() and retrench()?
Dates
Using long primitive to represent 'times' is an archaic concept from the old java.util.Date-based classes. In case you are not on Java 8 (with its new java.time.* APIs), you should look at the JodaTime library to better represent chronological events/periods. The long primitive also makes it questionable what is the epoch you are using. As a last resort, even a Date object will be better as it clearly represents a date-time, and uses the well-understood Unix epoch so that there is no ambiguity there.
equals(Object) comparison
@Override
public boolean equals(Object engineer) {
    if (this == engineer) {
        return true;
    }
    Engineer e = (Engineer) engineer;
    return this.isHappy == e.isHappy() && hashCode() == e.hashCode();
}

You will also need to return false when the input is not an Engineer implementation. This is partly why for the equals(Object) method, the argument name used here is usually something along the lines of object, obj, other or just o. It cannot be assumed that the casting will always work.
Answering your questions

Is it OK to put constants to interface and use them in the implementation?

Certainly, so long that it makes sense for them to 'belong' to the interface.
edit: After some Googling, I think it's prudent to clarify that this is not an endorsement of the constant interface pattern, and I hope you are not alluding to that. An interface should be used for its original purpose, foremost. It should not be used purely to attach constants to classes implementing the interface. When implementations require some constants to ease inter-implementation operability, or said constants are abstract enough not to be regarded as implementation-specific, then adding them to the interface 'makes sense'.

Should I make constants static final if they are defined in an interface? Which constants should I prefer, int or String?

As mentioned in @VoiceOfUnreason's answer, sometimes you should consider enums instead of 'plain' int and String values. Enums are usually more expressive and thus a better fit for enumerated values. Constants should always be declared as static final to communicate the intent that they are unmodifiable, and that they can be used without class instantiation.

Can I make some additional actions in setters?

The idea here is to be consistent. If your setEmployer() method calls signRenumerationPackage() and the optional (I hope) burnBridges() methods, then you have to make sure modifying the employer reference always goes through the setEmployer() setter. As long as you have consistency in place, having additional actions in setters are OK and sometimes even encouraged.

When should I write a JavaDoc?

As early as possible. :)

Making a better Engineer


Is there any way to mock and test Salesforce Streaming?

Question: Is there any way to mock and test Salesforce Streaming?
How do you test Salesforce Streaming API ?
Comment: Be a bit more explicit here - what/who are the subscribers/consumers of the stream?
Answer: Yes. It is possible.
<code> @isTest static void testPlatformEvent() {
        SomeEvent__e event = new SomeEvent__e(SomeField='test');

        Test.startTest();
        Database.SaveResult sr = EventBus.publish(event);
        Test.stopTest();

        System.assertEquals(true, sr.isSuccess());
</code>
For more information read Salesforce guide
Comment: this testmethod, while correct, actually tests nothing of interest. By definition, `EventBus.publish(event)` will always work in the test context provided you are not publishing more than 500 events. Consumption of the event is what one would test in a testmethod and that requires the org to have a subscriber (trigger/PB/flow) that leaves some persistence behind to asset against


How should we interpret the ending of "Palm Springs"?

Question: The wonderful (and well-received) 2020 Hulu movie Palm Springs ends on an ambiguous note, especially when you consider the mid-credits scene that follows.
So how should it be interpreted?
Answer: Josh Rottenberg sums it up well in this Los Angeles Times article on the movie:

So what does it all mean? Have Sarah and Nyles broken free from the time loop to live happily ever after? Or have they jumped into a different dimension in which they ultimately might end up stuck in the kind of dead-end marriage that they both fear?
Are they dead and eternally chilling in some kind of poolside afterlife? Or are there now two different Sarahs and Nyleses in two parallel timelines? And what is up with those dinosaurs?

He decided to ask the movie's makers:

If you were hoping for a single definitive answer from the film's creative team, you're out of luck. The ending was deliberately designed so that it could be viewed in different ways. How you read it will depend on personal beliefs about not just things like string theory and the possibility of alternate universes but the existence of true love itself.
"The intention was always to create an ending that was open to interpretation, where you could arrive at different conclusions about what had happened depending on how you were looking at the world, whether that was in a more optimistic or a more cynical light," director Max Barbakow says. "I think we all think different things happen after we pull away from that pool. That's the fun of it. Whatever you wanted to get out of an ending, you can get out of it."

Except that originally its ending was more explicit:

In early versions of the script, screenwriter Andy Siara says, "it was a little more clear what maybe the main interpretation could be." But after Samberg came on board, he and his Lonely Island producing partners, Akiva Schaffer and Jorma Taccone, helped push the film's conclusion in a more ambiguous direction.

Which apparently was something of a trial and error process:

"We definitely talked about the ending a lot," Samberg says. "There were many iterations written and even many iterations shot and cut together and screened for small friends-and-family screenings."

And this ambiguous ending has a purpose:

The goal all along was to land somewhere in the space between a traditional sort of pro-love-and-marriage rom-com happy ending and a slightly darker, more open-ended one that reflects the uncertainty of any romantic venture. "It was a real push-and-pull," Samberg says. "We didn't want the ending to feel saccharine, like, 'Yay, everything works out!' That felt untrue to the tone of the movie and the promise you had made with the characters. But at the same time you don't want to end on a note that's bitter and depressing. It was a delicate balance."
Answer: The way I'd see it considering what we were shown in the film is that the final scene is not set in the day of the loop, 9th Nov. They have chilled in that pool many times and on the 9th Nov, that family is not home. The final scene shows that they have returned. Which means it's the following day, showing us that Nyles and Sarah have broken out of the loop. The two of them also retain the cumulative memories from all their loops.
About Roy. He's still on the 9th Nov loop. He meets Nyles. This Nyles is no longer looping. That means the cumulative memories have progressed to the 10th along with the Nyles who is now free. The Nyles that we see in Roy's loop has not lived that day yet. He's meeting Roy for the first time and hence doesn't recognize him. This is proof for Roy that the "exit strategy" that Sarah leaves as a message to him on the phone has worked. He smiles because he too can escape.
Finally, the dinosaurs. I feel they are metaphorical. They are shown hazily. Think about Sarah's and Nyles' perspective. They have lived years in the loop. She learned Quantum Physics via distance learning, which must have taken ages. Nyles has been looping for decades before Sarah. Their own actual lives are going to be such a distant, hazy memory that feels like mere imagination, just like the vision of the dinosaurs in the end.


Older Shimano Ultegra Shifter compatibility

Question: I have an older Shimano Ultegra Shifter that broke, and I am wondering how I can know what shifters are compatible with the gear set as a replacement? My broken shifter is on the right side and is a Shimano Ultegra ST-6510 9-speed. Are current generation Shimano 9-speeds backwards compatible with my older gear set? I've looked at this Sora shifter as a possible replacement. I am not so concerned about weight or performance and am only hoping to get a couple more years out of my older bike.
Comment: I'd replace both shifters to avoid asymmetries in body position.
Comment: @Michael Interesting, I hadn't considered that. I wonder how different it will be and if I'll notice? I'm starting with just replacing the broken shifter, but I guess I'll see where I go from there. Thank you for pointing this out to me, I wouldn't have considered it.
Comment: Did it work? Got a vintage Trek with 7700 Dura Ace and want to put on R3000 shifters so i can run internal cabling.
Comment: @GuyLongbottom A little late, but yes, it did work. I replaced my shifter with the sora I linked and it all worked fine for the most part.
Answer: Any Shimano compatible 9 speed road shifter like the Sora you linked will work. While it will be visually different it will perform the same function. The last of these models were produced in 2007. While the Sora shifters you are looking at may be lower on the hierarchy list, they are likely equal to or better than your nearly the 20 year old technology you currently have. As new improvements are introduced Shimano eliminates the oldest technology and everything moves down a tier. Latest version of Ultegra is the previous version of Dura-Ace and it all moves down the line. My guess is you will be satisfied with a new Sora shifter.
Comment: Thank you for this, it gives me all the information I need. I've gone ahead and ordered a Sora shifter and am excited to hear the newer Sora shifter will be similar or perhaps superior to my old shifter.


(Co-) Homology of free nilpotent Lie Algebras

Question: What is actually known about the (co-) homology of free nilpotent Lie Algebras over $\mathbb{C}$ and coefficients also in $\mathbb{C}$?
I.e. the nilpotent Lie Algebras that one gets by a quotient of a free Lie algebra by some part of its descending central series.
Answer: There are several results on the homology of free-nilpotent Lie algebras with trivial coefficients, in particular for free two-step nilpotent Lie algebras.
Stefan Sigg has determined the homology in this case by working
out the structure of the homology as a module under the general linear group. The main tool is a Laplacian for the free two-step nilpotent Lie algebras, which turns out to be closely related to the Casimir operator of the general linear group. In addition, Grassberger, King, Tirao give
an explicit formula for the total dimension of the homology of a free 2-step
nilpotent Lie algebra.