text:
Q: How in depth should javadoc explanations of how algorithms work be? How in depth should I describe how an algorithm works?
For example, I'm working on a simple tetris game, and I want to explain how I rotate the tetrominoes in a way that the explanation doesn't cover a 100 lines, but the reader fully understands what I'm doing.
My javadoc for the algorithm as it is now:
/**
 * Rotates the tetromino 90 degrees clockwise.
 *

 * The rotating algorithm guarantees O(n^2) time complexity and O(1) space
 * complexity, n being the width/height of the tetromino's layout.
 *

 * The algorithm works by rotating each layer of the layout. A layer is
 * rotated by choosing 4 elements, one from each of the layout's sides, and
 * swapping them with each other in a clockwise manner. See an illustration
 * with the I-tetromino below:
 *

 *

 * Layout:
 *
 *     . . 1 .
 *     . . 1 .
 *     . . 1 .
 *     . . 1 .
 *
 * Its first and second layer (layers 0 and 1):
 *
 *   0:  x x x x   1:  . . . .
 *       x . . x       . x x .
 *       x . . x       . x x .
 *       x x x x       . . . .
 *
 * First we swap the first layer's elements, 4 at a time:
 *
 *   layout now:    swap these elements:
 *
 *   . . 1 .        x . 1 x
 *   . . 1 .        . . 1 .
 *   . . 1 .        . . 1 .
 *   . . 1 .        x . 1 x
 *
 *   layout now:    swap these elements:
 *
 *   . . 1 .        . x 1 .
 *   . . 1 .        . . 1 x
 *   . . 1 .        x . 1 .
 *   . . 1 .        . . x .
 *
 *   layout now:    swap these elements:
 *
 *   . . 1 .        . . x .
 *   . . 1 .        x . 1 .
 *   1 . 1 .        . . 1 x
 *   . . . .        . x . .
 *
 * Then we swap the second layer's elements:
 *
 *   layout now:    swap these elements:
 *
 *   . . . .        . . . .
 *   . . 1 .        . x x .
 *   1 . 1 1        1 x x 1
 *   . . . .        . . . .
 *
 *   layout now:
 *
 *   . . . .
 *   . . . .
 *   1 1 1 1
 *   . . . .
 *
 * The tetromino is now rotated.
 *

 */

Should I simply omit the step-by-step illustration, prefering the readability of the rest of the class, should I ignore this issue, prefering the reader, or should I give a link to an external source where a similar algorithm is already explained in depth, possibly resulting in a dead link later? Or something else?

A: I suggest limiting the javadoc to what a method does, rather than how it does it. This saves you from updating your JavaDocs every time you change your code. In your case, I'd be happy with writing:
/**
 * Rotates the tetromino 90 degrees clockwise.
 *

 * The rotating algorithm guarantees O(n^2) time complexity and O(1) space
 * complexity, n being the width/height of the tetromino's layout.
 *

 * @param, @return, @throws etc goes here.
 */

You'll have to update your JavaDocs if you improve your algorithm of course - but I'd leave it in as the complexity is something another reader (or future you) would like to know.
For the purpose of making it easy for a reviewer to understand your code I would suggest explaining the more difficult bits of the algorithm in the actual method, rather than as a javadoc. There are (at least) three good reasons for this:

*

*Distance from actual code to comment is shorter, and you can spread the comments out more.

*JavaDocs are often used by IDEs to get a quick overview of what a method/class does, putting the whole explanation of the code in the JavaDoc defeats this purpose.

*Perhaps not applicable in your situation, but perhaps good to keep in mind, is that JavaDocs are often published when publishing something like an API. You need not publish the source code, but the JavaDocs are almost always included, and often published on the web as well. If you have an algorithm in your code that does something amazing, that you want to keep secret for business purposes, it would really defeat the purpose of explaining the algorithm in the JavaDoc. ;-)


text:
Q: 'canAuthenticate()' is deprecated in android What should I use instead of biometricManager.canAuthenticate() is deprecated.
Doc says

This method is deprecated.
Use canAuthenticate(int) instead.

    BiometricManager biometricManager = BiometricManager.from(this);
    switch (biometricManager.canAuthenticate()){
        case BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE:
            break;
        case BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE:
            break;
        case BiometricManager.BIOMETRIC_SUCCESS:
            break;
        case BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED:
            break;
        case BiometricManager.BIOMETRIC_ERROR_UNSUPPORTED:
            break;
    }

How to use canAuthenticate(int) like the above manner.

A: The direct replacement for your code would look something like:
switch (canAuthenticate(Authenticators.BIOMETRIC_WEAK)) {
   case ...
}

According to the javadoc, the possible return values are BIOMETRIC_SUCCESS, BIOMETRIC_ERROR_HW_UNAVAILABLE, BIOMETRIC_ERROR_NONE_ENROLLED, BIOMETRIC_ERROR_NO_HARDWARE, or BIOMETRIC_ERROR_SECURITY_UPDATE_REQUIRED., as before.

A: The default implementation on canAuthenticate() is deprecated as it supported only Authenticators.BIOMETRIC_WEAK
With the following new implementation :
BiometricManager.from(context).canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_WEAK)

Following authentication mechanisms are supported :
public interface Authenticators {
        /**
         * Any biometric (e.g. fingerprint, iris, or face) on the device that meets or exceeds the
         * requirements for Class 3 (formerly Strong), as defined
         * by the Android CDD.
         */
        int BIOMETRIC_STRONG = 0x000F;

        /**
         * Any biometric (e.g. fingerprint, iris, or face) on the device that meets or exceeds the
         * requirements for Class 2 (formerly Weak), as defined by
         * the Android CDD.
         *
         *
Note that this is a superset of {@link #BIOMETRIC_STRONG} and is defined such that
         * {@code BIOMETRIC_STRONG | BIOMETRIC_WEAK == BIOMETRIC_WEAK}.
         */
        int BIOMETRIC_WEAK = 0x00FF;

        /**
         * The non-biometric credential used to secure the device (i.e. PIN, pattern, or password).
         * This should typically only be used in combination with a biometric auth type, such as
         * {@link #BIOMETRIC_WEAK}.
         */
        int DEVICE_CREDENTIAL = 1 << 15;
    }

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there a way to sort 2 dataframes side by side in python and move those that are not in both to the bottom I am using python to automate some of the day to day in my work. I am looking for some assistance on how I might go about sorting 2 dataframes side by side and moving those values that are not in both to the bottom of the dataframe in which is originated.
For example in the two dataframes below once it gets to WWT0117 (left hand df) there is a small residual amount of 0.03. WWT0117 is not in the dataframe on the right so I want to move this WWT0117 and the corresponding 0.03 value to the bottom of the dataframe.
The below is a view of the two dataframes side by side and the highlighted is where is goes a skew. The dataframes are a lot bigger and is tedious to go through line by line.

A: If this answer doesn't correspond to what you wanted, please clarify what you want. As it stands, there is some room for interpretation of your question.
First method: join by names
df1 = pd.DataFrame({'name1':['WWT0034', 'WWT0039', 'WWT0117', 'WWT0119'], 'v1':[-80832.72, 3949.78,0.03,-0.05]})
df2 = pd.DataFrame({'name2':['WWT0034', 'WWT0039', 'WWT0140', 'WWT0180'], 'v2':[80832.72, -3949.78,344.46,83464.11]})
# df1                      df2
#      name1        v1          name2        v2
# 0  WWT0034 -80832.72     0  WWT0034  80832.72
# 1  WWT0039   3949.78     1  WWT0039  -3949.78
# 2  WWT0117      0.03     2  WWT0140    344.46
# 3  WWT0119     -0.05     3  WWT0180  83464.11

df = df1.set_index('name1').join(df2.set_index('name2'), how='outer')
# df
#                v1        v2
# WWT0034 -80832.72  80832.72
# WWT0039   3949.78  -3949.78
# WWT0117      0.03       NaN
# WWT0119     -0.05       NaN
# WWT0140       NaN    344.46
# WWT0180       NaN  83464.11

(df['v1'] + df['v2']) == 0
# WWT0034     True
# WWT0039     True
# WWT0117    False
# WWT0119    False
# WWT0140    False
# WWT0180    False

df[(df['v1'] + df['v2']) == 0]
#                v1        v2
# WWT0034 -80832.72  80832.72
# WWT0039   3949.78  -3949.78

Second method: join by row number after sorting
Or alternatively:
>>> df = df1.sort_values(by='name1').reset_index(drop=True).join(df2.sort_values(by='name2').reset_index(drop=True))

>>> df
     name1        v1    name2        v2
0  WWT0034 -80832.72  WWT0034  80832.72
1  WWT0039   3949.78  WWT0039  -3949.78
2  WWT0117      0.03  WWT0140    344.46
3  WWT0119     -0.05  WWT0180  83464.11

>>> df[(df['v1'] + df['v2']) == 0]
     name1        v1    name2        v2
0  WWT0034 -80832.72  WWT0034  80832.72
1  WWT0039   3949.78  WWT0039  -3949.78

>>> df[(df['v1'] + df['v2']) != 0]
     name1    v1    name2        v2
2  WWT0117  0.03  WWT0140    344.46
3  WWT0119 -0.05  WWT0180  83464.11

Difference between the two methods
Note that those two methods are not equivalent. The first method joins the two dataframes based on the 'name1' and 'name2' columns; the second method ignores the names and joins them based on the row numbers after sorting.
Here is an example of two dataframes that would give different results with the two different methods:
df1 = pd.DataFrame({'name1':['WWT0034', 'WWT0039', 'WWT0117', 'WWT0119', 'WWT0120'], 'v1':[-80832.72, 3949.78,0.03,-0.05, 42]})
df2 = pd.DataFrame({'name2':['WWT0034', 'WWT0039', 'WWT0118', 'WWT0120', 'WWT0180'], 'v2':[80832.72, -3949.78,344.46,-42, 83464.11]})
# df1                      df2
#      name1        v1          name2        v2
# 0  WWT0034 -80832.72     0  WWT0034  80832.72
# 1  WWT0039   3949.78     1  WWT0039  -3949.78
# 2  WWT0117      0.03     2  WWT0118    344.46
# 3  WWT0119     -0.05     3  WWT0120    -42.00
# 4  WWT0120     42.00     4  WWT0180  83464.11

The first method would join the two 'WWT0120' together, whereas the second method would keep them separate.


text:
Q: Limit of $a_n$ is $0$ iff Limit of $a_n \sin(n t)$ is $0$ for all $t\in[0,1]$ I'd like to prove\begin{align} \lim_{n\rightarrow\infty}a_n=0 \iff \lim_{n\rightarrow\infty}a_n\sin(n t)=0 \quad \forall t\in[0,1]\end{align}
Since $\sin$ is bounded one of the implications is trivial. For the other one letting $t=\frac{\pi}{4 l}, l\in\mathbb{N}$ implies $a_{n_k}\rightarrow 0$ for all subsequences satisfying $(n_k)_{k\in\mathbb{N}}\subset\mathbb{N}\setminus 4 l \mathbb{N}$. Does this lead anywhere?

A: Suppose $\limsup_{n \to \infty} \left| a_n\right| > \epsilon > 0$, i.e. there are infinitely many $n$ with $|a_n| > \epsilon$.
Let $T_n = \{t \in [0,1]: |a_k \sin(kt)| > \epsilon \text{ for some } k > n\}$.
For any $k \ge 4$ there is $t \in [0,1]$ with $\sin(kt)=1$, so all $T_n$ are nonempty.
Now if $|a_k \sin(kt)| > \epsilon$, so is $|a_k \sin(k(t+j\pi/k)|$ for any integer $j$.   Any nonempty interval $(a,b) \subset [0,1]$ contains some $t+j\pi/k$ if $k$ is sufficiently large, i.e. $T_n$ is dense in $[0,1]$.  Moreover, $T_n$ is easily seen to be an open set.  The Baire Category Theorem then shows
that $\bigcap_n T_n$ is nonempty.  But if $t \in \bigcap_n T_n$,
it means $|a_k \sin(kt)| > \epsilon$ for infinitely many $k$, so $\lim_{n \to \infty} a_n \sin(nt) \ne 0$ for this $t$.

A: Proving by contrapositive: Suppose that $\operatorname{lim}a_n \neq 0.$ Then, letting $t=\pi/4$ we find that the sequence $(a_n\operatorname{sin}(nt))$ cannot converge to $0$, since the $\operatorname{sin}(nt)$ terms forever cycle through $\pm\frac{1}{\sqrt{2}},\pm1,0.$ Thus, $\exists t\in [0,1]$ such that $\operatorname{lim}(a_n\operatorname{sin}(nt))\neq0,$ which is the negation of the condition on the right hand side.

A: Suppose $(a_n)$ is such that for all $t\in I=[0,1],~\lim~a_n\sin(nt)$ exists and $=0$.
You are in effect saying that the sequence of functions $f_n:I\rightarrow \mathbb R, t\mapsto a_n\sin(nt)$ converges simply (direct translation from french, maybe "pointwise" in english) to the $0$ funtion. What you want to show is that this implies uniform convergence of the sequence $(f_n)$ to the zero function (since for $n\geq2>\pi/2,~\|f_n\|_{\infty}=|a_n|$.)
Suppose $(a_n)$ doesn't tend to $0$. Then there is a positive real number $\epsilon>0$ and a strictly increasing sequence of positive integers $\varphi(n)\uparrow +\infty$ such that $|a_{\varphi(n)}|>\epsilon$ for all $n$. Without loss of generality, we may assume that for all $n,~\varphi(n+1)\geq 100\varphi(n)$ and $\varphi(0)>100\pi$ ($100$ isn't special, it is just large enough for our purpose.)
For $x\in \mathbb R$ and $r>0$, we call $[x-r,x+r]$ the segment centered at $x$ and of length $2\times r$. We construct a sequence of nested closed intervals $(I_n)$ centered around maxima of $|f_{\varphi(n)}|$ and of length $2\times\frac{\pi}{3\varphi(n)}$.
The first one is defined to be $I_0\subset [0,1]$ centered around one of the maxima of $|f_{\varphi(0)}|$ of the form $\frac{\pi/2+k\pi}{\varphi(0)}$ and of length $2\times\frac{\pi}{3\varphi(0)}$. Since $\varphi(0)$ is quite large, $f_{\varphi(0)}$ has plenty of time to complete many of full oscillations, so there is room enough to fit $I_0$ into $I$.
Suppose the $n^{th}$ such nested interval $I_n$ has been constructed. Because $\varphi(n+1)\geq 100\varphi(n)$, the $\varphi(n+1)^{th}$ function has time to do several full oscillations inside $I_n$, and we just pick one point in $x_{n+1}\in I_n$ that realizes a maxima for $|f_{\varphi(n+1)}|$, is of the form $\frac{\pi/2+k\pi}{\varphi(n+1)}$, and is close enough to the center of $I_n$ so that the segment centered at this maxima and or length $2\times\frac{\pi}{3\varphi(n+1)}$ is completely contained in $I_n$.
Saying that the maxima of $|f_{\varphi(n)}|$ we choose are of this particular form is not necessary, since by hopothesis the $a_{\varphi(n)}$ are non zero, and so the maxima of $|f_{\varphi(n)}|$ are those of $|\sin(~\cdot\times\varphi(n))|$. I include this extra information only to facilitate the verification of a calculation further down which relies upon the fact that $|\sin(x)|\geq 1/2$ on $[\pi/2-\pi/3,\pi/2+\pi/3]$.
We thus get a nested sequence of closed intervals whose length tend quickly to $0$, and by compactness there exists $t\in I$ with
$$\bigcap_{n\in\mathbb N}I_n=\lbrace t\rbrace.$$
Our choice of $I_n$ (the fact that it is centered around a maxima of $|f_{\varphi(n)}|$ and of length $2\times\frac{\pi}{3\varphi(n)}$ ensures that for all $s\in I_n,~|\sin(\varphi(n)s)|\geq 1/2$. Since for all $n$ we have $t\in I_n$, we have for all $n$ that $|f_{\varphi(n)}(t)|\geq |a_n|/2>\epsilon/2$ which contradicts the assumption that $|f_n(t)|$ must tend to $0$.

A: If the $a_n \sin(nt)$ converge pointwise to 0, so do $|a_n| |\sin(nt)|$. It's a fact from measure theory (Egorov's Theorem) that if a sequence of measurable functions converge pointwise on $[0,1]$ to any function $f(t)$ then they converge almost uniformly to $f(t)$, meaning that for any $\epsilon > 0$ one can remove a set $A_{\epsilon}$ of measure $< \epsilon$ and the functions will converge uniformly to $f(t)$ on $[0,1] - A_{\epsilon}$.
In this case $f(t)$ is just zero, so off of $A_{\epsilon}$ the functions $|a_n| |\sin(nt)|$ converge uniformly to zero. But these functions are bigger than ${1 \over 2}|a_n|$ on most of $[0,1]$. Show if you choose $\epsilon$ small enough, you get that $|a_n| \rightarrow 0$.


text:
Q: Magento 2 - \Magento\Sales\Model\Order trying to fetch items in an order is not working I am trying to get items of an order and display it in phtml file. But not getting the result.
Below provided is the code which I have provided in block
protected $_order;

public function __construct(
    \Magento\Framework\View\Element\Template\Context $context,
    \Magento\Customer\Model\Session $session,
    \Cubet\RMA\Model\ListReturnsFactory $db,
    \Magento\Sales\Model\ResourceModel\Order\CollectionFactory $orderCollectionFactory,
    \Magento\Sales\Model\Order $order
) {
    parent::__construct($context);
    $this->_session = $session;
    $this->_logger = $context->getLogger();
    $this->_db = $db;
    $this->_orderCollectionFactory = $orderCollectionFactory;
    $this->_order = $order;
}
 public function getOrderItems()
  {
    $orderItems = $this->_order->create()->loadByIncrementId(000000003);
    $orderItems->getAllItems();
    return $orderItems;
 }

and the code provided in phtml is
$items = $block->getOrderItems();
print_r($items);

but it doesn't print any result. Please help on the same.

A: You can try with orderInterface and get items of order,
public function __construct(
    \Magento\Framework\View\Element\Template\Context $context,
    \Magento\Sales\Api\Data\OrderInterface $order,
    array $data = []
) {
    parent::__construct($context, $data);
    $this->order = $order;
}
public function getOrderItems(){
    $order = $this->order->loadByIncrementId(000000003);

    $items = $order->getAllItems();
    $product = array();
    foreach($items as $item){
        $product[] = $item->getName().'||'.$item->getQtyordered();
    }
    return $product;
}

in template file,
$items = $block->getOrderItems();
foreach($items as $item){
    print_r($item);
}

A: Try below Code to call in template
protected $_orderCollectionFactory;
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Customer\Model\Session $session,
        \Cubet\RMA\Model\ListReturnsFactory $db,
       \Magento\Sales\Model\ResourceModel\Order\CollectionFactory $orderCollectionFactory,
        \Magento\Sales\Model\Order $order
    ) {
        parent::__construct($context);
        $this->_session = $session;
        $this->_logger = $context->getLogger();
        $this->_db = $db;
        $this->_orderCollectionFactory = $orderCollectionFactory;
    }
     public function getOrders() {
            $this->orders = $this->_orderCollectionFactory->create()->addFieldToSelect('*');
            return $this->orders;
     }


text:
Q: Ant exec executable="cmd" with '-' issue So I am trying to execute some git commands in the old  tag of ANT.
<exec executable="cmd" failonerror="true" dir = "D:\Test">
    <arg value="/c"/>
    <arg value="git remote -v"/>
</exec>

But I get this error:
 [exec] error: unknown switch ` '
 [exec] usage: git remote [-v | --verbose]
If I execute any other commant that is not having '-' in it it works fine.

A: Put each argument of the git command in its own <arg> element:
<exec executable="cmd" failonerror="true" dir="D:\Test">
    <arg value="/c"/>
    <arg value="git"/>
    <arg value="remote"/>
    <arg value="-v"/>
</exec>


text:
Q: Plot candlesticks using matplotlib as weel as datas from pandas DataFrame I've been trying to plot candlesticks from a pandas DataFrame containing ohlc data (in m5 timeframe), as well as data from another pandas array (in s1 timeframe), but I didn't manage to make it work.
My data looks like this:
In [83]: df[:3]
Out[83]:
                        open     high      low    close
DateTime
2015-01-04 22:00:00  1.19548  1.19551  1.18627  1.19257
2015-01-04 22:05:00  1.19257  1.19455  1.18976  1.19116
2015-01-04 22:10:00  1.19115  1.19404  1.19068  1.19353

In [84]: sec[:5]
Out[84]:
                        open     high      low    close
DateTime
2015-01-04 22:00:00  1.19548  1.19551  1.19525  1.19551
2015-01-04 22:00:01  1.19535  1.19535  1.19479  1.19482
2015-01-04 22:00:02  1.19483  1.19496  1.19474  1.19485
2015-01-04 22:00:03  1.19487  1.19490  1.19487  1.19490
2015-01-04 22:00:04  1.19453  1.19453  1.19388  1.19397

Both my DataFrames' indexes are Datatime index, and both are holding ohlc data.
When I try to plot data from both DataFrame on the same graph, it works perfectly well:
fig,ax1 = plt.subplots()

ax1.plot(sec['open'],linewidth=2)
ax1.plot(df['close'],'ko')

But after I plot the candlesticks, I can't find a way to change the x-axis so that I can plot the above data on the same figure:
fig,ax1 = plt.subplots()

candlestick2_ohlc(ax1,opens=df["open"].values,highs=df["high"].values,lows=df["low"].values,closes=df["close"].values,width=.4,colorup='g')

I can't find a way to plot both on the same figure, I looked a bit on how to tweak the x-axis after I plot the candlesticks, but I think that I have a bad understanding of how matplotlib axis work, and of why I can plot data from pandas array with different TimeSeries on the same graph.
Would anyone have an idea on how to make it work?
Edit:
I didn't notice I was using the wrong function (candlestick_ohlc instead of candlestick2_ohlc), which explained why I didn't manage to make work the documentation I looked about my issue.
I tried to do the same as I found here: Overlapping Dates in Candlestick Plot from a Pandas DataFrame
fig,ax1 = plt.subplots()

ax1.xaxis_date()

ohlc = [df.index.map(mdates.date2num),df["open"].values,df['high'].values,df['low'].values,df['close'].values]

candlestick_ohlc(ax1,ohlc,width=.4,colorup='g')

Which doesn't work and yields the error ValueError: ordinal must be >= 1
I also tried something similar that I found here: candlestick plot from pandas dataframe, replace index by dates
fig,ax1 = plt.subplots()

ax1.xaxis_date()
ax1.xaxis.set_major_formatter(mdates.DateFormatter('%d-%m-%Y'))

ohlc = [mdates.date2num(df.index.astype(datetime.date)),df["open"].values,df['high'].values,df['low'].values,df['close'].values]

candlestick_ohlc(ax1,ohlc,width=.4,colorup='g')

Which yields another error message:
TypeError: dtype <class 'datetime.date'> not understood

I'm clearly doing something wrong, but I seriously can't figure out what.
I looked at the documentation about the candlestick_ohlc function of matplotlib.finance, and they say that:

time must be in float days format - see date2num

I assume my issue is that I didn't do the conversion properly, would anyone know what part of what I did is wrong, and why it doesn't yield the correct result?


text:
Q: How PageView is counted in Facebook Pixel? I measure standard and custom Facebook events on my website. One of the very important event is PageView. My site is a React site, so I included: react-facebook-pixel
and this is how I measure:
ReactPixel.pageView();

If I turn off this line ReactPixel.pageView(), I still can see values at PageView. How is it possible? Does PageView statistics shows only event when ReactPixel.pageView(); is called, or it takes into account other things as well?

A: Facebook Pixel implicit PageView
is it helpful? As it states: "I find that as soon as I init my pixel fbq('init', '1234567890');, a PageView event is being sent implicitly."
edit: fbq is also implemented in react-facebook-pixel regardless what I posted is an angular example.


text:
Q: Receiving error when using UtilityBarAPI in Winter '18 I'm trying to set a custom icon in a Utility Bar component using the new Utility Bar Component in Lightning.
TestComponent.cmp
<aura:component implements="flexipage:availableForAllPageTypes" access="global" >
    <force:utilityBarAPI aura:id="utilitybar" />
    <lightning:button label="Set Panel Header Icon" onclick="{! c.customizeUtilityPanel }" />
</aura:component>

TestComponentController.js
({
    customizeUtilityPanel : function(component, event, helper) {
        var utilityAPI = component.find("utilitybar");
        utilityAPI.getAllUtilityInfo().then(function(response) {
            var myUtilityInfo = response[0];

            utilityAPI.setPanelHeaderIcon({utilityId: myUtilityInfo.id, sldsKey: "clock"});
            utilityAPI.setUtilityIcon({utilityId: myUtilityInfo.id, sldsKey: "frozen"});

            utilityAPI.openUtility({utilityId: myUtilityInfo.id});
        });
    }
})

But I'm receiving following error in browser console:

aura_prod.js:922 null "Error: Invalid or missing icon undefined"
  (anonymous) @ aura_prod.js:922 aura_prod.js:849 Uncaught (in promise)
  Error: Invalid or missing icon undefined b @ aura_prod.js:849 Async
  Call d @ internal.js:1 b @ aura_prod.js:849 d.then @ internal.js:1

I'm using following Console Developer Guide and the new force:utilityBarAPI component introduced in Winter '18.
Does anyone have any idea why I'm unable to use the method to set an Icon in Utility bar component?

A: I got it to work, but honestly it was more of a trial and error method. I suspect we are running into a documentation bug of some kind. The documentation states setUtilityIcon({sldsKey, utilityId}) , but the error seems to indicate a key "icon" was missing. So i modified the code as follows and UtilityApi started to work as expected. Check the before and after images for the working scenario.

Controller:

    var utilityAPI = component.find("utilitybar");
    utilityAPI.getEnclosingUtilityId().then(function(response) {
        utilityAPI.setUtilityLabel({label : "Hello World", utilityId : response});
        utilityAPI.setUtilityIcon({icon : "insert_tag_field", utilityId : response });
    });

Before SetUtilityIcon()

After SetUtilityIcon()

We will be able to notice that the icon and label changed to "insert tag field" & "Hello World" respectively . And i guess callback is optional.


text:
Q: Picking two balls from 6 balls There are 30 balls in a bag. There are 6 balls each of 5 different colors. What is the minimum number of times I have to pick a ball to pick 2 balls of each color?

*

*24

*25

*26

*27

*28

Is the question correct? Someone asks me this and I'm confused.

A: What we're counting is the minimum number of balls we could blindly pick yet be entirely sure we have two of each color. For example, liken it to picking socks blindly from a drawer -- we want to determine how many socks we have to pull out blindly to ensure we have a pair.
Think of the worst case scenario, where you go through all 6 of the first 4 colors before you get a ball of the last color. This means you would need to pick $4\times6$ balls before getting to your last color and to pick 2 of the last color we end with $4\times6+2=26$ balls.

A: If we want to have certainty of picking at least two balls of each colour. The worst case is if we have picked up all the balls of every colour but yellow, and only one yellow. So $25$ is not enough.
But $26$ is enough. For if we pick $26$, there are only $4$ balls left, so we have at least $2$ balls of each colour.
Remark: If on the other hand we consider the simpler problem of what is the least number of times we need to do the picking, if we are very lucky, then the answer is $10$, since with some luck when we pick $10$ balls we will have $2$ of each colour.
There is some (well, more than some) ambiguity in the question. The choices provided indicate that the problem-poser did not intend the question to be interpreted in the "if we get lucky" sense.


text:
Q: How can I set the prompt for remote MySQL clients? I'd like to customize my MySQL command-line prompt for any remote clients connecting to a particular server. Something like LIVE SERVER DON'T DO ANYTHING STUPID>.
I know I can set an option in the various my.cnf files for a MySQL client so that the prompt is customized, but I believe that would have to be done on any client that might want to connect. The "server" doesn't seem to support that option. I'd prefer that every client that connects get that prompt.
Is that kind of thing possible? If so, how?


text:
Q: Parallel Boolean Expression Evaluation in Java
Possible Duplicate:
When Java evaluates a conjunction (<boolean exp1> && <boolean exp2>), does it eval exp2 if exp1 is false?

If I have 2 condition say, A and B and I type:
A && B

Are they both evaluated in parallel and only then it does AND?
For example, if I type A && false will it evaluate the A condition or it knows it will be false anyway?
And if it's not done in parallel, does it start from the right or left?
(A && false VS false && A).
Thanks.
EDIT: Got it. Thanks to all!

A: A && B

no,
A is first evaluated and if A is false it skips evaluating B
if A is true then it checks if B is true
A && false

in this case, A is evaluated first and if A is false, it doesnt check the next condition(false). If A is true then false will be evaluated but as it is false the whole condition would be false.

A: It will start from left to right. That is if there are no parentheses involved.
if("name".equals(variable1)){}

is will get an error when var1 is null. However, when you use:
if(variable1.equals("name")){}

it is null safe.


text:
Q: ReactJS -Throw Submission Error with axios response I am having understanding problem to make my code work properly. Basically I want to validate a data from server, which on validation doesn't throw error but give proper response where I need to handle the response and throw Submission Error to show validation error with redux-form.
Following is my code..
onFormSubmit = (values) =>{
    this.setState({loading:true});
    this.props.validateEmailFromServer(this.props.session,values,(response)=>{
      if(response.success === 2){
        throw new SubmissionError({email:'Email already Taken', _error:'Failed'});
      }
    });
}

Action is defined as follows
export function validateEmailFromServer(session,values,callback){

  var url='API_URL';
  var response = axios.get(url, null,
                           getHeaders(session));
  return (dispatch) => {
    response.then(({data}) => {
      if(data.resource.length>0){
        callback({success: 2,message:'Email id is not available!'});
      }else{
        callback({success: 1,message:'Email is available!'});
      }
    }).catch((error) => {
      callback({success: 0, message: error});
    });
  }
}

The problem I am facing is when I am throwing the Submission Error when callback is called on onFormSubmit function it is calling the error block of axios automatically, I am not able to get out of it..
I need help to solve this problem.
Thanks.

A: Thanks all for your pointers, I managed to get the solution, I changed the action and directly calling the axios in onFormSubmit function as follows, it works..
onFormSubmit = (values) =>{
    var getUrl = 'APIURL';
    return axios.get(getUrl,getHeaders(this.props.session))
            .then(function({data}) {
              if(data.resource.length>0)
                throw new Error("ValidationError");
              else{
                console.log("Proceed");
              }
            }).catch((err) =>{
                if(err.message === 'ValidationError')
                 throw new SubmissionError({email:'Email already Taken', _error:'Failed'});
            });
}

Hope this helps people who are trying to find similar solution.
Thanks for help.. Cheers.

A: Wrap your callback invocation in a regular try...catch, otherwise unhandled SubmissionError will naturally result in rejection of the whole response Promise.
export function validateEmailFromServer(session,values,callback){

  var url='API_URL';
  var response = axios.get(url, null,
                           getHeaders(session));
  return (dispatch) => {
    response.then(({data}) => {
      try {
        if(data.resource.length>0){
          callback({success: 2,message:'Email id is not available!'});
        }else{
          callback({success: 1,message:'Email is available!'});
        }
      } catch(ex) {
        // do something
      }
    }).catch((error) => {
      callback({success: 0, message: error});
    });
  }
}

A: When using promises, and you have a .catch block, it will not trigger additional .catch blocks in the chain unless you re-throw the error.
I suspect this may be the case here.

A: Instead of trowing an error when an email is already taken, handle it with something like notifyEmailTaken(). You are throwing and error so, it is getting caught by your catch statement (that is my guess).
Good luck!


text:
Q: Making a sub-query on query results? How do I unite these two?
This query:
SELECT f1.asked_user_id AS friend_id
    FROM friends AS f1 JOIN friends AS f2
    ON f1.asked_user_id = f2.asker_user_id
    AND f1.asker_user_id = f2.asked_user_id
    AND f1.asker_user_id = :user_id
WHERE f1.status = 1 AND f2.status = 1

With:
(SELECT GROUP_CONCAT(words_en.word) FROM connections JOIN words_en ON connections.word_id = words_en.id WHERE connections.user_id = friends.friend_id) As friend_words

And do yet another join:
JOIN users ON friends.friend_id = users.id

I've tried few things here: http://www.sqlfiddle.com/#!2/85d6d/36
First query selects two way friends from the table. I get friend_id from that query.
Now I want to know more about this friend_id.
So I want to use this id to do another query that would display all word_ids from connections table by that user, word_ids can be used to get actual words from words_en.
And lastly, I want to get users name_surname from users table.

A: Try this:
SELECT a.name_surname,GROUP_CONCAT(Distinct w.word Order by w.word asc) AS words
FROM (
  SELECT f1.asked_user_id AS friend_id,
       f1.created,
       u.name_surname,
       u.avatar
  FROM friends AS f1
  INNER JOIN friends AS f2 ON f1.asked_user_id = f2.asker_user_id
  INNER JOIN users AS u ON f1.asked_user_id = u.id
       AND f1.asker_user_id = f2.asked_user_id
       AND f1.asker_user_id = 1
  WHERE f1.status = 1 AND f2.status = 1
) a
LEFT JOIN connections c ON c.user_id = a.friend_id
LEFT JOIN words_en w ON c.word_id = w.id
GROUP BY 1;

sqlfiddle demo
Having your original query, what i did is treat that query as a table (a) and LEFT JOIN it with connections table. Then, LEFT JOIN the connections table with the words_en table to reach the desired words. This makes it possible to get all users that return from your original query, even when there are no connections/words.


text:
Q: Is there any keyboard shortcut to select/copy the auto highlighted text in VS Code? When I place my cursor at any position inside a text like the string in this photo, vs code automatically mildly highlights the entire string. Is there any shortcut key for selecting and copying this entire text highlighted by vs code?
Example: String being mildly highlighted by vs code How to select/copy this with a keyboard shortcut?
Update:
Added gif to show the highlighting - gif showing the highlighting

A: If in a string, triggering the command editor.action.smartSelect.grow a couple of times should select that entire string.  And then you can copy the normal way Ctrl+C.
That command is unbound by default.  You can assign a keybinding to it in the Keyboard Shortcuts editor by searching for smartSelect and click on the little pencil icon next to the command.

A: There's not a single, builtin keyboard shortcut for the behavior you described, but you can use a combination of two to achieve the result you want:
The first is called "Expand Selection" in the VS Code app, and the online keybindings documentation describes it as "Expand AST Selection" (editor.action.smartSelect.expand). The default platform keybindings for this are:

*

*linux: shift + alt + right

*mac: shift + ctrl + cmd + right

*win: shift + alt + right

If the highlighted string is one word, it will require one use, and if the string is multi-word, it will require two uses.
After that, the selection will be complete, and you can simply copy (cmd/ctrl + c).
Demo:


text:
Q: Conditional Operators(!=)(If-else Statement) Desired Output:
Data Type: int
Variable Name: a
Initial Value: 0
Conditional Operator: !=
Conditional Value: 5
Increment/Decrement: ++
Interval: 1
for(int a=0;a!=5;a+=1)
{
}
for(int a=1;a!=5;a+=1)
{
}
for(int a=2;a!=5;a+=1)
{
}
for(int a=3;a!=5;a+=1)
{
}
for(int a=4;a!=5;a+=1)
{
}

If you change the interval to 2, it should output "Infinite Loop! Try Again" and if you change the interval to 1, it should output the desired output stated above.
My program's output:
Data Type: int
Variable Name: a
Initial Value: 0
Conditional Operator: !=
Conditional Value: 5
Increment/Decrement: ++
Interval: 1
Infinite Loop! Try Again!

My code:
else if(inc_dec.equals("++") && conditionalOperator.equals("!="))
 {
   for(float c=initialValue;c!=conditionalValue;c+=interval)
     {
       if(initialValue == conditionalValue)
         System.out.print("for("+dataType+" "
         +varName+"="+c+";"+varName+conditionalOperator+conditionalValue+";"
         +varName+"+="+interval+"){\n}\n");
       else break;
     }
       System.out.println("Infinite Loop! Try Again!");
  }

P.S. The code should only use if-only statements

A: I fixed it!
else if(inc_dec.equals("++") && conditionalOperator.equals("!="))
                    {
                     for(float c=initialValue;c!=conditionalValue;c+=interval)
                     {
                      if(conditionalValue%interval == 0)
                         System.out.print("for("+dataType+" "+varName+"="+c+";"+varName+conditionalOperator+conditionalValue+";"+varName+"+="+interval+"){\n}\n");
                      else break;
                     }
                    }

A: Initial value of a = 0 and if you increment variable a value by 2 then the condition a!=5 will never be true.
Your a becomes 0,2,4,6,8...infinity (But it will never become 5). Hence you are going into infinite loop.


text:
Q: Update rows based on range around values without changing rows that are not initially within range In a local SQLite (vs 3.29.0) database, there is a table with 3 columns (excluding the rowID). Two contain values, and one contains categories. I want to update the category based on a range around the values of one specific category. It needs to be possible that the category that is SET is the same category as the one that determines the range.
Example:

id
Value
Value2
Category

1
20
20
2

2
30
30
2

3
40
40
2

4
70
70
2

5
5
5
1

6
19
19
1

7
26
26
1

8
42
42
1

9
49
49
1

10
52
52
1

11
71
71
1

12
90
90
1

13
17
17
1

I want rows to be changed to category 2, based on a range of 4 around value and a range of 2 around value2. This should change only rows 6, 9 and 11:

id
Value
Value2
Category

1
20
20
2

2
30
30
2

3
40
40
2

4
70
70
2

5
5
5
1

6
19
19
2

7
26
26
1

8
42
42
2

9
49
49
1

10
52
52
1

11
71
71
2

12
90
90
1

13
17
17
1

My current SQL statement is:
UPDATE tablename
SET Category = 2
WHERE (Category != 2
  AND EXISTS (
        SELECT *
        FROM tablename t
        WHERE t.Category = 2
          AND tablename.Value BETWEEN t.Value - 4 AND t.Value + 4
          AND tablename.Value2 BETWEEN t.Value2 -2 AND t.Value2 +2)
          );

of which the result is:

id
Value
Value2
Category

1
20
20
2

2
30
30
2

3
40
40
2

4
70
70
2

5
5
5
1

6
19
19
2

7
26
26
1

8
42
42
2

9
49
49
1

10
52
52
1

11
71
71
2

12
90
90
1

13
17
17
2

What appears to be happening is that due to row 6 changing to category 2, row 13 is now within range of the values of a row that is in category 2, and therefore is also assigned category 2. How do I change the statement so that the SET is only applied to the values that were within range initially?
See the demo for the example.

A: If your version of SQLite is 3.33.0+ you can use the join-like UPDATE...FROM syntax to perform a self join in the UPDATE statement:
UPDATE tablename AS t1
SET Category = t2.Category
FROM tablename AS t2
WHERE t2.Category = 2
  AND t1.Category <> t2.Category
  AND t1.Value BETWEEN t2.Value - 4 AND t2.Value + 4
  AND t1.Value2 BETWEEN t2.Value2 - 2 AND t2.Value2 + 2;

For previous versions of SQLite, first create a temporary table with all the rows of the table with Category = 2:
CREATE TEMPORARY TABLE t AS
SELECT * FROM tablename WHERE Category = 2;

and then update the table:
UPDATE tablename
SET Category = 2
WHERE Category <> 2
  AND EXISTS (
        SELECT 1
        FROM t
        WHERE tablename.Value BETWEEN t.Value - 4 AND t.Value + 4
          AND tablename.Value2 BETWEEN t.Value2 -2 AND t.Value2 + 2
      );

See the demo.


text:
Q: How to export function with hoc?  function UpdateID(index, id) {
    let CardsData = Cards

    var CardsObj = {
        link: Cards[index].link,
        icon: Cards[index].icon,
        name: Cards[index].name,
        png: Cards[index].png,
        id: id,
    }
    CardsData[index] = CardsObj

    setCards(CardsData)
    const [Cards, setCards] = props.value.Cards
}

export withUserData(UpdateID)

this is my code I want to export this const not export default 'cause I already have many other functions in one file I want to export them all.

A:  function UpdateID(index, id) {
    ...
}

const userData = withUserData(UpdateID)
export {
  userData
}


text:
Q: What is shared across hardcore characters in my account? I just created a new character and I noticed he has 10k of gold, by going into the AH, without even logging on. Are items collected by any of my HC characters kept in my account's stash in case I die? Is the same true for gold or is this some kind of bug?
This is quite important since all that's with the character is lost when he dies.
Also, what of artisans' progress?

A: Hardcore works the same as normal mode in terms of what is shared. This includes at least: gold, artisan progress and anything in your stash as well as stash size unlocked. These things just aren't shared between hardcore and normal mode.
No items on your character or in their inventory at the time of death is saved. Gold is special in that you can't 'store' it as such and so any gold you have accumulated is saved.

A: Artisan progress, gold, and items in your shared stash are shared between HC characters.


text:
Q: Robolectric java.lang.IllegalArgumentException: class com.android.app.R contains final fields I am testing a legacy app with resources distributed across 3 packages.
So I extended RobolectricTestRunner and modified resource path as below.
public class DialerRobolectricTestRunner extends RobolectricTestRunner {

    @Override
    protected AndroidManifest getAppManifest(Config config) {

     return new AndroidManifest(Fs.fileFromPath(manifestPath),
     Fs.fileFromPath(resDir), Fs.fileFromPath(assetsDir)) {

       @Override
       public List<ResourcePath> getIncludedResourcePaths() {
           List<ResourcePath> paths = super.getIncludedResourcePaths();

           paths.add(new ResourcePath(getRClass(),Fs.fileFromPath("../pkg1/res/"), getAssetsDirectory()));
           paths.add(new ResourcePath(getRClass(), Fs.fileFromPath("../pkg2/res/"), getAssetsDirectory()));
           paths.add(new ResourcePath(getRClass(), Fs.fileFromPath("../pkg2/res/"), getAssetsDirectory()));
           return paths;
       }
    }
}

I see below exception while testing android app with Robolectric
java.lang.IllegalArgumentException: class com.android.app.R contains final fields, these will be inlined by the compiler and cannot be remapped.

Robolectric : 3.3.2,
sdk : 23


text:
Q: upload into my soundcloud account using my web form and api? I'm creating a mobile application which plays music stored in my SoundCloud account.
Is there any way to create an automatic login to my SoundCloud account (PHP)? I don't want each user to have to use OAuth because it is only accessing my account and they will have already logged into my site.
Basically i just want to have a list of users tracks, and have the users be able to add or delete tracks from this account with my web form.
All the documentation I've seen uses OAuth to log into individuals accounts but i only want to access my account.
any help or a direction to look would be great
thanks

A: I was able to login in to a soundcloud account programmatically in PHP using the undocumented (in PHP as yet!) credentialsFlow function:
$sc_client_id = "Client ID from the developer page on soundcloud for your app";
$sc_secret = "Client Secret from the developer page";
$sc_user = "your soundcloud account user";
$sc_pass = "your soundcloud account password";
// create client object and set access token
$client = new Services_Soundcloud($sc_client_id, $sc_secret);
// login
$client->credentialsFlow($sc_user, $sc_pass);

Then you can upload audio files using the $client variable, e.g. this code, taken from 'Uploading Audio Files', http://developers.soundcloud.com/docs#uploading
// upload audio file
$track = json_decode($client->post('tracks', array(
    'track[title]' => 'This is my sound',
    'track[asset_data]' => '@/absolute/path/to/file.mp3'
)));

// print track link
print $track->permalink_url;

A: Looks like you can parse the track data in JSON format
http://api.soundcloud.com/tracks?client_id=#{client_id}&limit=10&format=json

There's no "login" either.  You're just grabbing a user's public tracks.
Soundcloud has a whole developer API that you should probably brush up on.

A: Here's my suggestion: have your users create individual SoundCloud accounts for themselves, then create an interface that allows them to share individual tracks with you, which you can then aggregate into a playlist of some sort (which could then be streamed to whatever device you wish, via SoundCloud).
This has the following advantages:

*

*You maintain control of your own personal SoundCloud account and don't have to worry about it expanding to an unmanageable size.

*You have the ability to moderate tracks, allowing you to screen for copyrighted or troll content.

*It's more extensible -- if you use something like Drupal's aggregate facility, or a plugin like FeedWordPress (not sure what your CMS platform is, if any), the RSS feeds of tracks you're using can also be taken and used elsewhere by your users, thus potentially increasing the size of your audience. I.e., a widget that displays the latest tracks people can drop onto social profiles or blogs or whatever.

*If set up well enough, your solution might be able to encompass non-SoundCloud streaming sources -- YouTube, etc.

Basically, you're dumping links sent to you into an RSS feed, which are super easy to work with both cross-browser and cross-OS. I'd personally use Drupal for this, but I'm sure there are ways to do this just as easily in Joomla!, WordPress or any other CMS worth its salt.


text:
Q: No images in GitHub Pages RSS feed I recently set up a blog with Jekyll / GitHub Pages and it automatically provides an RSS feed.
Embedding images in the blog itself works perfectly fine, using:
{{ site.baseurl }}/...

but in the RSS feed, they are not displayed.
I also noticed that this website: https://validator.w3.org/feed/ throws quite some errors, always saying that description should not contain relative URL references: /blog/assets/images/IMG_8196.jpg.
It would be great if you had an idea on how to solve this, because absolute URLs aren't too great especially when it comes to testing on own server / localhost.
Thank you in advance!

A: In _config.yml, set url and baseurl, if needed.
Any link or resource in your feed.xml must be pointing to an absolute url. This file is consumed my tools that only knows where to find things with absolute urls.
{{ site.url }}{{ site.baseurl }}/myPath/myFile.html

This can also be done with the new absolute_url filter
{{ "myPath/myFile.html" | absolute_url }}

And this is true for links, images, css, js, and so on.


text:
Q: Make error on PerlMagick 6.8.6 Attempting to install the CPAN Image::Magick module and am getting a fatal error that a core file is missing (note the fatal error highlighted between horizontal lines):
Reading '/Users/coblem/.cpan/Metadata'
Database was generated on Sat, 27 Jul 2013 18:29:02 GMT
Running install for module 'Image::Magick'
Running make for J/JC/JCRISTY/PerlMagick-6.86.tar.gz
Checksum for /Users/coblem/.cpan/sources/authors/id/J/JC/JCRISTY/PerlMagick-6.86.tar.gz ok

CPAN.pm: Building J/JC/JCRISTY/PerlMagick-6.86.tar.gz

Checking if your kit is complete...
Looks good
Warning (mostly harmless): No library found for -lperl
Writing Makefile for Image::Magick
Writing MYMETA.yml and MYMETA.json
cp Magick.pm blib/lib/Image/Magick.pm
AutoSplitting blib/lib/Image/Magick.pm (blib/lib/auto/Image/Magick)
/opt/local/bin/perl5.12 /opt/local/lib/perl5/5.12.4/ExtUtils/xsubpp -typemap      /opt/local/lib/perl5/5.12.4/ExtUtils/typemap -typemap typemap Magick.xs > Magick.xsc && mv  Magick.xsc Magick.c
/usr/bin/clang -c -I/usr/local/include/ImageMagick-6 -DMAGICKCORE_HDRI_ENABLE=0 - DMAGICKCORE_QUANTUM_DEPTH=16 -I/usr/include/libxml2 -I"/usr/include/ImageMagick-6" -pipe -O2 - fno-common -DPERL_DARWIN -I/opt/local/include -no-cpp-precomp -fno-strict-aliasing -fstack- protector -I/opt/local/include -I/usr/include/freetype2 -fopenmp -g -O2 -Wall -pthread - DMAGICKCORE_HDRI_ENABLE=0 -DMAGICKCORE_QUANTUM_DEPTH=16 -O3 -DVERSION=\"6.86\" - DXS_VERSION=\"6.86\" "-I/opt/local/lib/perl5/5.12.4/darwin-thread-multi-2level/CORE" -  D_LARGE_FILES=1 -DHAVE_CONFIG_H Magick.c
clang: warning: argument unused during compilation: '-fopenmp'

Magick.xs:60:10: fatal error: 'magick/MagickCore.h' file not found

#include <magick/MagickCore.h>
^
1 error generated.
make: *** [Magick.o] Error 1
JCRISTY/PerlMagick-6.86.tar.gz
/usr/bin/make -- NOT OK
Running make test
Can't test without successful make
Running make install
Make had returned bad status, install seems impossible

Thoughts on what to do next?

A: You may need to install ImageMagick-devel package (with MagickCore.h header file).


text:
Q: Chi-square testing for constraining a parameter I have an important question about the use of chi^2 test to constrain a parameter in cosmology. I appreciate your help. Please do not give this question negative rate (this question is important to me).
Assume we have a data file (data.txt) concluding 600 data and this data file has 3 columns, first column is redshift(z), second column is observational dL(m_obs) and third column is error(err). As we know chi^2 function is
 chi^2=(m_obs-m_theo)**2/err**2  #chi^2=sigma((m_obs-m_theo)**2/err**2) from 1 to N=600

All of thing that we must calculate is putting z from given data file into our function in m_theo for all 600 data and calculate chi^2. Now in m_thoe we have a free parameter(o_m) and we have to find its value in which the chi^2 reach its minimum value.
q= 1/sqrt( (1+z)**2 * (1+0.01*o_m*z) - z*(2+z)*(1-0.01*o_m) )
m_theo = 5.0 * log10( (1+z)*q ) + 43.1601

This question is not repetitive and is very important to every body using chi^2 specially for cosmologists and physicists.
How to find minimized chi^2 and relative o_m?
from math import *
import numpy as np
from scipy.integrate import quad
min=l=a=b=chi=None
c=0   #for Sigma or summation chi^2 terms in c=c+chi for first term
def ant(z,o_m):    #0.01*o_m  is steps of o_m
   return 1/sqrt(((1+z)**2*(1+0.01*o_m*z)-z*(2+z)*(1-0.01*o_m)))
for o_m in range(24,35,1): #arbitrary range of o_m
############## opening data file containing 580 dataset
    with open('data.txt') as f:
        for i, line in enumerate(f): #
            n= list(map(float, line.split())) #
            for i in range(1):
##############
                q=quad(ant,0,n[1],args=(o_m,))[0]  #Integration o to z, z=n[1]
                h=5*log10((1+n[1])*(299/70)*q)+25    #function of dL
                chi=(n[2]-h)**2/n[3]**2       #chi^2 test function
                c=c+chi            #sigma from 1 to N of chi^2 and N=580
        if min is None or min>c:
            min=c
            print(c,o_m)

I think my code is correct but it doesn't give me a proper answer.
Thank you and I appreciate your time and your attention.

A: This is the correct answer:
 from math import *
 import numpy as np
 from scipy.integrate import quad
 min=l=a=b=chi=None
 c=0
 z,mo,err=np.genfromtxt('Union2.1_z_dm_err.txt',unpack=True)
 def ant(z,o_m):            #0.01*o_m  is steps of o_m
     return 1/sqrt(((1+z)**2*(1+0.01*o_m*z)-z*(2+z)*(1-0.01*o_m)))
 for o_m in range(20,40):
     c=0
     for i in range(len(z)):
         q=quad(ant,0,z[i],args=(o_m,))[0]     #Integration o to z
         h=5*log10((1+z[i])*(299000/70)*q)+25     #function of dL
         chi=(mo[i]-h)**2/err[i]**2               #chi^2 test function
        c=c+chi
        l=o_m
        print('chi^2=',c,'Om=',0.01*l,'OD=',1-0.01*l)


text:
Q: Resize images when upload I am very new to Resize image in php.Basically i wanted to make thumbnail image using uploaded image. i have used below code but its not working, can anybody help me?.. Thanks in Advance...
if($_FILES['logo2_1']['name'])
{
        $uniq = substr( md5(uniqid (rand())), 0, 10 );
        $ext = strtolower(substr(strrchr($_FILES['logo2_1']['name'], '.'), 1));
        $allwd = array('jpg','jpeg','gif','png');
        if (in_array( $ext , $allwd ))
        {

            if (move_uploaded_file($_FILES['logo2_1']['tmp_name'], $upload_dir['path']."/".$uniq.".".$ext)){
            move_uploaded_file($_FILES['logo2_1']['tmp_name'], $upload_dir['path']."/".$uniq.".".$ext);
            $logo2_1 = $upload_dir['path']."/".$uniq . '.' . $ext;
            //$logo_1 = "yes";
            }
            else
            {$logo2_1 = "no00";}
        }

}

A: There is a really nice library to do this called phpThumb.
    http://phpthumb.sourceforge.net/
It works well and is well documented.


text:
Q: What does plasmon look like in 3D band structure graph? Consider metal, and its reciprocal lattice representation with Fermi surface.
What is the correct way to represent a plasmon in this system? M.b. rotating points on the surface? Or 3d membrane-like oscillation of surface? Or what?


text:
Q: Create an empty object of a specified type dynamically Using a dataclass to specify a set of environment variables and am trying to keep the dataclass separate from a class that modifies the environment. Passing in an instance of the dataclass and have a get_env that determines if those variables are set in the environment. When os.getenv(field.name.upper(), None) is called I want None to be type as specified in the dataclass. e.g. if field.type is a str I want something like os.getenv(field.name.upper(), field.type.__new__(field.type))
This seems to work but would like to confirm this makes sense or what alternatives to consider?
class Env:
  def __init__(self, config: Config):
    self.config = config

  def get_env_dict(self):
    return self.config.to_dict()

  def get_env(self):
    env_dict = self.get_env_dict()
    for field in fields(self.config):
      env_dict[field.name.upper()] = os.getenv(field.name.upper(), None)

A: This works for a dataclass with strings. unsure yet if it will work will all kinds of types.
class Env:
  def __init__(self, config: Config):
    self.config = config

  def get_env_dict(self):
    return self.config.to_dict()

  def get_env(self):
    env_dict = self.get_env_dict()
    for field in fields(self.config):
      env_dict[field.name.upper()] = os.getenv(
                                               field.name.upper(),
                                               field.type.__new__(field.type)
                                              )


text:
Q: Wordpress page not taking precedence over server directory On my wordpress site, I have a page mysite.com/download. On the same server I have a directory named download, where I store files which I need to provide on download page. So the problem is that when someone tries to access mysite.com/download, he's taken to the directory instead of the page. I have turned off the directory access for now, so it currently displays no permission to access.
I want wordpress to display the page instead of the directory. I am not sure if it's a problem with the server or wordpress. I hope someone can clarify.

A: Found an answer!
It's an issue with the .htaccess file. I needed to write a rule in the .htaccess file for this exception, after renaming my download folder to downloads. So it still requires the folder to be renamed.
RewriteRule ^download/(.+)$ downloads/$1

This rule should be before the wordpress rules in the file. This makes sure that if someone is looking in the mysite.com/download/folder1 sub-directory, he's actually redirected to mysite.com/downloads/folder1.
Ref: WP Page and Subdirectory with same name


text:
Q: Select entity containing list, where list argument has specific value I have two tables first one which contains employees:
@Entity
public class Employee {
@Id
@GeneratedValue
private long id;
private String firstName;
private String lastName;
private double Salary;
@ManyToMany(mappedBy = "employees")
private List<Project> projects;
//getters and setters
}

And the second which contains projects:
@Entity
public class Project {
@Id
@GeneratedValue
private long id;
private String name;
@ManyToMany
private List<Employee> employees;
//getters and setters
}

I want to select all employees that are currently working at project named for example "ProjectOne". Whats the best way to write this query in hibernate, and is there any option to use TypedQuery? Or i need to use normal Query? I was trying to write something like:
Query query= entityManager.createQuery("select e,p from Employee e, Project p where p.name='ProjectOne' ");
List<Employee>queryResultList=query.getResultList();

And I'm already getting some response from hibernate, but it is strange reference, which I can't read properly.
EDIT: The answer was easier that I thought it would be. If query returns 2 values, firstly it has to be casted to Object[], and then first value (Employee) can be cast from object[0], and second (Project) from object[1]:
Iterator iterator=queryResultList.iterator();
    while(iterator.hasNext()){
        Object[] object= (Object[]) iterator.next();
        Employee emp= (Employee) object[0];
        Project proj= (Project) object[1];
        System.out.println(emp.getFirstName()+" "+emp.getLastName()+" at project "+proj.getName());
    }


text:
Q: Clion cmake in ubuntu 18.04 I've seen this one over and over but every answer that was given before didn't help me.
I downloaded clion and cmake, and updated gcc.
When manualy using gcc/g++ the code is compiling.
from the clion's cmake I keep getting:
CMake Error at /home/dm/Downloads/CLion-2018.1.4/clion-2018.1.4/bin/cmake/share/cmake-3.10/Modules/CMakeTestCCompiler.cmake:52 (message):
  The C compiler

    "/usr/bin/gcc"

  is not able to compile a simple test program.

  It fails with the following output:

    Change Dir: /home/dm/CLionProjects/TheTestingGrounds/cmake-build-default/CMakeFiles/CMakeTmp

    Run Build Command:"/usr/local/bin/cmake" "cmTC_9582b/fast"
    CMake Error: The source directory "/home/dm/CLionProjects/TheTestingGrounds/cmake-build-default/CMakeFiles/CMakeTmp/cmTC_9582b/fast" does not exist.
    Specify --help for usage, or press the help button on the CMake GUI.

  CMake will not be able to correctly generate this project.

Thing is, the cmTC_9582b/fast obviously dosen't exist. What is clion trying to do? It looks like it's trying to test cmake with a bad test and when its failing Clion decideds there's a problem.
Any solution for that?


text:
Q: Linq: Getting missing records So heres my case i got 2 tables one with Languages one with Resources and what i want to do is to find all Resources that is missing on each language...
The default language i wanna go after is languageId = 1
Table "Resources"
Id    Key    Value    LanguageId
1     k1     test     1
2     k1     test     2
3     k1     test     3

Table "Languages"
Id
1
2
3
4
5
6
7

language contains about 10 rows of languages.
Now what i wanna do is to take out those resources that dosent exists
(ex results)
Key   Value   LanguageId
k1    test    1
k1    test    2
k1    test    3
k1    null    4
k1    null    5
k1    null    6
k1    null    7

Any suggestions how to solve this problem, ive tried with GroupJoin And SelectMany but no good results.

A: It feels to me like actually your structure isn't quite right yet: you should have a third table of ResourceKeys, with k1 in. That way when you add a resource key, the first thing you add is an entry in ResourceKeys, at which point all languages will be missing that translation. Otherwise you have no way of representing "a resource with no translations" which is a meaningful concept IMO.
You can then cross-join Language and ResourceKeys, and group join against Resources:
var query = from language in Languages
            from resourceKey in ResourceKeys
            join resource in Resources
                 on new { LangId = language.Id, ResId = resourceKey.Id }
                 equals new { LangId = resource.LanguageId,
                              ResId = resource.Key }
                 into values
            select new { LangId = language.Id,
                         ResId = resourceKey.Id,
                         Value = values.SingleOrDefault() };

A: from lang in context.Languages
where !context.Resources.Contains(r => r.LanguageId == lang.LanguageId)
select lang


text:
Q: How to get PHP DOM getElementsByTagName('body') with html tags Im getting the body content but without html tags(It is cleaned up) inside the body.I need with all html tags inside the body. what do I want to change on my code?
$doc = new DOMDocument();
@$doc->loadHTMLFile($myURL);

$elements2 = $doc->getElementsByTagName('body');

        foreach ($elements2 as $el2) {
            echo $el2->nodeValue, PHP_EOL;
        echo "
";
}

A: You will need to save the body child nodes as HTML. I suggest using Xpath to fetch the nodes, this avoids the outer loop:
$html = <<<'HTML'

    Foo

Bar

HTML;

$document = new DOMDocument();
$document->loadHtml($html);
$xpath = new DOMXpath($document);

$result = '';
foreach ($xpath->evaluate('//body/node()') as $node) {
  $result .= $document->saveHtml($node);
}
var_dump($result);

Output:
string(29) "
    Foo

Bar

  "


text:
Q: Compilation error in connecting Arduino Uno with SKYNAV skm53 GPS module I am trying to connect Arduino Uno with skm53 GPS module, however before uploading the sketch with the Arduino software, I verified it and found the following error.

Error: #error NewSoftSerial has been moved into the Arduino core as of version 1.0. Use SoftwareSerial instead.

I have included the libraries TinyGPS and NewSoftSerial in the libraries directory of the Arduino tool, I have searched and found that almost all code are the same as mine.
#include <TinyGPS.h>
#include <NewSoftSerial.h>

unsigned long fix_age;
NewSoftSerial GPS(2,3);
TinyGPS gps;
void gpsdump(TinyGPS &gps);
bool feedgps();
void getGPS();
long lat, lon;
float LAT, LON;

void setup(){
    GPS.begin(9600);
    //Serial.begin(115200);
}

void loop(){
    long lat, lon;
    unsigned long fix_age, time, date, speed, course;
    unsigned long chars;
    unsigned short sentences, failed_checksum;

    // Retrieves +/- latitude/longitude in 100000ths of a degree.
    gps.get_position(&lat, &lon, &fix_age);

    getGPS();
    Serial.print("Latitude : ");
    Serial.print(LAT/100000,7);
    Serial.print(" :: Longitude : ");
    Serial.println(LON/100000,7);
}

void getGPS(){
    bool newdata = false;
    unsigned long start = millis();
    // Every 1 seconds we print an update.
    while (millis() - start < 1000)
    {
        if (feedgps ()){
            newdata = true;
        }
    }
    if (newdata)
    {
        gpsdump(gps);
    }
}

bool feedgps(){
    while (GPS.available())
    {
        if (gps.encode(GPS.read()))
            return true;
    }
    return 0;
}

void gpsdump(TinyGPS &gps)
{
    //byte month, day, hour, minute, second, hundredths;
    gps.get_position(&lat, &lon);
    LAT = lat;
    LON = lon;
    {
        feedgps(); // If we don't feed the GPS during this long
                   //routine, we may drop characters and get
                   //checksum errors.
    }
}

A: You might be looking at older examples (pre Arduino 1.0 and pre inclusion of softwwareserial).
Those examples would have worked with Arduino .23 and earlier.
Just change your first four lines of code like this and it will compile ok:
#include <TinyGPS.h>
#include <SoftwareSerial.h>

unsigned long fix_age;
SoftwareSerial GPS(2,3);

Then you can delete the NewSoftLibrary to avoid future problems.
Also a suggestion: having two variables named the same but with different case, is very confusing.
Better to use more descriptive and distinquishing names to quickly identify them. Probably a better choice might be ssGPS for the serial software connection interface and tlibGPS for the tiny GPS library.


text:
Q: Dynamic names in Spring internationalization I have in the properties file several properties to be translated into different laguages:
list.var1=XXX
list.var2=XXX
list.var3=XXX

They are values of a list so in the JSP I want to get the translated value. So I have a property for example called myVar whose values can be {var1, var2, var3} and I want to get the message "list.${myVar}".
The problem is that in fmt:message tag, key attribute doesn't accept expressions.
<%@ taglib prefix="fmt" uri="java.sun.com/jstl/fmt" %>
<fmt:message key="list.${myVar}"/>

What is the best way to do this?
Thanks.

A: It should work the way you want: <fmt:message key="list.${myVar}"/>
Because the tag lib definition alowes that key is an expression:
fmt.tdl:
<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
    version="2.0">

  <description>JSTL 1.1 i18n-capable formatting library</description>
  <display-name>JSTL fmt</display-name>
  <tlib-version>1.1</tlib-version>
  <short-name>fmt</short-name>
  <uri>http://java.sun.com/jsp/jstl/fmt</uri>
...
<tag>
    <description>
        Maps key to localized message and performs parametric replacement
    </description>
    <name>message</name>
    <tag-class>org.apache.taglibs.standard.tag.rt.fmt.MessageTag</tag-class>
    <body-content>JSP</body-content>
    <attribute>
        <description>
Message key to be looked up.
        </description>
        <name>key</name>
        <required>false</required>
        <rtexprvalue>true</rtexprvalue>
    </attribute>
...

And what defently worked in may application is
<%@ taglib prefix='spring' uri='http://www.springframework.org/tags'%>
...
<spring:message code="myPrefix.${transaction.state}"/>


text:
Q: Finding a map between tuples of linear dependencies Through my research I have arrived at the following question which I am unable to solve:
Given a triple of 4-tuples, $$(a_1,...,a_4);(b_1,...,b_4);(c_1,...,c_4)$$ (all are vectors, taken from the set of $k$-Hamming weight vectors (vectors with exactly $k$ ones) in $\Bbb{F}_2^n$ for $n>k$) where each of the 4-tuples is a linear dependency (i.e. $a_1+a_2+a_3+a_4=0$, same for $b_i,c_i$'s) match it with a couple of 6-tuples, $$(d_1,...,d_6);(e_1,...,e_6)$$ such that these are also linear dependencies (i.e $d_1+...+d_6=0$, same for $e_i$'s), and $d_i$'s and $e_j$'s are also of $k$ Hamming weight for any $i,j$, and this matching should be one-to-one (Two triples (with order taken for the triples and inside the triples) give distinct two couples).
So far, I have maps for each $t\in\Bbb{F}_2^n$ that match a triple of 4-dependencies to a couple of 6-dependencies, given by:
$$f_t((a_1,...,a_4);(b_1,...,b_4);(c_1,...,c_4))=(a_1,a_2,a_3,b_1,b_2,a_4+b_1+b_2);(b_3,c_1,c_2,c_3,t,c_4+b_3+t)$$
but this clearly does not guarantee that the last element in each 6-tuple is of $k$ Hamming weight.
Basically I think that my problem is that I don't know how to use the fact that the 3 dependencies I get as input all have Hamming weight $k$ (That is, that the sum $a_1+a_2+a_3$ also has Hamming weight $k$) to construct the 6 tuples.


text:
Q: show the custom message in Django form Sorry, I'm not good at English. I have some problem for studying Django.
I wrote the below code to make a form. And I need to show the custom message when user didn't enter the value in text box.
class ArticleForm(ModelForm):
    title = forms.CharField( error_messages={'required': 'Please enter title'},
                         max_length=128 ,
                         required=True,
                         widget=forms.TextInput(attrs={'size':60}))
    contents  = forms.CharField( required=True,
                         widget=forms.Textarea(attrs={'cols': 160, 'rows': 20}))
    email = forms.CharField(max_length=128, widget=forms.TextInput(attrs={'size':60}))
    writed_by = forms.CharField(max_length=100,
                            required=True,
                            widget=forms.TextInput(attrs={'size':60}))
    class Meta:
        model  = Article
        fields = ["title", "writed_by", "email", "contents"]

I want to show 'Please enter title' message when didn't enter the title. But form shows the default message.
what is the problem in this code?
Thanks.

A: You can try setting the custom message in the __init__() like so:
class ArticleForm(ModelForm):
    title = forms.CharField(max_length=128,
                            required=True,
                            widget=forms.TextInput(attrs={'size': 60}))
    class Meta:
        model  = Article
        fields = ["title"]

    def __init__(self, *args, **kwargs):
        super(ArticleForm, self).__init__(*args, **kwargs)

        # add custom error messages
        self.fields['title'].error_messages['required'] = 'Please enter title'


text:
Q: Show all posts if fields empty // Start the Query
$v_args = array(
    'post_type' => 'listing',
    'meta_query' => array(
        array(
            'key' => 'wpcf-services',
            'value' => $services,
            'compare' => 'LIKE',
        ),
    ),
    'tax_query' => array(
        'relation' => 'AND',
        array(
            'taxonomy' => 'listing-city',
            'field' => 'name',
            'terms' => $location,
            'compare' => 'LIKE',
            'operator' => 'IN'
        ),
        array(
            'taxonomy' => 'listing-category',
            'field' => 'name',
            'terms' => $listing_category,
            'compare' => 'LIKE',
            'operator' => 'IN'
        ),
    ),
);

$listingsearch = new WP_Query( $v_args );

I want to show all posts in search results if field is empty. If either tax_query or meta_query is left blank, show all posts in search results.
How can I achieve this?

A: <?  if(isset($services)&&$services!=""){
            $meta_query[] = array(
                'key'     => 'wpcf-services',
                'value'   => $services,
                'compare' => 'LIKE',
                );
        }

         $tax_query = array('relation'=>'AND');

          if(isset($location)&&$location!=""){
             $tax_query[] = array(
                        'taxonomy' => 'listing-city',
                        'field' => 'name',
                        'terms' => $location,
                        'compare' => 'LIKE',
                        'operator' => 'IN'
                );
            }

        if(isset($listing_category)&&$listing_category!=""){
             $tax_query[] = array(
                        'taxonomy' => 'listing-category',
                        'field' => 'name',
                        'terms' => $listing_category,
                        'compare' => 'LIKE',
                        'operator' => 'IN'
                );
            }

        $v_args = array(
            'post_type'  =>  'listing',
            'meta_query' => $meta_query,
            'tax_query' =>$tax_query,

        );

 $listingsearch = new WP_Query( $v_args );?>

This should work for you.
It would check the empty and if found, it will fetch all the products. Else it would fetch accordingly. Let me know if any more suggestions.
Thanks

A: I guess you may mean this ?:
$v_args = array(
'post_type'     =>  'listing',
'meta_query' => array(
            array(
            'key'     => 'wpcf-services',
            'value'   => empty($services)?'%':$services,
            'compare' => 'LIKE',
            ),
            ),
'tax_query' =>array(
                'relation' => 'AND',
        array(
                'taxonomy' => 'listing-city',
                'field' => 'name',
                'terms' => empty($location)?'%':$location,
                'compare' => 'LIKE',
                'operator' => 'IN'
        ),
        array(
                'taxonomy' => 'listing-category',
                'field' => 'name',
                'terms' => empty($listing_category)?'%':$listing_category,
                'compare' => 'LIKE',
                'operator' => 'IN'
        ),
        ),

);


text:
Q: Prove the ratio of distances $d(P_1,P_2):d(P_2,P_3)$ is independant of line M If $L_1,L_2,L_3$ are three parallel lines in $\Bbb E^2$, and they meet in a line M in $P_1,P_2,P_3$.then the (signed) ratio of distances $d(P_1,P_2):d(P_2,P_3)$ is independent of M.
I can see that this is true, but I don't know how I could prove this in a correct way.
I'd appreciate some hints, about what kind of prove I need, or some other theorems I need to prove this one.

A: Hint
The triangles formed by $M$ on $L_1,L_2,L_3$ are similar.


text:
Q: Prove that $\int(x^2-1)^n \,dx = \frac{x(x^2-1)^n}{2n+1} - \frac{2n}{2n+1}\int(x^2-1)^{n-1} \,dx$ I have tried to solve the problem mainly with the LS of the equation.
I can not seem to get rid of the x variable within the resultant integrand.
ex. after the first integration by parts I am left with:
$x(x^2-1)^n - 2n\int x^2(x^2-1)^{n-1} \,dx$
Thanks for all the help in advance!

A: Hint: Just write $\int x^{2}(x^{2}-1)^{n-1}dx$ as $\int (x^{2}-1+1)(x^{2}-1)^{n-1}dx=\int (x^{2}-1)^{n}dx+\int (x^{2}-1)^{n-1}dx$ and transfer one term to the left side.


text:
Q: base64 encoding with ios8/ios9 api without line length limit How to base64 encode string with ios8 and ios9 api without line length limit.
I'm preparing some custom basic authentication and I need to encode credentials according to standard which means:
The resulting string is then encoded using the RFC2045-MIME variant of Base64, except not limited to 76 char/line
In old ios7 there was a method: NSData base64Encoding but now is deprecated and instead of it I have:
- (NSString *)base64EncodedStringWithOptions:
(NSDataBase64EncodingOptions)options NS_AVAILABLE(10_9, 7_0);

and the options are:
typedef NS_OPTIONS(NSUInteger, NSDataBase64EncodingOptions) {
// Use zero or one of the following to control the maximum line length after which a line ending is inserted. No line endings are inserted by default.
NSDataBase64Encoding64CharacterLineLength = 1UL << 0,
NSDataBase64Encoding76CharacterLineLength = 1UL << 1,

// Use zero or more of the following to specify which kind of line ending is inserted. The default line ending is CR LF.
NSDataBase64EncodingEndLineWithCarriageReturn = 1UL << 4,
NSDataBase64EncodingEndLineWithLineFeed = 1UL << 5,

} NS_ENUM_AVAILABLE(10_9, 7_0);

So I can choose line length 64 or 76. The base64 encoding for basic authentication don't have line length limit so how can I approach to this.

A: If you don't choose any options, line endings are not added.
[myData base64EncodedStringWithOptions:0]; // One long string


text:
Q: Not able to mount shared drive on server A to server B I am not able to mount a drive that is located on server A to server B. I have followed this document step by step just replacing portmap to rpcbind as the system installed rpcbind instead of portmap. I am getting the below exception when I try to mount the file system.
mount.nfs connection timed out
My servers are located on Microsoft Azure. I tried pinging from client(server B) to server A but I was not able to. I believe it is a port issue but how to rectify that I am not able to get it.
Please let me know what i need to check to get it working.

A: Check telneting to the port on the Azure server, if that fails you might have to modify the Azure servers security group and add a rule that allows ingress to
Port 111 (TCP and UDP) and 2049 (TCP and UDP) for the NFS server, and egress rules for the client. if they are on the same subnet then something else is wrong.
https://azure.microsoft.com/en-us/documentation/articles/virtual-networks-nsg/


text:
Q: Clearcase UCM is trying to merge pdf files While delivering to integration stream , Clearcase UCM is trying to merge pdf files and fails.
As PDF files no need to be merged, how to solve this?
Is it a defect in Clearcase UCM? any work around is there or some policy settings needs to be set to solve this?

A: If you don't want to merge a specific type of file, you can change its type to a "copy merge" policy (ClearCase will copy the source over the destination)
cleartool find . -name '*.jar' -exec 'cleartool chtype "COPY_MERGE" $CLEARCASE_XPN'

This is an improvement from the NEVER_MERGE presented in this IBM article, and is available in ClearCase 7.x.
You can create a custom "FILE_COPY_MERGE" type as described here:
cleartool mkeltype -supertype compressed_file -mergetype copy -nc FILE_COPY_MERGE
cleartool chtype FILE_COPY_MERGE 'element'

A more complete example is detailed in this technote "Handling binary files in ClearCase":


text:
Q: Randomly introduce NaN values in pandas dataframe How could I randomly introduce NaN values into my dataset for each column taking into account the null values already in my starting data.
I want to have for example 20% of NaN values by column.
For example:
If I have in my dataset 3 columns: "A", "B" and "C" for each columns I have NaN values rate how do I introduce randomly NaN values by column to reach 20% per column:
A: 10% nan
B: 15% nan
C: 8% nan

For the moment I tried this code but it degrades too much my dataset and I think that it is not the good way:
df = df.mask(np.random.choice([True, False], size=df.shape, p=[.20,.80]))

A: I am not sure what do you mean by the last part ("degrades too much") but here is a rough way to do it.
import numpy as np
import pandas as pd

A = pd.Series(np.arange(99))

# Original missing rate (for illustration)
nanidx = A.sample(frac=0.1).index
A[nanidx] = np.NaN

###
# Complementing to 20%
# Original ratio
ori_rat = A.isna().mean()

# Adjusting for the dataframe without missing values
add_miss_rat = (0.2 - ori_rat) / (1 - ori_rat)

nanidx2 = A.dropna().sample(frac=add_miss_rat).index
A[nanidx2] = np.NaN

A.isna().mean()

Obviously, it will not always be exactly 20%...
Update
Applying it for the whole dataframe
for col in df:
    ori_rat = df[col].isna().mean()

    if ori_rat >= 0.2: continue

    add_miss_rat = (0.2 - ori_rat) / (1 - ori_rat)
    vals_to_nan = df[col].dropna().sample(frac=add_miss_rat).index
    df.loc[vals_to_nan, col] = np.NaN

Update 2
I made a correction to also take into account the effect of dropping NaN values when calculating the ratio.

A: Unless you have a giant DataFrame and speed is a concern, the easy-peasy way to do it is by iteration.
import pandas as pd
import numpy as np
import random

df = pd.DataFrame({'A':list(range(100)),'B':list(range(100)),'C':list(range(100))})
#before adding nan
print(df.head(10))

nan_percent = {'A':0.10, 'B':0.15, 'C':0.08}

for col in df:
    for i, row_value in df[col].iteritems():
        if random.random() <= nan_percent[col]:
            df[col][i] = np.nan
#after adding nan
print(df.head(10))

A: I guess I am a little late to the party but if someone needs a solution that's faster and takes the percentage value into account when introducing null values, here's the code:
nan_percent = {'A':0.15, 'B':0.05, 'C':0.23}

for col, perc in nan_percent.items():
    df['null'] = np.random.choice([0, 1], size=df.shape[0], p=[1-perc, perc])
    df.loc[df['null'] == 1, col] = np.nan

df.drop(columns=['null'], inplace=True)

A: Here is a way to get as close to 20% nan in each column as possible:
def input_nan(x,pct):
    n = int(len(x)*(pct - x.isna().mean()))
    idxs = np.random.choice(len(x), max(n,0), replace=False, p=x.notna()/x.notna().sum())
    x.iloc[idxs] = np.nan

df.apply(input_nan, pct=.2)

It first takes the difference between the NaN percent you want, and the percent NaN values in your dataset already. Then it multiplies it by the length of the column, which gives you how many NaN values you want to put in (n). Then uses np.random.choice which randomly choose n indexes that don't have NaN values in them.
Example:
df = pd.DataFrame({'y':np.random.randn(10), 'x1':np.random.randn(10), 'x2':np.random.randn(10)})
df.y.iloc[1]=np.nan
df.y.iloc[8]=np.nan
df.x2.iloc[5]=np.nan

#           y        x1        x2
# 0  2.635094  0.800756 -1.107315
# 1       NaN  0.055017  0.018097
# 2  0.673101 -1.053402  1.525036
# 3  0.246505  0.005297  0.289559
# 4  0.883769  1.172079  0.551917
# 5 -1.964255  0.180651       NaN
# 6 -0.247067  0.431622 -0.846953
# 7  0.603750  0.475805  0.524619
# 8       NaN -0.452400 -0.191480
# 9 -0.583601 -0.446071  0.029515

df.apply(input_nan)

#           y        x1        x2
# 0  2.635094  0.800756 -1.107315
# 1       NaN  0.055017  0.018097
# 2  0.673101 -1.053402  1.525036
# 3  0.246505  0.005297       NaN
# 4  0.883769  1.172079  0.551917
# 5 -1.964255       NaN       NaN
# 6 -0.247067  0.431622 -0.846953
# 7  0.603750       NaN  0.524619
# 8       NaN -0.452400 -0.191480
# 9 -0.583601 -0.446071  0.029515

I have applied it to the whole dataset, but you can apply it to any column you want. For example, if you wanted 15% NaNs in columns y and x1, you could call df[['y','x1]].apply(input_nan, pct=.15)


text:
Q: Solving $\int_0^{\infty} \frac{\sin^m(x)}{x^n} dx$ for $m, n \in \mathbb{Z}^+$ I saw this question and thought of the more general integral $$I(m, n) =\int_0^{\infty} \frac{\sin^m(x)}{x^n} dx$$
where $m, n$ are positive integers, and the integral converges. The integral converges when $2 \le n \le m$ or $n = 1, m$ is odd.
I tried substitution by parts, but was not able to get anywhere. Setting $u = \sin^m(x)$ and $dv = \frac{dx}{x^n}$ when $n \not= 1$, I got $$\frac{\sin^m(x)}{(1-n)x^{n-1}}\Biggl|^\infty_0-\int_0^{\infty}\frac{m\cos(x)\sin^{m-1}(x)}{(1-n)x^{n-1}} dx=\frac{m}{n-1}\int_0^{\infty}\frac{\cos(x)\sin^{m-1}(x)}{x^{n-1}} dx$$
This seems just as bad, if not worse, than the original integral. Even when I tried setting $u$ and $dv$ to something else, I could not get something that looked easier to solve.

Switching tracks completely, I will try to use Feynman's trick (in a similar way as Mark Viola did in the top answer to the linked question). We can write $$F(s) = \int_0^{\infty} \frac{\sin^m(x)}{x^n} e^{-sx}dx$$
Differentiating $F(s)$ with respect to $s$, $n$ times, yields $$F^{(n)}(s) = \int_0^{\infty} (-1)^n e^{-sx}\sin^m(x) dx$$
The integral can be rewritten as a rational function, but I realized that it would become extremely messy to integrate that $n$ times. Because of this, I didn't even bother finding the analytical expression of this.

I found without proof that $I(2k+1, 1) = \frac{\binom{2k}{k}\pi}{2^{2k+1}}$
How can I solve the integral, whether by substitution by parts, Feynman's trick, or some other method?

A: In this essay, I had found a formula for the integrals with powers of the same parity.
$$
\boxed{\int_0^{\infty} \frac{\sin^{m}x}{x^{n}}dx=\frac{(-1)^{\frac{m-n}{2}} \pi}{2^{m}(n-1) !} \sum_{k=0}^{\left\lfloor\frac{m-1}{2}\right\rfloor}(-1)^{k}\left(\begin{array}{l}
m \\
k
\end{array}\right)(m-2 k)^{n-1}},
$$
$\text{where }m$ and $n$ are of the same parity and $2\leq n\leq m.$
In particular, when $m=n$, we had completed a formula for:
$$
\boxed{\int_{0}^{\infty} \frac{\sin ^{n} x}{x^{n}}=\frac{\pi}{2^{n}(n-1) !} \sum_{k=0}^{\left\lfloor\frac{n-1}{2}\right\rfloor}(-1)^{k}\left(\begin{array}{c}
n \\
k
\end{array}\right)(n-2 k)^{n-1}
}$$
$\textrm{where }n\in N.$
First of all, I start with the integral of even powers in both numerator and denominator. Let
$\displaystyle I(m, n):=\int \frac{\sin^{2m}x}{x^{2n}}dx,\tag*{}  $
where $0<n\leq m.$
Using the formula below, we first express $\sin^{2m}x$ as a linear combination of $\cos 2kx$, whose high derivatives can be easily found.
$$\sin ^{2 m} x=\frac{1}{2^{2 m-1}(-1)^{m}} \sum_{k=0}^{m-1}(-1)^{k}\left(\begin{array}{c}2m\\ k\end{array}\right) \cos (2 m-2 k) x+\frac{1}{2^{2m}} \left(\begin{array}{c}2 m \\ m\end{array}\right)\quad \text{(See footnotes for proof.)} $$
Now differentiate $\sin ^{2 m} x$ w.r.t. $x$ by $2n-1$ times.
$$\left(\sin ^{2 m} x\right)^{(2 n-1)}=\frac{1}{2^{2 m-1}(-1)^{m}} \sum_{k=0}^{m-1}(-1)^{k+1}\left(\begin{array}{c}2 m \\ k\end{array}\right)(-1)^{n-1}(2 m-2 k)^{2 n-1} \sin (2 m-2k)x$$
$$=\frac{(-1)^{m-n}}{2^{2 m-1}} \sum_{k=0}^{m-1}(-1)^{k}\left(\begin{array}{c}2 m \\ k\end{array}\right)(2 m-2 k)^{2 n-1} \sin (2 m-2 k) x$$
Applying integration by parts $2n-1$ times yields
$\displaystyle I(m, n)=\int_{0}^{\infty} \frac{\left(\sin ^{2 m} x\right)^{(2 n-1)}}{(2 n-1) ! x} d x \\ \\ \displaystyle \quad \qquad =\frac{(-1)^{m-n}}{2^{2 m-1}(2 n-1) !} \sum_{k=0}^{m-1}(-1)^{k}\left(\begin{array}{c}2 m \\ k\end{array}\right)(2 m-2 k)^{2 n-1} \int_{0}^{\infty} \frac{\sin (2 m-2 k) x}{x} d x$
Using the well-known result  $ \displaystyle \int_{0}^{\infty} \frac{\sin a x}{x} d x=\frac{\pi}{2}$ for any $a>0, $ we can conclude that
$$\displaystyle  I(m, n) =\frac{(-1)^{m-n} \pi}{2^{2 m}(2 n-1) !} \sum_{k=0}^{m-1}(-1)^{k}\left(\begin{array}{c}2 m \\ k\end{array}\right)(2 m-2 k)^{2 n-1}.\tag*{(1)}  $$
Now I come back to the integrals with odd powers $$J(m, n):=\int_{0}^{\infty} \frac{\sin ^{2 m+1} x}{x^{2 n+1}} d x$$
By the other similar formula for odd powers of sine:
$$\sin ^{2 m+1} x=\frac{1}{2^{2 m} (-1)^{m}} \sum_{k=0}^{m}(-1)^{k}\left(\begin{array}{c}2 m+1 \\ k\end{array}\right) \sin (2 m+1-2 k) x$$
We differentiate the equation w.r.t.$x$ by $2n$ times and get
$$\left(\sin ^{2 m+1} x\right)^{(2 n)}=\frac{(-1)^{m-n}}{2^{2 m}} \sum_{k=0}^{m}(-1)^{k}\left(\begin{array}{c}2 m+1 \\ k\end{array}\right)(2 m+1-2 k)^{2 n}\sin (2 m+1-2 k) x$$
Applying integration by parts $2n $ times yields
$$
\begin{array}{l}\displaystyle
\int_{0}^{\infty} \frac{\sin ^{2 m+1} x}{x^{2 n+1}} d x=\int_{0}^{\infty} \frac{\left(\sin ^{2 m+1} x\right)^{(2 n)}}{(2 n) ! x} d x
\end{array}
$$
Plugging the $2n^{th }$derivative gives
$$\begin{array}{l}
\displaystyle J(m,n) =\frac{(-1)^{m-n}}{2^{2 m}(2 n) !} \sum_{k=0}^{m}(-1)^{k}\left(\begin{array}{c}
2 m+1 \\
k
\end{array}\right)(2 m+1-2 k)^{2 n} \int_{0}^{\infty} \frac{\sin (2 m+1-2 k)}{x} \\
\\ \displaystyle \quad \qquad =\frac{(-1)^{m-n} \pi}{2^{2 m+1}(2 n) !} \sum_{k=0}^{m}(-1)^{k}\left(\begin{array}{c}
2 m+1 \\
k
\end{array}\right)(2 m+1-2 k)^{2 n}\tag*{(2)}
\end{array}$$
Merging the formula (1) and (2), we can now conclude in one single formula  that
$$
\boxed{\int_0^{\infty} \frac{\sin^{m}x}{x^{n}}dx=\frac{(-1)^{\frac{m-n}{2}} \pi}{2^{m}(n-1) !} \sum_{k=0}^{\left\lfloor\frac{m-1}{2}\right\rfloor}(-1)^{k}\left(\begin{array}{l}
m \\
k
\end{array}\right)(m-2 k)^{n-1}},
$$
In particular, when $m=n$, we had completed the formula for:
$$
\boxed{\int_{0}^{\infty} \frac{\sin ^{n} x}{x^{n}}=\frac{\pi}{2^{n}(n-1) !} \sum_{k=0}^{\left\lfloor\frac{n-1}{2}\right\rfloor}(-1)^{k}\left(\begin{array}{c}
n \\
k
\end{array}\right)(n-2 k)^{n-1}
}$$
$\textrm{where }n\in N.$
By the way, we can easily get any results by putting values of $n$ in the formula.  For example,
Example 1
\begin{aligned}
& \int_{0}^{\infty} \frac{\sin ^{7} x}{x^{3}} d x \\
=& \frac{(-1)^{\frac{7-3}{2}} \pi}{2^{7}(3-1) !} \sum_{k=0}^{3}(-1)^{k}\left(\begin{array}{l}
7 \\
k
\end{array}\right)(7-2 k)^{2} \\
=& \frac{\pi}{2^{8}}\left[\left(\begin{array}{l}
7 \\
0
\end{array}\right) 7^{2}-\left(\begin{array}{c}
7 \\
1
\end{array}\right) 5^{2}+\left(\begin{array}{l}
7 \\
2
\end{array}\right) 3^{2}-\left(\begin{array}{l}
7 \\
3
\end{array}\right) 1^{2}\right] \\
=& \frac{\pi}{2^{8}}(49-175+189-35) \\
=& \frac{7 \pi}{64}
\end{aligned}
Example 2
$$
\begin{array}{rl}
\displaystyle  \displaystyle \int_{0}^{\infty} \frac{\sin ^{9} x}{x^{9}} dx=\displaystyle \frac{\pi}{2^{9} \cdot 8 !}\left[\left(\begin{array}{l}
9 \\
0
\end{array}\right) 9^{8}-\left(\begin{array}{l}
9 \\
1
\end{array}\right) 7^{8}+\left(\begin{array}{l}
9 \\
2
\end{array}\right) 5^{8}-\left(\begin{array}{l}
9 \\
3
\end{array}\right) 3^{8}+\left(\begin{array}{l}
9 \\
4
\end{array}\right)\right]
\end{array}
\displaystyle =\frac{259723 \pi}{1146880}$$
Footnotes:

*

*Let $z=\cos \theta+i \sin \theta$, then
$\displaystyle \sin x=\frac{z-\bar{z}}{2 i}$ and

$\displaystyle \quad  \sin ^{2 n} x=\left(\frac{z-\overline{z}}{2 i}\right)^{2n}=\frac{1}{2^{n}(-1)^{n}} \sum_{k=0}^{2 n}\left(\begin{array}{c}2 n \\ k\end{array}\right) z^{2 n-k}\left(-\bar z\right)^{k}\\ \displaystyle \qquad  =\frac{1}{2^{2 n}(-1)^{n}} \left[\sum_{k=0}^{n-1}(-1)^{k}\left(\begin{array}{c}2 n \\ k\end{array}\right)\left(z^{2 n-2 k}+\bar z^{2 n-2 k}\right)+(-1)^n\left(\begin{array}{c}2 n \\ n\end{array}\right)\right]\\ \\ \displaystyle \qquad =\frac{1}{2^{2 n-1}(-1)^{n}} \sum_{k=0}^{n-1}(-1)^{k}\left(\begin{array}{c}2 n \\ k\end{array}\right) \cos (2 n-2 k) x+\frac{1}{2^{2n}} \left(\begin{array}{c}2 n \\ n\end{array}\right)$

*$\displaystyle \sin ^{2 n+1} x=\left(\frac{z-\bar{z}}{2 i}\right)^{2 n+1}$
$\displaystyle \quad \qquad\qquad =\frac{1}{2^{2 n+1}(-1)^{n} i} \sum_{k=0}^{2 n+1}\left(\begin{array}{c}2 n+1 \\ k\end{array}\right) z^{2 n+1-k}(-\bar{z})^{k}$
$\displaystyle \quad \qquad\qquad =\frac{1}{2^{2 n+1}(-1)^{n} i} \sum_{k=0}^{n}(-1)^{k}\left(\begin{array}{c}2 n+1 \\ k\end{array}\right)\left(z^{2 n+1-2 k}-\bar{z}^{2 n+1-2 k}\right)$
$\displaystyle \quad \qquad\qquad =\frac{1}{2^{2 n+1}(-1)^{n} i} \sum_{k=0}^{n}(-1)^{k}\left(\begin{array}{c}2 n+1 \\ k\end{array}\right) 2 i \sin (2 n+1-2 k) x$
$\displaystyle \quad \qquad\qquad =\frac{1}{2^{2 n} (-1)^{n}} \sum_{k=0}^{n}(-1)^{k}\left(\begin{array}{c}2 n+1 \\ k\end{array}\right) \sin (2 n+1-2 k) x$

A: I'm not certain if this helps but I thought of deriving a reduction formula,
$$I(m,n) = \int_0^{\infty}\frac{\sin^mx}{x^n}dx$$ Using Integration by Parts,
$$I(m,n) = -\frac{1}{(n-1)x^{n-1}}\sin^mx|_0^{\infty}+\int_0^{\infty}\frac{m\sin^{m-1}x\cos x}{(n-1)x^{n-1}}dx=\int_0^{\infty}\frac{m\sin^{m-1}x\cos x}{(n-1)x^{n-1}}dx$$The first term is $0$ since for convergence, we need $n \leq m$.
Using Integration by Parts once more,
$$\frac{n-1}{m}I(m,n) = -\frac{1}{(n-2)x^{n-2}}\sin^{m-1}x\cos x|_0^{\infty}+\int_0^{\infty}\frac{(m-1)\sin^{m-2}x\cos^2x-\sin^mx}{(n-2)x^{n-2}}dx$$
$$\therefore \frac{m-1}{n}I(m,n)=\frac{m-1}{n-2}\int_0^{\infty}\frac{\sin^{m-2}x(1-\sin^2x)}{x^{n-2}}dx-\frac{1}{n-2}I(m,n-2)$$
$$\frac{m-1}{n}I(m,n) =\frac{m-1}{n-2}\int_0^{\infty}\frac{\sin^{m-2}x}{x^{n-2}}dx-\frac{m-1}{n-2}\int_0^{\infty}\frac{\sin^mx}{x^{n-2}}dx-\frac{1}{n-2}I(m,n-2)$$
$$\therefore \frac{m-1}{n}I(m,n) =\frac{m-1}{n-2}I(m-2,n-2)-\frac{m-1}{n-2}I(m,n-2)-\frac{1}{n-2}I(m,n-2)$$
$$\therefore \frac{m-1}{n}I(m,n)=\frac{m-2}{n-2}I(m-2,n-2)-\frac{m-2}{n-2}I(m,n-2)$$
This only works if $n >1$ which ensures the first step.
Hopefully, this leads to something.


text:
Q: Define a list of strings in a Datatable cell for a field inside a Cucumber step in Java What I want
I am working with DataTables in Cucumber.
I have the following situation:
Step in the feature file:
I set the ingredients necessary for a meal
  | name           | ingredients        |
  | mac and cheese | pasta,cheese       |
  | hamburger      | bread,meat,lettuce |

In the StepDefinition file I have
@When("I set the ingredients necessary for a meal")
public void setIngredients(List<Meal> meals){
  //do things with it
}

And I have a class Meal
public class Meal {
  String name;
  List<String> ingredients;
}

This doesn't work.
what I know
If I set my ingredients field as a simple String Cucumber "magically" matches both name and ingredients to the fields of the class and, in the step definition I will get a List of Meals correctly filled.
But as it currently is it doesn't automatically match.
What I tried
I tried defining the class as:
public class Meal {
  String name;
  String ingredients;
  List<String> ingredientsList;
}

*

*And having a constructor Meal(String, String) that would parse the ingredients into the ingredients list, but it doesn't work.

*I tried defining a setter for ingredients that would parse it and also define the ingredientsList but it also doesn't work.

*I tried using a DataTable in the step definition but still I can't find a way to transform it into my list of ingredients.

*I tried using Transformer but, AFAIK, I would have to define a step for each meal I want to serve and I would have to sent the values within the step itself.
What I don't want
I don't want to be forced to parse the information anywhere but the Meal class.
How I temporarily solved it
Within the more complete Meal definition, a defined a setIngredientsList() that parses the ingredients into a list.
On the step definition, I iterate through the list of meals and call setIngredientsList for each of them. As I said, I don't want any of this processing done outside of the Meal class.
Question
Does anyone know how I can do this please?

A: I would consider using a Map<String, String> instead of a list. Looking at your examples looks like name value pairs to me. A map might be a good fit.
When your fields are package private in Meal you probably don't need a constructor. I would, however, hide them as private variables and add a two parameter constructor. The habit of exposing as little as possible tend to support long term maintenace.
I wrote a blog post a while back that might help you.

A: You can use the @XStreamConverter annotation to register your XStream converter class.
The column names in the datatable and fields in the desired POJO need to be the same for Cucumber to assign them values.
Create a converter by extending AbstractSingleValueConverter for the parsing logic.
public class IngredientConverter extends AbstractSingleValueConverter {

    @Override
    public boolean canConvert(Class type) {
        return type.equals(ArrayList.class);
    }

    @Override
    public Object fromString(String ingreds) {
        return Arrays.asList(ingreds.split(","));
    }
}

Annotate the ingredients field with @XStreamConverter(IngredientConverter.class)
public class Meal {

    private String name;

    @XStreamConverter(IngredientConverter.class)
    private List<String> ingredients;

    public String getName() {
        return name;
    }

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

    public List<String> getIngredients() {
        return ingredients;
    }

    public void setIngredients(List<String> ingredients) {
        this.ingredients = ingredients;
    }
}

If you are using Cucumber2 then look at these two links which allow global registration of custom xstreamconverters. These are now part of official cucumber release. Link 1 Link 2


text:
Q: Eloquent ORM returns null using with() eager load When using Eloquent's with() the eager loaded data sometimes becomes null. In my case, I have three tables, Users, Blogposts and Categories. The blogposts table has two foreign keys, called author and category. The query performed is given by
return Blogpost::with(['author', 'category'])->get();

The response is, well, odd. Note that author becomes null from id: 3 and category from id: 4.
In reality both the ids 1, 3 have the same author (superuser) as do the ids 2, 4 (steve). Also id 1, 4 have the same category (web dev).
It seems as if a/an category/author is already retrived and bounded to a blogpost the past categories/authors becomes null.
[
  {
    id: 4,
    author: null,
    image_name: "banner1.png",
    category: null,
    intro: "Hello World!",
  },

  {
    id: 3,
    author: null,
    image_name: "banner1.png",
    category: {
        id: 3,
        name: "big data",
    },
    intro: "Hello World!",
  },

  {
    id: 2,
    author: {
        id: 2,
        email: "foo@foo.foo",
        fullname: "foo foo",
        is_admin: false,
    },
    image_name: "banner1.png",
    category: {
        id: 2,
        name: "science",
    },
    intro: "Hello World!",
  },

  {
    id: 1,
    author: {
        id: 1,
        email: "superuser@superuser.com",
        fullname: "superuser superuser",
        is_admin: true,
    },
    image_name: "banner1.png",
    category: {
        id: 1,
        name: "web dev",
    },
    intro: "Hello World!",
  }
]

Finally here are the relations defined in the models
// User model
public function blogposts() {
    return $this->hasMany('App\Blogpost', 'id');
}

// Blogpost model
public function author() {
  return $this->belongsTo('App\User', 'id');
}

public function category() {
  return $this->belongsTo('App\Category', 'id');
}

// Category model
public function blogposts() {
  return $this->hasMany('App\Blogpost', 'id');
}

Is there any explanation to this?

A: It appears the fault was in the model definitions, here are the corrected models.
// User model
public function blogposts() {
   return $this->hasMany('App\Blogpost', 'id', 'author');
}

// Blogpost model
public function author() {
  return $this->belongsTo('App\User', 'author', 'id');
}

public function category() {
  return $this->belongsTo('App\Category', 'category', 'id');
}

// Category model
public function blogposts() {
  return $this->hasMany('App\Blogpost', 'id', 'category');
}


text:
Q: java.lang.NullPointerException: While displaying all my user files I'm trying to display all my user files using java as follows...
 public static String Tree(File file)
{
    if(file.isDirectory()==true)
    {
        File fr[]=file.listFiles();
        No_fold++;
        for(int i=0;i<fr.length;i++)
        {
            Tree(fr[i]);
        }
    }
    else
    {
        X+=file.getPath()+"\n";
        No_files++;
    }
    return X;
}

works perfectly while displaying my documents files...
But the following exception is thrown while trying to display the files from C:/Users/username
at com.monster.app.__SHELL137.run(__SHELL137.java:9)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at bluej.runtime.ExecServer$3.run(ExecServer.java:725)

Please help me regarding this..
Thnk U

A: The documentation for File.listFiles() says,

An array of abstract pathnames denoting the files and directories in the directory denoted by this abstract pathname. The array will be empty if the directory is empty. Returns null if this abstract pathname does not denote a directory, or if an I/O error occurs.

So, there are only 2 cases when the returned value of listFiles() is null

*

*The abstract pathname does not denote a directory

*I/O error occurs

Since you are making sure that file is a directory I suspect that there is an I/O error.
You have said,

works perfectly while displaying my documents files... But the following exception is thrown while trying to display the files from C:/Users/username

I think there is some directory inside C:/Users/username or its subdirectories which is not readable by you and is causing an I/O error.