Set back date when creating posts in Wordpress - current_time()

Question: Is it possible to somehow setback the date of the current_time function in wordpress?
Right now i am using it like this:
$time = current_time('mysql');

I would like to get the same year, month and time.. but set back the day with for example 2.
Any ideas guys? :)
Thanks
Answer: function days_ago($days, $type, $gmt=0) {
    $time = $gmt? time() : time() + ( get_option('gmt_offset')*3600 );
    $d = explode('-', date('H-i-s-n-j', $time));
    $time = mktime($d[0], $d[1], $d[2], $d[3], $d[4]-$days);
    return $type=='mysql'? gmdate('Y-m-d H:i:s', $time) : $time;
}

It works just like current_time(), except that you pass it a number of days:
$time = days_ago(2, 'mysql');

Note that if you didn't need the $type and $gmt options that current_time() provides, you could use this instead:
function days_ago($days) {
    $d = explode('-', date('H-i-s-n-j'));
    return date('Y-m-d H:i:s', mktime($d[0], $d[1], $d[2], $d[3], $d[4]-$days));
}

$time = days_ago(2);


RAID1: Migrate HDD to SSD?

Question: My current workstation uses an Adaptec 5805, with Win2008 mirrored between two 72 GB (10K?) savvio drives.
My question is if there's a way to migrate the mirror to use SSDs - I've been looking at 90GB Corsair Force (Sandy Bridge) to replace the existing setup.  If it's possible, without installing the OS fresh.
If I replaced the mirrored drive with an SSD, would the array sync the drives?  Then I could promote the SSD mirror to be the primary, and use the second SSD as the mirror.  That'd be too easy...
Or should use Ghost to get an image of the existing setup, apply it to the SSD for a new mirror to be setup on?
Answer:
If I replaced the mirrored drive with
  an SSD, would the array sync the
  drives?

Yes. And it should turn it into a hybrid raid. No need to use a second SSD then, pretty much. Adaptec has special support for hybrid RAID 10 / mirrors. ALl writes go to both discs, all (!) reads only to the SSD. Cheaper, nearly same perforamnce unless you do a lot of writes, which you normall dont on a OS.
But the old disc somewhere else and kill the parittions then, then you can reuse it ;)
Comment: These Adaptec Hybrid RAID still don't appear to support TRIM so you will see degredation in speed compared to a single SSD.
Comment: I want the RAID array to be a matched pair of drives, ultimately.
Comment: So you like wasted money? No joke - Adapted has some very interesting white papers re performance of hybris drives.

RAID1: Migrate HDD to SSD?


Trying to enter an argument with multiple words into a Views argument

Question: I'm using Organic Groups with Views in Drupal 7  with OG Tokens to create a view which returns all content with a type associated with it, so groups/foo/article would return all articles where the content type is article and the group is foo. This works fine for a group audience where the audience is one word, such as foo, or two run together without spaces, such as FooBar. However when I create a group like foo-bar, the view returns the no content page even when there is content attached the group. The contextual filter that I am using is OG Group: Label.
I've tried putting PHP to explode the results in the 'WHEN THE FILTER VALUE IS IN THE URL OR A DEFAULT IS PROVIDED', following the posts that I've seen but although I can see it printing out the "foo bar", it is not calling the types attached to the group. Is there somewhere else that I can explode this data and remove the spaces so that the group details can be presented in the view, or even look at the query to see what is being passed into it by the argument?
Thanks for your help and time.
UPDATE:
Having run a slightly orthogonal search, i came across the following code:
    $handler->argument = str_replace('_', ' ', $argument);
    return TRUE;

Having replaced the underscore with a dash, the multi-worded OG audience type can be used as I outlined above. Put the code into the "PHP Validate" code on the specify validation code and apply. The original came from PixelClever . I'll mark as answered when the site allows me to do so as I don't have enough user points to do so immediately.
Answer:
If the arguments are not in a taxonomy term then add a vocabulary to contain them
Under the contextual filter section for When the filter value is in the URL check validation, set it to a Taxonomy term  and pick the vocabulary.
Select the Filter type or term name from the term ID
Check the box for Transform Dashes.

The view should now read the name from the URL and access the term id.
Comment: I'm going to give it a go. I'm trying to get the content types related to the group (so all articles for that group for example) and don't quite see how adding a taxonomy term would help as it sets up the relationship between term id and type rather than group membership and type
Comment: Having run a slightly orthogonal search, i came across the following code:
Comment: What code?  I see your problem.  I was thinking the problem is that the URL has dashes between words (unless you set it otherwise) and will not compare with words with spaces. The only way I know to get Views to read a multi-word URL is with Taxonomies. Its kind of a hack, but....
Comment: the code is in the above Update with the answer which I found to solve the problem in this case. Thanks for your suggestion though which I'm keeping in mind for something else.
Comment: Thanks for your research, I have been looking in the code for how to address URLS in views for several problems, and here is an answer right in the view!


Is it possible to generate an URL object from a path?

Question: Can I generate a
https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Url.php/class/Url/8.2.x
from a simple path, e.g. "/products/widget" ?
(assume /products/widget exists in the system and is a canonical path)
Answer: Use Url:fromRoute () and pass in the route's name and arguments. You can also use fromUri() for external paths. https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Url.php/function/Url%3A%3AfromRoute/8.2.x
I usually find the route name by searching the routing.yml files for the path.
Alternately, you can do this. How to get the Route object from an URI?


Rademacher random variables in terms of Bernoulli

Question: I've found out that Rademacher random variables and Bernoulli random variables plays an important role in Probability theory. I am wondering how they are connected. For example,
Let $r_i, i=1, \ldots, n$ be Rademacher random variables, such that $P(r_i=1)=a$ and $P(r_i=-1)=1-a$.
Let $b_i, i=1, \ldots, n$ be Bernoulli random variables, such that $P(b_i=1)=b$ and $P(b_i=0)=1-b$.
Let $x_i, i=1, \ldots, n$ be real numbers.
Consider $A=\sum_{i=1}^nx_ir_i$.
How to represent $A$ in terms of $B=\sum_{i=1}^nx_ib_i$? What is the relation between $a$ and $b$?
Thank you.
Answer: Hints:
If $r_i$ is a Rademacher random variable, then consider $\dfrac{r_i+1}{2}$.
Now consider  $\displaystyle\sum_i x_i \dfrac{r_i+1}{2}$ or equivalently $\dfrac{\displaystyle\sum_i x_i r_i}{2} + \dfrac{\displaystyle\sum_i x_i }{2}$.


how to create task takening in account build flavors

Question: task wsUpload(type: Exec) {
  commandLine '../scripts/ws_upload.sh'
  args = [rootProject.ext.VERSION_CODE]

  crashlyticsUploadDistributionMinAPI16ProdRelease
}

wsUpload is defined outside and block at the bottom of app/build.gradle file
I want it to execute ws_upload.sh script and then upload apk to fabric beta.
In android block i have several  productFlavors
flavorDimensions "api", "mode"
  productFlavors {
    // Define separate dev and prod product flavors.
    dev {
    }
    prod {
    }
    minAPI21 {
    }
    minAPI16 {
    }
  }

However when I try to sync I am getting Error:(150, 0) Could not get unknown property 'crashlyticsUploadDistributionMinAPI16ProdRelease' for task ':app:wsUpload' of type org.gradle.api.tasks.Exec.
Answer: Exec Task doesn't know what is crashlyticsUploadDistributionMinAPI16ProdRelease
The properties that Exec task handles are here
If you want to create a Custom task, you can do so please refer to docs
Comment: This property name generated after evaluation of product flavors and build variants. crashlyticsUploadDistribution default task name provided by crashlitics, MinAPI16Prod - product flavor ,Release build variant.  I assumed that properties for all combinations should exist, but seems it is not the case.
Comment: I'm not sure but even if, your task is a Type of `Exec` which accepts only the above properties. if you want to use different properties you need a task that is going to accepts that property.


About the GMRFlib

Question: I am trying to access the GMRFlib as mentioned in the link http://www.math.ntnu.no/~hrue/GMRFsim/doc/html/. However, I think it is not available anymore. I couldn't see the tarball mentioned. Does anyone have access to it?
Answer: Its author has incorporated it into a Google Code project: http://code.google.com/p/inla/source/browse/gmrflib

About the GMRFlib


Firefox Not Responding to .addClass

Question: There's a couple things I'm trying to make happen with a sticky nav on a website. I have it working in all browsers, except Firefox.

I want the links to change as the window scrolls.
I want to add a class to change the navigation at a certain point.

Here's the code that's been working in Chrome:

Snap

Organize

Store

Unify

Share

Get it on Google Play

Download on the App Store

The Javascript/jQuery
// Auto Nav Active Switching
var nav = $('#nav-sticky-wrapper').height();
var navh = nav+1;
var b = $('section#b').offset().top - navh;
var c = $('section#c').offset().top - navh;
var d = $('section#d').offset().top - navh;
var e = $('section#e').offset().top - navh;
var f = $('section#f').offset().top - navh;
var remove = $('nav ul li a');

setInterval(function() {
    if ( $(window).scrollTop() < b ) {
        $('section#nav ul').removeClass('stuck');
        $('section#nav ul li.sticky-dl').fadeOut(250);
    } else {
        $('section#nav ul').addClass('stuck');
        $('section#nav ul li.sticky-dl').fadeIn(250);
    }

    if ( $(window).scrollTop() < c ) {
        $(remove).removeClass('active');
        $('#nb').addClass('active');
    } else if ( $(window).scrollTop() >= c && $(window).scrollTop() < d ) {
        $(remove).removeClass('active');
        $('#nc').addClass('active');
    } else if ( $(window).scrollTop() >= d && $(window).scrollTop() < e ) {
        $(remove).removeClass('active');
        $('#nd').addClass('active');
        //bonusoff();
    } else if ( $(window).scrollTop() >= e && $(window).scrollTop() < f ) {
        $(remove).removeClass('active');
        $('#ne').addClass('active');
        // Runs Bonus Animation upon Entry
        bonus();
    } else if ( $(window).scrollTop() >= f ) {
        $(remove).removeClass('active');
        $('#nf').addClass('active');
    }

});

Does Firefox not respond to setInterval or something? Thanks in advance!
Comment: `setInterval` requires a ** delay time** to wait. What is the delay you want? ex: `setInterval(function(){...}, 3000);`
Comment: @SimchaKhabinsky Thanks a ton! That fixed the problem right away. I wish I had enough rep to upvote your answer. Thanks for the awesome answer. :)
Comment: Could you make a JSFiddle?
Comment: You can still set my answer is "The Answer" ;-)
Answer: setInterval requires a ** delay time** to wait. What is the delay you want? ex: setInterval(function(){...}, 3000);

Firefox Not Responding to .addClass


MySQL Sum Problem

Question: I have table a and b.

a has order_id and ship_total
b has order_id, item, qty, and price

How do I query and get the sum of all ship_total on all orders that have a total qty under 100?
I am afraid if I do something like this, it's going to be wrong.
select SUM(ship_total) FROM a as a inner join b as b on a.order_id=b.order_id WHERE SUM(qty) < 100 GROUP BY a.order_id

Any help would be greatly appreciated!
I've tried the answers from below and it's not adding everything together.  It's giving me the shipping amount from each order.
Comment: In other words (contrary to the current list of answers), what you really want is the grand-total of all the orders, not separate totals of the individual orders.
Comment: @X-Zero This is correct.
Comment: I inadvertently added a `GROUP BY` to my answers earlier, but have removed them now. Give them a shot and let me know if they don't do what you want.
Answer: One way:
SELECT
    SUM(A.ship_total)
FROM
    (SELECT B.order_id FROM B GROUP BY B.order_id HAVING SUM(qty) < 100) SQ
INNER JOIN A ON
    A.order_id = SQ.order_id

Another way:
SELECT
    SUM(A.ship_total)
FROM
    A
WHERE
    order_id IN (
        SELECT order_id
        FROM B
        GROUP BY order_id
        HAVING SUM(qty) < 100)

Try each out and see which performs best for you.
Answer: You're close. When you want to limit results that are aggregated, you need to use the HAVING clause.
select SUM(ship_total)
FROM a as a
inner join b as b
  on a.order_id=b.order_id
GROUP BY a.order_id
having SUM(qty) < 100

MySQL Sum Problem


Azure: cloned disk, can't bring online

Question: I have an Azure server on which I now realize I'm paying a fortune for a 1TB SSD, when in reality I only need about 400GB of HDD.
I took a snapshot of the SSD and stored it in Azure, then created a new HDD. Azure wouldn't let me make the new disk smaller than 1 TB, since that was the snapshot size, so...OK, at least I'll save on HDD vs SSD.
So I attached this new drive to my server, but now for some reason I can't bring it online:

"Access denied"?! But I'm the guy who created it, and I'm logged in as a Windows admin.
Maybe it's a conflict with the drive letter? My current drive is labeled F:, so maybe the snapshot also wants to force this new drive to be F:? So I tried detaching the existing drive, but that didn't help, either.
So, how do I attach this drive? (Bonus points if you can tell me how to shrink the size of the new disk, too.)
Answer: Turns out there's an easy way to change the disk from SSD to HDD, if you're using managed disks. Just shut down the VM, then in the Azure console, open the disk and select "configuration":

(Note: I took this snapshot while my VM was running, so it's disabled here, but this was really simple to do in the end.)

Azure: cloned disk, can't bring online


Isomorphism of quotient ring of polynomial ring

Question: Are $F_3[x]/(x^2-2)$ and $F_3[x]/(x^2-2x-1)$ isomorphic?
I know that $x^2-2$ and $x^2-2x-1$ are irreducible but how to determine if they are isomorphic or not?
Here, $F_3$ means finite field of order 3.
Answer: One of the most important facts about finite fields is that all finite fields of the same size are isomorphic!
Finding the isomorphism can be a little trickier. For a problem expressed like yours, the most direct approach would be something like finding a root of the polynomial $t^2 - 2$ in the field $\mathbf{F}_3[x] / (x^2 - 2x - 1)$.
Aside: it sometimes helps to use different indeterminate variables to keep everything straight: e.g. let your two fields be $\mathbf{F}_3[x]/(x^2 - 2)$ and $\mathbf{F}_3[y]/(y^2 - 2y - 1)$.
Answer: Hint: Note that $x^2-2x-1 = (x-1)^2 - 2$. Does this suggest an isomorphism?
Answer: There's a well known result about finite fields which states that finite fields are completely determined by their cardinality.
As you said the two polynomials are irreducible hence the quotient are two $F_3$ vector spaces of dimension $2$ and so they have both cardinality $3^2=9$.
By the theorem I've named above it follows that such fields must be isomorphic.


How can I replicate the process sklearn calculates the posterior probabilities?

Question: I have a question pertaining to scikit-learn methods.
Can I get the same probabilities obtained with predict_log_proba() by hand calculating the likelihoods and prior obtained with feature_log_prob_ and class_log_prior_?
After obtaining likelhoods and prior, I summed the likelihoods and prior in an attempt to get posterior but the values given by predict_log_proba() are different.
Comment: This will depend on the model implementation, which model are you using?
Comment: @Gijs, my apology, I missed out the model!! I am using multinomial.
Answer: I resolved it by building my own MultinomialNB and understood how posteriors are calculated.
Although I could still not replicate the process by using sklearn, building it helped answer alot.
If anyone would like to know the detail of calculation, I post my code below. Hope it helps.
import numpy as np
class multinomialNB:
    def init(self, alpha=1):
        self.alpha = alpha
<code>def fit(self, X_train, y_train):
    m, n = X_train.shape
    self._classes = np.unique(y_train)
    n_classes = len(self._classes)

    # init: Prior & Likelihood
    self._priors = np.zeros(n_classes)
    self._likelihoods = np.zeros((n_classes, n))

    # Get Prior and Likelihood
    for idx, c in enumerate(self._classes):
        X_train_c = X_train[c == y_train]
        self._priors[idx] = X_train_c.shape[0] / m
        self._likelihoods[idx, :] = ((X_train_c.sum(axis=0)) + self.alpha) / (np.sum(X_train_c.sum(axis=0) + self.alpha))

def predict(self, X_test):
    return [self._predict(x_test) for x_test in X_test]

def _predict(self, x_test):
    # Calculate posterior for each class
    posteriors = []
    for idx, c in enumerate(self._classes):
        prior_c = np.log(self._priors[idx])
         # You need to add piece of code that filters out the features presented or not for the test sample
        likelihoods_c = self.calc_likelihood(self._likelihoods[idx,:], x_test)
        posteriors_c = np.sum(likelihoods_c) + prior_c
        posteriors.append(posteriors_c)

    return self._classes[np.argmax(posteriors)]

def calc_likelihood(self, cls_likeli, x_test):
    return np.log(cls_likeli) * x_test

def score(self, X_test, y_test):
    y_pred = self.predict(X_test)
    return np.sum(y_pred == y_test)/len(y_test)
</code>


Not able to access 'task' object in workflow service task

Question: I am able to access "task" object in workflow user tasks.
<userTask id="usertask1" name="Manager Approval" activiti:candidateGroups="GROUP_ALFRESCO_MANAGERS" activiti:formKey="tcdr:managerForDeleteApproval">
        <extensionElements>
            <activiti:taskListener event="complete" class="org.alfresco.repo.workflow.activiti.tasklistener.ScriptTaskListener">
              <activiti:field name="script">
                  <activiti:string>
                  logger.log(task.getName());
                  </activiti:string>
              </activiti:field>
            </activiti:taskListener>
        </extensionElements>
    </userTask>

I am not able to access "task" object in workflow service task,
it's giving error of "task not defined".
<serviceTask id="scripttask2" name="Submit" activiti:class="org.alfresco.repo.workflow.activiti.script.AlfrescoScriptDelegate">
      <extensionElements>
        <activiti:field name="script">
          <activiti:string><![CDATA[
          logger.log(task.getName());
          ]]></activiti:string>
        </activiti:field>
      </extensionElements>
    </serviceTask>

Answer: Try to use execution instead task, I had the same problem with startTask, but I'm not sure if it will work with seviceTask
Comment: Thank you ,for your reply I will try and  update you soon.


Prove that $(0, 1)$ is open if we call $U$ in $\mathbb R$ open if $\forall x\in U\ \exists \epsilon>0, (x - \epsilon , x + \epsilon) \subseteq U$.

Question: Hey guys I am new to discrete math and as an exercise I am supposed to prove that $(0,1)$ is an open set by considering the a subset $U\subseteq \mathbb R$ open if
$$\forall x\in U\ \exists \epsilon>0, (x - \epsilon , x + \epsilon) \subseteq U.$$
My textbooks suggests that answer requires setting $\epsilon$ to $\min\{t, t-1\}$ which really doesnt make any sense to me, any help on this would be great! Thank you! Sorry if my $\LaTeX$ is off, I am using a computer that does not display it on the screen before you post the question
Comment: What's $t$?It's related to $x$?
Answer: Let $t\in(0,1)$, so $0<t<1$. Then the choice $\epsilon=\min\{t,1-t\}$ first of all guarantees that $\epsilon>0$ (because $t>0$ and $1-t>1-1=0$) as required. Moreover, $t-\epsilon\ge 0$ because $\epsilon\le t$ and $t+\epsilon\le 1$ because $\epsilon\le 1-t$ (recall that $\min\{u,v\}$ is $\le u$ and $\le v$). So the interval $(t-\epsilon,t+\epsilon)$ has its left end $\ge 0$ and its right end $\le 1$, which means that $(t-\epsilon,t+\epsilon)\subseteq (0,1)$.
Comment: thank you! This makes a lot more sense
Comment: Shouldn't we set =min{/2,(1−)/2}. For instance, if we consider t = 0.5 then  = 0.5, that would give us an epsilon ball that would touch (Include) 0 and 1, but we have to show epsilon ball around any point has to be in (0,1), so it can't touch 0 and 1?
Answer: So we are after proving $(0,1)$ is open. Let $x \in (0,1)$, fix $\epsilon = \min\{x, 1-x\}$ and see if the definition fits...


In Java is Permanent Generation space garbage collected?

Question: I have read that Perm gen (or Permanent Generation) space is not garbage collected. However, in CMS collection I can see some classes unloading in my GC log. So is perm gen garbage collected during full collection or CMS collection?
Comment: no its not duplicate at all. This is a concept question asks for Yes/No answer, not a question seeking solution for an error.
Comment: Possible duplicate of http://stackoverflow.com/questions/88235/how-to-deal-with-java-lang-outofmemoryerror-permgen-space-error ? Anyway check that thread it will help for sure.
Answer: The PermGen is garbage collected like the other parts of the heap.
The thing to note here is that the PermGen contains meta-data of the classes and the objects i.e. pointers into the rest of the heap where the objects are allocated. The PermGen also contains Class-loaders which have to be manually destroyed at the end of their use else they stay in memory and also keep holding references to their objects on the heap. The "Presenting the Permanent Generation" article by Jon Masamitsu on the Sun / Oracle blog site might help you.
Comment: I've inlined the title and author so that people can find it if the link breaks again.
Comment: Corrected. It was a Sun blog so it is now an Oracle blog :)
Comment: Permgen is not part of heap
Comment: People are always mess up with native heap and java heap. PermGen is in native heap within java process. I think by using the term heap they sometimes mean java and native heap.
Comment: PermGen also has String Pool.
Answer: In recent JVMs prior to Java 8, permgen is indeed collected like other parts of the heap.  The visualgc page states that it is collected together with the old generation.
In older JVMs this was apparently not always so.  For instance, in Java 5 the CMS collector apparently did not collect permGen by default: you could enable it with <code>-XX:+CMSPermGenSweepingEnabled</code>.  I also recall hearing that some really old JVMs did not implement permgen collection at all, though I cannot find a reliable source for this ... ermm ... "factoid".
The other point, is that a lot of people used to incorrectly attribute "OutOfMemoryError : permgen" exceptions to permgen not being collected at all.  The reality is different.  The most common cause of permgen OOME's is an insidious kind of storage leak that manifests when you hot-load code into an executing JVM.  The leak occurs because when an instance of some old class that has been replaced remains reachable.  This causes the object's class to be reachable, which causes the classes classloader to be reachable, which causes all of the old classes to be reachable, together with their code objects, their string literals, and their static frames and static.  A lot of these leaked objects live in permgen space.

As of Java 8, permgen no longer exists: PermGen elimination in JDK 8


About Riemann integrability

Question: I need to prove if $f$ is continuous on an interval $I$, then its Riemann integral exists.
It is hard for me because it is an interval and not closed interval.
Can anyone give me some answers or clues? Thanks!
It is an exercise from this book: Measure and Integral An introduction to real analysis by Richard L. Wheeden.
Comment: The result is false for intervals in general hence the book *must* mean "closed interval".
Comment: Take $f(x)=\frac1x$ on $I=(0,1)$. Its Riemann integral does not exist.
Comment: I am confused because it is an exercise in this book: Measure and Integral An introduction to real analysis by Richard L. Wheeden.
Comment: Does the exercise mean closed interval when it says interval?
Comment: I edited it and it is exactly what the exercise says.
Comment: Hint: If $f$ is continious on a closed interval then it's uniformly continuous.
Comment: Read the bottom of the page 11$\,$: $I$ is supposed compact $\dots$
Answer: Note that $I$ is compact.
By theorem 1.15 (ii)$\,$ there exist $\;\mathbf x_{1k}\,,\mathbf x_{2k} \in I_k\,$ such that $$U_\Gamma=\sum_{k=1}^N f(\mathbf x_{1k})\,v(I_k)$$ and $$L_\Gamma=\sum_{k=1}^N f(\mathbf x_{2k})\,v(I_k)$$ Theorem 1.15 (iii) assures that for every $\varepsilon>0$ ther exists $\delta>0$ such that $$|f(\mathbf x)-f(\mathbf y)|<\frac \varepsilon {v(I)}$$ if $\;|\mathbf x-\mathbf y|<\delta\,$ and $\,\mathbf x,\mathbf y \in I\,$.
So, if $\,|\Gamma|<\delta$, then $$\inf_{\Gamma}\,U_{\Gamma}-\sup_{\Gamma}\,L_{\Gamma}\, \le \,
U_{\Gamma}-L_{\Gamma}=\sum_{k=1}^N \;[f(\mathbf x_{1k})-f(\mathbf x_{2k})]\;v(I_k)<\varepsilon$$ because $$v(I)=\sum_{k=1}^N \,v(I_k)$$Since in every case $$\inf_{\Gamma}\,U_{\Gamma}-\sup_{\Gamma}\,L_{\Gamma}\ge 0$$ the arbitrariness of $\varepsilon$ gives $$\inf_{\Gamma}\,U_{\Gamma}=\sup_{\Gamma}\,L_{\Gamma}$$

About Riemann integrability


Unable to resize lvm to max of vda

Question: I am trying to resize my lvm partition frm 29GB to ~60GB. Here is my current status:
root@demo:~# lsblk
NAME                      MAJ:MIN RM   SIZE RO TYPE MOUNTPOINT
loop0                       7:0    0    99M  1 loop /snap/core/11081
loop1                       7:1    0  99.2M  1 loop /snap/core/11167
loop2                       7:2    0  55.4M  1 loop /snap/core18/2066
loop3                       7:3    0  55.5M  1 loop /snap/core18/1997
loop4                       7:4    0 125.9M  1 loop /snap/docker/471
loop5                       7:5    0 131.6M  1 loop /snap/docker/796
loop6                       7:6    0  70.4M  1 loop /snap/lxd/19647
loop7                       7:7    0  32.1M  1 loop /snap/snapd/12057
loop8                       7:8    0  32.1M  1 loop /snap/snapd/11841
loop9                       7:9    0  67.6M  1 loop /snap/lxd/20326
sr0                        11:0    1  1024M  0 rom
vda                       252:0    0    60G  0 disk
├─vda1                    252:1    0     1M  0 part
├─vda2                    252:2    0     1G  0 part /boot
└─vda3                    252:3    0    59G  0 part
  └─ubuntu--vg-ubuntu--lv 253:0    0    29G  0 lvm  /

As you can observe, my vda3 is 59G and my lvm is 29G. When I run the following commands I am unable to resize the lvm to ~59G.
root@demo:~# lvextend -l +100%FREE /dev/mapper/ubuntu--vg-ubuntu--lv
  New size (7423 extents) matches existing size (7423 extents).
root@demo:~# resize2fs /dev/mapper/ubuntu--vg-ubuntu--lv
resize2fs 1.45.5 (07-Jan-2020)
The filesystem is already 7601152 (4k) blocks long.  Nothing to do!

root@demo:~#

How can I fix it?
Later edits:
root@demo:~# vgs
  VG        #PV #LV #SN Attr   VSize   VFree
  ubuntu-vg   1   1   0 wz--n- <29.00g    0

Comment: What is the size of the volume group (`vgs`)?
Comment: @eblock   ubuntu-vg   1   1   0 wz--n- <29.00g    0
Comment: Then you need to extend the volume group first.
Comment: @eblock `pvresize /dev/vda3` did the trick
Answer: Apprently it worked with:
root@demo:~# lsblk
NAME                      MAJ:MIN RM   SIZE RO TYPE MOUNTPOINT
loop0                       7:0    0    99M  1 loop /snap/core/11081
loop1                       7:1    0  99.2M  1 loop /snap/core/11167
loop2                       7:2    0  55.4M  1 loop /snap/core18/2066
loop3                       7:3    0  55.5M  1 loop /snap/core18/1997
loop4                       7:4    0 125.9M  1 loop /snap/docker/471
loop5                       7:5    0 131.6M  1 loop /snap/docker/796
loop6                       7:6    0  70.4M  1 loop /snap/lxd/19647
loop7                       7:7    0  32.1M  1 loop /snap/snapd/12057
loop8                       7:8    0  32.1M  1 loop /snap/snapd/11841
loop9                       7:9    0  67.6M  1 loop /snap/lxd/20326
sr0                        11:0    1  1024M  0 rom
vda                       252:0    0    60G  0 disk
├─vda1                    252:1    0     1M  0 part
├─vda2                    252:2    0     1G  0 part /boot
└─vda3                    252:3    0    59G  0 part
  └─ubuntu--vg-ubuntu--lv 253:0    0    29G  0 lvm  /
root@demo:~# pvresize /dev/vda3
  Physical volume "/dev/vda3" changed
  1 physical volume(s) resized or updated / 0 physical volume(s) not resized
root@demo:~# vgs
  VG        #PV #LV #SN Attr   VSize   VFree
  ubuntu-vg   1   1   0 wz--n- <59.00g 30.00g
root@demo:~# lvextend -r -l +100%FREE /dev/mapper/ubuntu--vg-ubuntu--lv

Unable to resize lvm to max of vda


How to Resolve Write Conflict w/ Unbound Access Form

Question: Have searched around and not yet found a solution that seems to fit. Perhaps someone here can offer some ideas.
Background
Application built in MS Access 2010 with tables linked to Access 2010 database, may eventually link.
Form contains an 'edit' section (unbound) and a 'list' section (bound sub-form).
Many forms of this type are used throughout the application.
All forms use a common UpsertRecord() method to insert/update records based on their respective fields.
Issue
When the 'Save' button is clicked, the Write Conflict error is displayed.

Write Conflict
This record has been changed by another user since you started editing it. If you save the record, you will overwrite the changes the other user made.
  Copying the changes to the clipboard will let you look at the values the other user entered, and then paste your changes back in if you decide to make changes.

The line triggering the error is where the form recordsource is set to a SQL string.
.RecordSource = strSQL

My Interpretation
Although the form could directly update the bottom subform list without clicking 'Save', this is not desirable to avoid users inadvertently changing data.
So, I'm attempting to force the 'Save' through the click event which in turn calls the common public UpsertRecord() method for saving the data. That method works fine, however triggers the Write Conflict since the form believes it is also changing the data by itself (w/o the 'Save' click).
Solutions Attempted
I've attempted to set a private variable m_SaveOK to prevent saves w/o the button click event by using the Form_BeforeUpdate() event with the code below however that also triggers the Write Conflict.
If Not m_SaveOK Then
    Cancel = True
End If

Also tried to save the form data prior to doing the qry.SQL direct save, however this too failed. That code was basically a check for dirty and forcing a form save using frm.Dirty = False prior to the direct save.
If frm.Dirty Then
    frm.Dirty = False
End If

Form Image
This is what the form looks like. Clicking the pencil (edit) button of a record in the subform populates the top controls.
When the 'Save' button is clicked, the record is saved to the database and the form is requeried to refresh the subform list.

Anyway, I'd appreciate some ideas on how to prevent the form from attempting to save the record vs. the Save button click event.
Thanks in advance for your help!
UPDATE
Subform properties are set to not allow additions and edits (delete is okay since that's what the 'X' button is for in the list), and no locks is set.
After adding some debug.print statements evaluating frm.Dirty and frm.subform.Form.Dirty I've narrowed it down to the main form versus the subform being Dirty and causing the conflict.
Underlying tables are properly updated using the 'Save' button, however the form remains Dirty. So although I'm not currently triggering the Write Conflict error, the Dirty state causes other errors & undesirable behavior on form exit -- You can't save this record at this time... and 2101 The setting you entered isn't valid for this property. when I add a frm.Dirty = False after the button triggered save.
So I'm still working through the issue and would appreciate any other ideas.
Comment: im just wondring if the `frm` on   `frm.Dirty = False` was referenced to the subform. If not then try, `frm![theSubform].Form.Dirty = False`
Comment: No actually not. So you're suggesting that the subform is the culprit in trying to update versus the unbound edit form.  I'll have to take a closer look at that. Thanks!
Comment: Totally unrelated, but use `site && location` in your label to get `site & location` in form view.
Comment: @Andre thanks for your comment. Will check that.
Answer: For the subform the properties Allow Additions, Allow Deletions, Allow Edits
should be set to No and Record Locks to No Locks. This way the subform should not be able to interfere anymore.
Comment: Thanks @Tieme, good thing to check. Checked the subform and all values except "Allow Deletions" were `No` or `No Locks`. While `Allow Deletions` was left for allowing the `delete` (x) button to delete a record I went ahead & set that also to `No` in the subform and retried the `Save` button of the main form. Unfortunately the same `Write Conflict` error results.


Let X be a cont or discrete RV. Define a function $f:R\rightarrow R, f(t)=E(X-t)^2$. Show that f attains its minimum at t=EX

Question: Let X be a continuous or discrete RV. Define a function $f:R->R,$
$$f(t)=E(X-t)^2$$
Show that f attains its minimum at t=EX
I have no idea how to do this problem, because I don't know how to interpret it. I'm assuming $E(X-t)^2$ is the expectation with respect to X-t and then I don't really know what it means by "attains its minimum". I'm assuming that means it's lowest value? But I don't really know how that applies to discrete or continuous variables.
Comment: It applies to any r.v. Hint: Use linearity of expectation. Can you find extrema of such function of variable $t$ ?
Answer: $E(X-t)^{2}=EX^{2}-2tEX+t^{2}$. This quadratic function of $t$ attains its minimum when $-2EX+2t=0$ or $t=EX$.


Sql Advanced Replace

Question: I have to make a difficult word processing. How can I change dynamically as the following example?
Example: /hello/ baby /deneme/ /hello2/
Output: (/hello/) baby (/deneme/) (/hello2/)
Comment: What database product are you using?
Comment: See http://stackoverflow.com/questions/17365222/sql-server-2008-update-and-replace-part-of-a-string
Comment: That's not what I wanted to do, thank you
Answer: This is a pretty rudimentary solution, but it works for the case you've given (SQL Fiddle here):
SELECT
  in_str,
  (
    -- If the string starts with '/', prepend '('
    CASE WHEN in_str LIKE '/%' THEN '(' ELSE '' END
    -- Replace / after a space with (/
    + REPLACE(
        -- Replace / before by a space with /)
        REPLACE( in_str, ' /', ' (/' ),
        '/ ', '/) '
      )
    -- If the string ends with '/', append ')'
    + CASE WHEN in_str LIKE '%/' THEN ')' ELSE '' END
  ) AS out_str
FROM table1;

If table1 has the following in_str values this will give you the corresponding out_str values:
in_str                    out_str
------------------------  ------------------------------
/one/ two /three/ /four/  (/one/) two (/three/) (/four/)
one /two/ /three/         one (/two/) (/three/)
/one/ /two/ three         (/one/) (/two/) three
//one / // two/ /         (//one (/) (//) two/) (/)

I've included the last one to demonstrate some edge cases. Also note that this only handles / characters immediately followed by a space or the beginning or end of the string. Other whitespace characters like newlines and tabs aren't handled. For example, if you had a string like this (where ⏎ indicates a newline and ⇒ a tab):
/one/⇒/two/⏎
/three/⏎

...the output you would get is this:
(/one/⇒/two/⏎
/three/⏎

You could handle these scenarios with additional REPLACE functions, but that's a rabbit hole you'll have to jump down yourself.
Comment: thx :( but now work under code

Example :
[Dealer_Type] in( 'xx' , 'xxx') and [Is_Success] = '1' and [Product_Full_Name] in ( N'xxx' )

Output :
[Dealer_Type] in( ['xx'] , ['xxx']) and [Is_Success] = ['1'] and [Product_Full_Name] in ( N['xxx'] )

Sql Advanced Replace


Script para identificar 2 serviços ativos, derrubar os 2 e subir apenas 1

Question: Seguinte, tenho um serviço aqui em meu ambiente que roda em algumas máquinas, porém este serviço não pode ficar duplicado ( não podem ter 2 serviços ativos ao mesmo tempo ) gostaria de saber se é possível redigir um script que verifique se tem 2 serviços ativos ou mais, desative os 2 ou mais e ative somente 1?
Answer:
em RtlService, altere para o nome do serviço desejado.
  O script entrará em loop, e sempre que houver mais de 1 deste serviço
   ele irá finalizar todos desse tipo, e irá iniciar novamente o serviço.

<code>@echo off
mode 100,2
:loop
cls

set servico=RtlService

if not exist %tmp%\servdupl (md %tmp%\servdupl)

cd %tmp%\servdupl

tasklist | find /i "services" | find /i "%servico%">servdupl.txt

type "servdupl.txt" | find /v /c "">num.txt

set /p num=<num.txt

if "%num%" gtr "1" (net stop %servico%

net start %servico%
goto loop)
</code>
Comment: Dica: caso queira saber o nome correto do serviço,
digite NET START no prompt e verá a lista com os serviços que foram iniciados no Windows!
(Testado no Windows 7)
Comment: Obrigado pela resposta Cristian, este escript é pra ser salvo como VBS ? OBS : estou usando windows10
Comment: como .cmd ou .bat


want to return a value and process order is something wrong

Question: I need to return a value from Method C in Class B.
I want my code to be processed like : 1 - 2 - 3 - 4 - 5
but it's processed like : 1 - 4 - 5 - 2 - 3
(As you can see, I put some logs in the code.)
I've been working with this problem over a week but I couldn't find the problem.
I removed some useless code in this question.
What is the problem and how can I figure this problem out?
I rewrite the post because someone said I shortened the code too much.
Hope it is enough!
Thank you in advance!

Class A
public class a() {
    public void checkConnectivity(Context context) {
         this.context = context;
         myObservable.subscribe(mySubscriber);
    }

    private Observable<Integer> myObservable = Observable.create(
        new Observable.OnSubscribe<Integer>() {
            @Override
            public void call(Subscriber<? super Integer> sub) {
                Log.d("1", "1");
                int connType = cc.getConnectionStatus(context);
                sub.onNext(connType);
                sub.onCompleted();
            }
        }
    );

    private Subscriber<Integer> mySubscriber = new Subscriber<Integer>() {
        @Override
        public void onNext(Integer connType) {
            int code = c.getcode();
            Log.d("4", "4");
            textView.setText("code : " + code);
        }

        @Override
        public void onCompleted() {
            Log.d("5", "5");
        }

        @Override
        public void onError(Throwable e) {
            Log.d("-- NetPresenter", "onError");
        }
    };
}

Class C
public class C() {
    public int getcode() {
         observable
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<Response<ResponseBody>>() {
                public void onCompleted() {
                    Log.d("3", "3");
                }

                public void onError(Throwable e) {
                    code = 0;
                }

                public void onNext(Response<ResponseBody> response) {
                    code = 1;
                    Log.d("2", "2");
                }
            });
        return code;
    }
}

Comment: I'm saying rx-java is asyncronous by nature. Running on new threads all the time is fine but is also asyncronous, if you need them ordered (syncronous), you have to do it differently.
Comment: Your running on new threads all the time, it depends which thread finishes first, it's asyncronous.
Comment: Thanks for the comment. Is running on new threads all the time inefficient? What would you recommend?
Comment: See     http://stackoverflow.com/questions/35062485/rxjava-how-to-emit-observables-synchronously
Comment: Thank you for your kindness Jon. I changed my code synchronously but it works same.. weird haha..
Comment: I'll look at your code in the morning, sleep well.
Comment: Where do you use your mySubscriber? There is only its declaration.
Comment: Hello maxost. Actually there's another method which uses myObservable.subscribe(mySubscriber) in Class A. I think the problem is about async. I'm totally new to android, especially Async so I'm still finding a way
Comment: You need to provide the full code in order that we understand it.
Comment: Hi Hans, I can provide the full code but only thing different is class A. I added the code for you
Comment: checkConnectivity is called when the button's clicked
Answer: First of all RxJava is synchronous by default if nothing else specified.
These two lines
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())

make your c.getcode() call asynchronous. If you remove these lines, you'll get what you need. I checked it by myself.
P.S. Please note that textView.setText("code : " + code); could throw exception (if you initiate whole chain not from UI thread). So you need to find workaround to run this code in UI thread (Handler with Looper.getMainLooper() could help).
Upd 1. try postById.execute() to run request in the same thread. You can achieve your goal if and only if you make all calls in the same thread. postById.enqueue initialize async call. So you broke it again.
Comment: Thank you Stas. Unfortunately I removed whole observable code but it was same. I coded like `postById.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {`
Comment: I use code that you provided with question and everything works for me. You could even try it be yourself from this project, where I keep some interesting code: https://github.com/Shakenbeer/articles.
So I believe I've answered your initial question.

Could you please provide current code so we could figure it out?


AHK sent media keys being blocked by Chrome

Question: So I have a really basic script that makes for the media previous, play/pause, and next keys when I press the appskey and F7/F8/F9, however for some reason, its being blocked by my Chrome browser.
<code>AppsKey & F7::      Send {Media_Prev}
AppsKey & F8::      Send {Media_Play_Pause}
AppsKey & F9::      Send {Media_Next}
</code>
This was meant to work with FooBar2000 and VLC Player, both of which work with the hotkeys when Chrome is not loaded. Prodikl had given an update in the link below in regards to how I found this out in the first place.
autohotkey Media_Play_Pause not mapped to Pause but mapped to ^Space
Anyone have any ideas on how to make this work while Chrome is open?
Answer: Found the answer!
Chrome Hijacking Your Media Keys? Here's The Simple Fix
I'm not currently using Google Play Music, but I had at one point installed it. After turning Google Play Music's shortcuts to "In Chrome," media hotkeys now work fine both through AHK and a keyboard with built in media keys.
This works on Chrome Version 47.0.2526.106.


Mercure Hub server load - better solution

Question: What is better solution taking into account server load (Mercure Hub)?

Users subscribe for one general topic so that Mercure Pushes information to all of them through this one topic and, based on some kind of ID in sent data, user endpoint decides if do something with it or not.
Or the better solution is to have unique topic for each element in the app? So that Mercure Hub handles and push data regarding this one particular topic to some amount of client endpoints?
Answer: It depends if you want to publish private (authorized) or public updates. Option 2 is the best when everything is public in my opinion because you can  put a wildcard in your JWT like:
{
    "mercure": {
        "subscribe": ["*"]
    }
}

But when using the private (authorized) mode, you can't specify every resource the user has access to in the JWT, because it would require a lot of database queries and your JWT will get too big probably.
So what i would do is the following;
Put the user resource as URL Template in the JWT like:
{
    "mercure": {
        "subscribe": ["/api/users/123/{?}"]
    }
}

The {?} means match anything. So /api/blogs/1 doesn't match but /api/users/123/blogs/1 does.
Now you'll only have to dispatch the update to the correct topics, this can be done by using $blog->getSharedUsers() for example by looping it and create topics like:
$topics = [];
foreach ($blog->getSharedUsers() as $user) {
    $topics[] = "/api/users/{$user->getId()}/blogs/{$blog->getId()}";
}

I hope this helps, this is how i've done it in one of my SaaS apps.
If you have further questions feel free to ask, happy to help!
Comment: Thank you @Oliver I mean for public items. I was wondering what is more efficient. One topic for everything or contextual topics for each part of the website.


Declarar Set - JAVA

Question: Queria saber como declarar um conjunto com tipo genérico que não seja uma classe. Exemplo: Set<double>.
Todos os exemplos que eu vi o conjunto é de uma classe.
Estou começando a ver agora a ver conjuntos. Preciso fazer um Set que tenha 20 números aleatórios e tire uma média.
Vou ter que criar uma classe com atributo double pra fazer isso? Ou tem outra maneira?
Answer: Os conjuntos, que implementam a interface Collection do Java, como ArrayList, LinkedList, HashSet, etc... não aceitam tipos primitivos.
Mas nada impede você de declarar um Set<Double> seuSet e depois fazer seuSet.add(2.33), um double primitivo. O Java utiliza os Wrappers ou invólucros quando isso acontece.
Todo tipo primitivo no java tem um Wrapper correspondente:
int => Integer
long => Long
float => Float
double => Double
... assim por diante...

Então quando você tenta adicionar um double primitivo ao array fazendo assim seuSet.add(2.33) , na verdade o Java executa o seguinte: seuSet.add(new Double(2.33))
E, para o que você está querendo, que é tirar uma média dos números, não vejo problema em fazer dessa maneira.
Answer: De fato, você não pode usar tipos primitivos nas Collections do Java.
Se quer trabalhar com double e Set, para o seu caso, as alternativas são:

Usar alguma biblioteca que forneça collections
implementada com tipos primitivos, como Trove ou HPPC;
Fazer sua própria implementação :);
Usar Set<Double> mesmo, se o double primitivo não for uma obrigatoriedade;

Declarar Set - JAVA


What's the best way to build an apache flink connector?

Question: I want build flink connector to OrientDB database. I want handle data locality characteristic, whats is the best way to load all data in parallel way in a Dataset? I know that I have to handle the OrientDB way to read data, but, in flink side, wath are the principles and best practices that I have to handle this kind of task.
Answer: You can refer to flink-hbase connector under flink-connectors in flink source. Basically, you have to implement the interface named InputFormat or RichInputFormat if you need the RuntimeContext.


Geodesics on the flat torus...

Question: I want the set of closed geodesics on the flat torus i.e. $\mathbb{T}= \mathbb{E}^2 / \mathbb{Z}^2$.
That would be

All vertical lines $x=t,\quad t\in [0,1)$
All horizontal lines $y=t,\quad t\in [0,1)$
The two diagonal lines $x=y$ and $x=-y$

Is that all, or am I missing something?
Answer: You're still missing a lot.
Besides the $+1$ slope diagonal line $x=y$, there are all the parallel diagonal lines $x=y+a$.
Besides the $-1$ slope diagonal line $x=-y$, there are all the parallel diagonal lines $x=-y+a$.
And besides all of those, for each rational number $r = \frac{m}{n}$ there is the diagonal line $x = \frac{m}{n} y$ as well as all the parallel diagonal lines $x = \frac{m}{n} y + a$.
Answer: There are infinitely many more diagonal ones because they "wrap around" the torus/closed square.
Take your square and draw the perpendicular bisector through two opposite sides making two smaller rectangles.  Draw a diagonal of one rectangle.  This meets the median at one vertex.  Now "wrap" this diagonal by going to the corresponding point on the opposite side and then drawing the diagonal ofvthe second rectangle that's parallel to the first.  This ends at the opposite corner from where you started but wraps back to the starting point making a closed geodesic.
You can apply this wrapping procedure to other lines as well.  You should find that any wrapped diagonal  line is a closed geodesic iff its slope is a ________ number (you should be able to fill in the blank).
Comment: Thanks, both of you gave me very clear answers.

Geodesics on the flat torus...


Album photos not shown

Question: I would love to display the pictures in my app album into a recycler view with view holder,but after I tried the tutorials and compile it. There is no error but neither photos display in my app.
Still facing the same issue and I have updated my current code
UPDATED ON 30-01-17
Below are the codes:
Album.java
public class Album extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater,
                         ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.album, container, false);

    RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.albumView);
    recyclerView.setHasFixedSize(true);
    RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getContext(), 3);
    recyclerView.setLayoutManager(layoutManager);

    ArrayList<CreateList> createLists = prepareData();
    AlbumAdpater adapter = new AlbumAdpater(getContext(), createLists);
    recyclerView.setAdapter(adapter);

    return view;
}

private ArrayList<CreateList> prepareData() {

    ArrayList<CreateList> theimage = new ArrayList<>();
    String path = Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES).toString();
    File files = new File(path);
    File file[] = files.listFiles();
    Log.e("Album","PrepareData");
    for (int i = 0; i < file.length; i++) {
        CreateList createList = new CreateList();
        createList.setImage_location(file[i].getAbsolutePath());
        createList.setImage_title(file[i].getName());
        theimage.add(createList);
    }
    return theimage;
}
 public void reprmission() {if (ContextCompat.checkSelfPermission(getActivity(), android.Manifest.permission.READ_CONTACTS)
            != PackageManager.PERMISSION_GRANTED);
    {
        if (ActivityCompat.shouldShowRequestPermissionRationale(
                getActivity(), android.Manifest.permission.READ_EXTERNAL_STORAGE)){
        } else {

        ActivityCompat.requestPermissions(getActivity(), new String[]
                {Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_CODE_ASK_PERMISSION);
    }
    } return;
}
}

Createlist.java
public class CreateList  {

private String image_title;
private Integer image_id;
private String image_location;

public String getImage_location() {
    return image_location;
}

public void setImage_location(String image_location) {
    this.image_location = image_location;
}

public String getImage_title() {
    return image_title;
}

public void setImage_title(String android_version_name) {
    this.image_title = android_version_name;
}

public Integer getImage_ID() {
    return image_id;
}

public void setImage_ID(Integer android_image_url) {
    this.image_id = android_image_url;
}
}

AlbumAdapter.java
public class AlbumAdpater extends RecyclerView.Adapter<AlbumAdpater.ViewHolder> {

private ArrayList<CreateList> galleryList;
private Context context;

public AlbumAdpater(Context context, ArrayList<CreateList> galleryList){
    this.galleryList= galleryList;
    this.context = context;
}

@Override
public AlbumAdpater.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i){
    View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.cell_layout, viewGroup, false);
    return new ViewHolder(view);
}

@Override
public void onBindViewHolder(AlbumAdpater.ViewHolder viewHolder, int i){
  //  viewHolder.title.setText(galleryList.get(i).getImage_title());
    viewHolder.img.setScaleType(ImageView.ScaleType.CENTER_CROP);
 //   viewHolder.img.setImageResource((galleryList.get(i).getImage_ID()));
    setImage(galleryList.get(i).getImage_location(),viewHolder.img);
    Picasso.with(context).load(galleryList.get(i).getImage_location()).resize(50,50).centerCrop().into(viewHolder.img);
}

@Override
public int getItemCount(){
    return galleryList.size();
}

public class ViewHolder extends RecyclerView.ViewHolder{

    private TextView title;
    private ImageView img;

    public ViewHolder(View view){
        super(view);
        title = (TextView) view.findViewById(R.id.imgtitle);
        img = (ImageView) view.findViewById(R.id.img);
    }
}

void setImage(String filePath, ImageView imageView){
Picasso.with(context).load(new File(filePath)).into(imageView);
}
}

Logcat report
  Reconstruct Branch               :
   01-30 13:31:54.924 8612-8701/com.example.kaiser.bdiary I/OpenGLRenderer: Initialized EGL, version 1.4
 01-30 13:31:54.941 8612-8612/com.example.kaiser.bdiary W/Settings: Setting airplane_mode_on has moved from android.provider.Settings.System to android.provider.Settings.Global, returning read-only value.
 01-30 13:31:54.951 8612-8612/com.example.kaiser.bdiary E/Album: onBindViewHolder
 01-30 13:31:54.952 8612-8612/com.example.kaiser.bdiary E/Album: onBindViewHolder
 01-30 13:31:54.954 8612-8612/com.example.kaiser.bdiary E/Album: onBindViewHolder
 01-30 13:31:54.956 8612-8612/com.example.kaiser.bdiary E/Album: onBindViewHolder
 01-30 13:31:54.957 8612-8612/com.example.kaiser.bdiary E/Album: onBindViewHolder
 01-30 13:31:54.958 8612-8612/com.example.kaiser.bdiary E/Album: onBindViewHolder
 01-30 13:32:23.922 8612-8612/com.example.kaiser.bdiary V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance@b911fe5
 01-30 13:32:23.979 8612-8612/com.example.kaiser.bdiary V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance@adce0c8
 01-30 13:33:41.293 8612-8695/com.example.kaiser.bdiary W/System: ClassLoader referenced unknown path: /data/data/com.example.kaiser.bdiary/lib
 01-30 13:33:41.349 8612-8612/com.example.kaiser.bdiary V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance@d54d109
 01-30 13:33:41.350 8612-8612/com.example.kaiser.bdiary V/BoostFramework: BoostFramework() : mPerf =           com.qualcomm.qti.Performance@ac3ef0e
 01-30 13:33:41.350 8612-8612/com.example.kaiser.bdiary V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance@b173d2f
 01-30 13:33:41.387 8612-8612/com.example.kaiser.bdiary V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance@7a4e0bc
 01-30 13:33:41.387 8612-8612/com.example.kaiser.bdiary V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance@b152845
 01-30 13:33:41.390 8612-8612/com.example.kaiser.bdiary E/Album: PrepareData
 01-30 13:33:41.393 8612-8612/com.example.kaiser.bdiary V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance@3d4ca8
 01-30 13:33:41.535 8612-8612/com.example.kaiser.bdiary E/Album: onBindViewHolder
 01-30 13:33:41.536 8612-8612/com.example.kaiser.bdiary E/Album: onBindViewHolder
 01-30 13:33:41.538 8612-8612/com.example.kaiser.bdiary E/Album: onBindViewHolder
 01-30 13:33:41.543 8612-8612/com.example.kaiser.bdiary E/Album: onBindViewHolder
 01-30 13:33:41.545 8612-8612/com.example.kaiser.bdiary E/Album: onBindViewHolder
 01-30 13:33:41.547 8612-8612/com.example.kaiser.bdiary E/Album: onBindViewHolder
 01-30 13:33:41.579 8612-8701/com.example.kaiser.bdiary V/RenderScript:      0x7f819bb000 Launching thread(s), CPUs 4
 01-30 13:33:50.192 8612-8612/com.example.kaiser.bdiary V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance@fcf2205
 01-30 13:33:50.916 8612-8612/com.example.kaiser.bdiary V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance@b720c8b
 01-30 13:33:53.217 8612-8612/com.example.kaiser.bdiary V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance@724d981
 01-30 13:33:54.881 8612-8612/com.example.kaiser.bdiary V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance@fbc1a26

RecycleView
    <?xml version="1.0" encoding="utf-8"?<android.support.v7.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/albumView">
 </android.support.v7.widget.RecyclerView>

I was using my phone as emulator all along, and when I use the emulator from the studio itself it crashes, because of the length of array is null. And I thought I populated the array list already ? no ?
New error
  01-30 13:48:55.551 4603-4603/? E/AndroidRuntime: FATAL EXCEPTION: main
                                             Process: com.example.kaiser.bdiary, PID: 4603
                                             java.lang.NullPointerException: Attempt to get length of null array
                                                 at com.example.kaiser.bdiary.Album.prepareData(Album.java:44)
                                                 at com.example.kaiser.bdiary.Album.onCreateView(Album.java:29)
                                                 at android.support.v4.app.Fragment.performCreateView(Fragment.java:2087)
                                                 at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1113)
                                                 at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1295)
                                                 at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:801)
                                                 at android.support.v4.app.FragmentManagerImpl.execSingleAction(FragmentManager.java:1643)
                                                 at android.support.v4.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:679)
                                                 at android.support.v4.app.FragmentStatePagerAdapter.finishUpdate(FragmentStatePagerAdapter.java:166)
                                                 at android.support.v4.view.ViewPager.populate(ViewPager.java:1272)
                                                 at android.support.v4.view.ViewPager.populate(ViewPager.java:1120)
                                                 at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1646)
                                                 at android.view.View.measure(View.java:18788)
                                                 at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:715)
                                                 at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)
                                                 at android.view.View.measure(View.java:18788)
                                                 at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
                                                 at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
                                                 at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:139)
                                                 at android.view.View.measure(View.java:18788)
                                                 at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
                                                 at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
                                                 at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
                                                 at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
                                                 at android.view.View.measure(View.java:18788)
                                                 at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
                                                 at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
                                                 at android.view.View.measure(View.java:18788)
                                                 at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
                                                 at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
                                                 at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
                                                 at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
                                                 at android.view.View.measure(View.java:18788)
                                                 at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
                                                 at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
                                                 at com.android.internal.policy.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2643)
                                                 at android.view.View.measure(View.java:18788)
                                                 at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2100)
                                                 at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1216)
                                                 at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1452)
                                                 at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1107)
                                                 at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6013)
                                                 at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
                                                 at android.view.Choreographer.doCallbacks(Choreographer.java:670)
                                                 at android.view.Choreographer.doFrame(Choreographer.java:606)
                                                 at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)
                                                 at android.os.Handler.handleCallback(Handler.java:739)
                                                 at android.os.Handler.dispatchMessage(Handler.java:95)
                                                 at android.os.Looper.loop(Looper.java:148)
                                                 at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                 at java.lang.reflect.Method.invoke(Native Method)
                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

Comment: check my updated answer
Comment: Thank you Mr Ahamed!
I did managed to solve the arguments, but there is a null object references issue
Comment: Update your question with what you have done up-to now.i will see
Comment: Dear Mr Ahamed, kinky review my code
Thank you!
Comment: Post your xml of  RecyclerView and Its ItemView and before that, you should not use getContext() from your fragment. use getActivity() instead. and I think, Environment.getExternalStoragePublicDirectory() will return file . why are converting to String then make it as file.?Comment the code of setImage() function.
Comment: Sure understood
have already post the recycle view =)
Comment: post your R.layout.album?
Comment: change Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES).toString() to Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES).getPath();
Comment: yup! thats the code for R.layout.album
Comment: I have added a new crash report =) Hope it will help us solve the issue
Comment: onPrepareData method,  File file[] = files.listFiles(); file having no files. so, it's becoming null array. in that null array you are trying to get the files using for loop. so the new error says the same.
Comment: String path = Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES).getPath().  try to print the path, and check with logcat. and make sure that path having valid image files.
Comment: sorry! how do I check if path has valid image files?
Comment: post your path which printed on logcat. i will tell you how.
Comment: I have posted in my questions =)
Answer: As READ_EXTERNAL_STORAGE is a dangerous permission you should request that permission at run time. Please check the documentation. Also don't forget to declare it in manifest.

Your photo is not display because you are assigning image_location in Activity and in adapter you are setting the image using image_id which is null. You are not getting NPE because you are creating an empty ArrayList and didn't push any Object in it.
Adding data in ArrayList should be like this
private ArrayList<CreateList> prepareData() {

    ArrayList<CreateList> theimage = new ArrayList<>();
    String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
            .toString();
    File f = new File(path);
    File file[] = f.listFiles();
    Log.e("Album","PrepareData");
    for (int i = 0; i < file.length; i++) {
        CreateList createList = new CreateList();
        createList.setImage_location(file[i].getAbsolutePath());
        createList.setImage_title(file[i].getName());
       //If you want to use image_id then you have to set a value using setImage_ID here
       theimage.add(createList);
    }
    return theimage;
}

Show image in adapter using any library like Glide or Picasso
Using Picasso
Picasso.with(context).load(galleryList.get(i).getImage_location()).resize(50, 50).centerCrop().into(viewHolder.img);

Using Glide
Glide.with(context).load(galleryList.get(i).getImage_location()).centerCrop().placeholder(R.drawable.placeholder_img).into(viewHolder.img);

Comment: Mr Kaushik, thank you for your input.
But what if I dont wanna use Glide or Picasso? Any other alternative ?
Comment: and sorry where do i place the picasso or glide code ?
Comment: inside your adapter's `onBindViewHolder` @kaikai where you setting the image for recyclerview
Comment: Dear Mr Kaushik,

Im still facing the same issue, and I have updated my code, kindly help me to review? Thank you!
Comment: can you please print those path using `Log` inside `prepareData's for loop` and inside `onBindViewHolder` and also may I know which device you are testing and it's os
Comment: Its Xiaomi Android 6.0.1 API 23
and I add edited my question with the logcat
Comment: You have ask permission at runtime please implement that code
Comment: I have added the permission to my Album activity, but now there is new issue where logcat state that 01-30 17:41:12.136 15632-15632/com.example.kaiser.bdiary W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
Answer: Managed to get the help from Mr Kaushik
Album.java
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    imgview = (ImageView) getActivity().findViewById(R.id.solopic);
    soloimg = (LinearLayout)getActivity().findViewById(R.id.imgsolo);

    View view = inflater.inflate(R.layout.album, container, false);
    recyclerView = (RecyclerView) view.findViewById(R.id.albumView);
    recyclerView.setHasFixedSize(true);
    RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getContext(), 3);
    recyclerView.setLayoutManager(layoutManager);
    if (Build.VERSION.SDK_INT >= 23) {
        if (!verifyGalleryPermission()) {
            ArrayList<CreateList> createLists = prepareData();
            AlbumAdpater adapter = new AlbumAdpater(getContext(), createLists);
            recyclerView.setAdapter(adapter);
        }
    } else {
        ArrayList<CreateList> createLists = prepareData();
        AlbumAdpater adapter = new AlbumAdpater(getContext(), createLists);
        recyclerView.setAdapter(adapter);
    }

    return view;
}

private ArrayList<CreateList> prepareData() {
    ArrayList<CreateList> theimage = new ArrayList<>();
    String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString()+"/BDiary";
    File files = new File(path);
    if(files.exists()){
        File file[] = files.listFiles();
        Log.e("Album","PrepareData");
        for (File aFile : file) {
            CreateList createList = new CreateList();
            createList.setImage_location(aFile.getAbsolutePath());
            createList.setImage_title(aFile.getName());
            theimage.add(createList);
        }
    }
    else
    {
        Toast.makeText(getContext(),"Folders not found", Toast.LENGTH_SHORT).show();
    }
    return theimage;
}

@TargetApi(23)
private boolean verifyGalleryPermission() {
    if (ActivityCompat.checkSelfPermission(getActivity(),android.Manifest.permission.READ_EXTERNAL_STORAGE)
            !=
            PackageManager.PERMISSION_GRANTED) {
        if (shouldShowRequestPermissionRationale(android.Manifest.permission.READ_EXTERNAL_STORAGE))
        {
            displayPermissionDialog("Would like to grant BDiary access to read your gallery",
                    new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_PERMISSION);
        } else
        {
            requestPermissions(new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_PERMISSION);
        }
        return true;
    }
    return false;
}

@TargetApi(23)
private void displayPermissionDialog(String msg, final String[] permission, final int resultCode) {
    AlertDialog alertDialog = new AlertDialog
            .Builder(getActivity())
            .setMessage(msg)
            .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    dialogInterface.cancel();
                    requestPermissions(permission, resultCode);
                }
            }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    dialogInterface.cancel();
                }
            })
            .create();
    alertDialog.show();
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch (requestCode) {
        case REQUEST_PERMISSION:
            ArrayList<CreateList> createLists = prepareData();
            AlbumAdpater adapter = new AlbumAdpater(getContext(), createLists);
            recyclerView.setAdapter(adapter);
            break;
    }
}
}

AlbumAdapter.java
public class AlbumAdpater extends RecyclerView.Adapter {
    private ArrayList<CreateList> galleryList;
    private Context context;

    public AlbumAdpater(Context context, ArrayList<CreateList> galleryList){
        this.galleryList= galleryList;
        this.context = context;
    }

    @Override
    public AlbumAdpater.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i){
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.cell_layout, viewGroup, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(AlbumAdpater.ViewHolder viewHolder, int i){
        viewHolder.title.setText(galleryList.get(i).getImage_title());
        viewHolder.img.setScaleType(ImageView.ScaleType.CENTER_CROP);
        Glide.with(context).load(galleryList.get(i).getImage_location()).centerCrop().into(viewHolder.img);
    }

    @Override
    public int getItemCount(){
        return galleryList.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder{

        private TextView title;
        private ImageView img;

        public ViewHolder(View view){
            super(view);
            title = (TextView) view.findViewById(R.id.imgtitle);
            img = (ImageView) view.findViewById(R.id.img);
        }
    }
}

Hope this will help the people who are doing gallery too =)
Cheers!
And this have to be credit to Mr Kaushik
Answer: 1) First of all, Make sure the Pictures directory having the Image file.
2) You didn't add the file path on the list items. you just add the name of     the file and didn't add it on the list.
 for (int i = 0; i < file.length; i++) {
    CreateList createList = new CreateList();
  // createList.setImage_location(file[i].getName());
     createList.setImage_location(file[i].getPath);
     theimage.add(createList);

}

3) You didn't add bind the file path into imageview on adapter class.
4) add below method on your adapter class.
 void setImage(String filePath,ImageView imageView){//here I made the mistake. Apologise.
   Picasso.with(context).load(new File(filePath)).into(imageView);
 }

5) from onBindViewHolder(..) method do the below stuff.
  @Override
 public void onBindViewHolder(AlbumAdpater.ViewHolder viewHolder, int i){
    .....
    ......
    setImage(galleryList.get(i).getImage_location(),viewHolder.img);
 }

Updated
I used Picasso library to load the file because it will manage outOfMemoryError. so , here, if you dont want to Picasso Library means,
use below method.
  Uri uri= Uri.parse(filePath);
  imageView.setImageUri(uri);

Comment: Thank you Mr Ahamed,
As for the instructions

1) Yes I do have!
2) I have add in successfully
3) I presumed that this code has done the job?

        ArrayList createLists = prepareData();
        AlbumAdpater adapter = new AlbumAdpater(getContext(),                createLists);
        recyclerView.setAdapter(adapter);

4) I have problem with the .into(imageView):, as it stated that it cannot resolve method 'into (java.lang.String)'

5)I have problem with the  viewHolder.img); as the found argument type is ImageView but the required is java.lang.String
Comment: dear Mr Ahamed,

I have change it to void setImage(String filePath, ImageView imageView)

But im getting a int jav.lang.Integer.intValue() on a null object reference
for this line of code:
viewHolder.img.setImageResource(galleryList.get(i).getImage_ID());
Do you have any idea what has gone wrong?
Comment: viewHolder.img.setImageResource() this method parameter will always be integer resource. it is pointing the image which is in drawable folder. here, you want to load the image from gallery.
Comment: hmmm im sorry Mr Ahamed, Im poor in Java, but I have already direct the path to the storage directory, therefore what did i do wrong?
Comment: Hi Mr Ahamed, the null object references issue i mentions is refer to this question. Thank yoU!

Album photos not shown


AngularJS - Save attribute value by default

Question: I use own tags 'repairwidth' with attribute 'width'. I get 'input' from this tag. Width = size.
First repairwidth tag must have width="50" always.
Second and third tags repairwidth have width="{{width}}"
I can change width from input with ng-model="width".
But width="50" doesn't work.
plunker
Yes. I can use scope: {width: '@'} to fix it.
But in my application scope must have false value.
I can't use ng-init and ng-model.
Where is my mistake?
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>width with scope: false</title>

scope: false

    <repairwidth width="50" ></repairwidth>
    input must have size=50 always
    Doesn't work

    <repairwidth width="{{width}}" ></repairwidth>

    <repairwidth width="{{width}}" ></repairwidth>

 size for 2 & 3 inputs:
 <input type="text" ng-model="width" />
 I can change size for 2 & 3 inputs
 Doesn't work

 not use ng-init and ng-model

Answer: Since your directive scope is false, the directive inherits its scope from the parent.  That means all instances of your directive will use the same value of width that is set in the controller.  The width parameter that you are passing into the directive is essentially being ignored.
<repairwidth size="{{width}}" ></repairwidth>

does the same thing as
<repairwidth></repairwidth>

The easiest thing to do is to bind directly to the size parameter like this:
<repairwidth size="50" ></repairwidth>
<repairwidth size="{{width}}" ></repairwidth>
<repairwidth size="{{width}}" ></repairwidth>

You don't even need the link function.
Plunker.


How could you make a key change sound natural

Question: I've been working on an orchestral piece for a while and I want to include a key change. For example,  from Bb major into Eb major. How could one go about changing keys in a way that makes the music flow smoothly while keeping the same tone and feel?
Comment: Does this answer your question? [How many types of modulation are there?](https://music.stackexchange.com/questions/27079/how-many-types-of-modulation-are-there)
Answer: There are several ways. One easy one is to use a pivot chord; this is a chord that is diatonic in both keys; one approaches the chord in the first key and exits the chord in the target key. In your case, Bb to Eb, one could use Cm. It's the ii chord of Bb and the vi chord of Eb. A possibility (not necessarily the best) is to play a Gm chord (also diatonic in both keys) followed by a Cm, a Bb7, and then Eb. The key of Eb needs to be "confirmed" by playing something like an Ab or Fm chord; these have an Ab in Eb as opposed to an A in Bb. (That sentence sounds weird.) Schoenberg calls this "neutralizing" the A. Of course one could take the shortcut of playing Bb7 (the dominant seventh of Eb) followed by Eb.
Besides the usual harmony books, there are several (older) books on modulation. These can be found on the Wayback Machine or the Internet Archive. One is Arthur Foote has one called "Modulation." Max Reger has another called, "Modulation." A third one is Frank Shepard's "How to Modulate." Reger's book is a list of modulations from C to every other key and from Am to every other key. Foote and Shepard concentrate more on the theory behind modulation.
Answer: Yes, B♭ major to E♭ major is trivial.  Just stick in some A♭ notes.   Shall we be a bit more adventurous?
A lot of discussion on modulation concentrates on the chord progression.   Melody is also important.  Here's a simple transition from C major to E♭ major.  It's carried by repetition of a simple melodic phrase.

Also consider the 'just do it' modulation. Don't try to smooth it out, dramatise it!   You can imagine Beethoven doing something like this.  'I'm done in C major for now.  Let's try F♯ major!'

If you want something a little less abrupt, the ii - V -I  sequence is incredibly powerful. Write one in the old key, repeat it in the new.  Literally any new key will work.  Try!  Here's an example, C major to E major, followed by a condensed version.
Answer: B♭ major and E♭ major are very closely related. In fact, there's only one diatonic note that changes - A♮ becomes A♭ when the key changes to E♭ major.
So I doubt there could be a more subtle, unnoticable key change. In fact, there are many instances in pieces where the music modulates in that way, and most people would not consider there's much of a move.
The note that is pivotal to E♭ is its leading note - D. That is part of the dominant chord in E♭, which is B♭7. So playing a harmony using that chord is exactly what's needed to introduce the new key. And the note which isn't diatonic to key B♭ is A♭. That's what'll lead the piece into key E♭.


Calculate odds ratios for continuous variables

Question: I am at the univariable stage of my analysis, and I am looking at significance of individual variables/predictors.  I've tested each predictor for significance by Wilcoxon Rank-Sum for continuous variables (not using t-test because data are not necessarily normal) and chi-square for discrete variables.  However, in addition to p-values, I also need to calculate odds ratios (and 95%CI for the OR) for each predictor.
I was able to calculate ORs for the discrete variables using the (ad)/(cb) shortcut with a simple 2x2 table.  But I cannot find instructions for how to calculate univariable ORs for the continuous variables.
Should I run a separate logistic regression for each of the variables, where the independent variable is the continuous predictor and the dependent variable is my 0/1 outcome?
Any help is appreciated!
Comment: What is a *"univariable stage of my analysis*" ? Please do NOT use the "significance" of variables in univariable regression models to inform which variables to use in a multivariable regression model. This is a terrible mistake.
Comment: This sounds like some kind of variable selection for a regression model. Is that what you're doing?
Comment: @RobertLong Yes, understood.  No, I'm not hunting for p-values.  Working on a manuscript and need to report significance of predictors in both univariable and multivariable analysis.
Comment: Why in the univariate case? You don't have to do every statistically dubious suggestion a reviewer makes.
Comment: I'm glad you understand :) but in what sense is the significance of variables in univariate models relevant to your research question(s) ? How will these be used ?
Answer: There is no straightforward way to compute odds ratios manually for continuous predictors. You need to run a one-predictor logistic regression, exponentiate the coefficient on the predictor and its confidence bounds, and then report that as the odds ratio and its 95% confidence interval. You can (and maybe should) do this with your binary predictors as well.
Comment: I realized this was a possibility just after posting.  Thanks, Noah.  I'm so used to working with multivariable regressions that I forgot univariable regressions are a thing, too :-)


RTNETLINK answers: File exists when using netem with tc

Question: So I simply get this error when I enter this command in my master VM:
 sudo tc qdisc add dev eth0 root netem delay 97ms
RTNETLINK answers: File exists

Any idea how that could be fixed?
I am running this command in Ubuntu:
uname -a
Linux anmol-vm1-new 3.13.0-46-generic #79-Ubuntu SMP Tue Mar 10 20:06:50 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux
ubuntu@anmol-vm1-new:~$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 14.04.2 LTS
Release:    14.04
Codename:   trusty

Here's the content of /etc/network/interfaces file:
auto lo
iface lo inet loopback
source /etc/network/interfaces.d/*.cfg

ls /etc/network/interfaces.d/
eth0.cfg

And here's what I have in /etc/network/interfaces.d/eth0.cfg
# The primary network interface
auto eth0
iface eth0 inet dhcp

Additionally I get these errors:
ubuntu@anmol-vm1-new:/home/hadoop/yarnpp/workloads/RESULTS$ tc qdisc change dev eth0 root netem delay 100ms
RTNETLINK answers: Operation not permitted
ubuntu@anmol-vm1-new:/home/hadoop/yarnpp/workloads/RESULTS$ sudo tc qdisc change dev eth0 root netem delay 100ms
RTNETLINK answers: Invalid argument

In reference you might also want to look at this StackOverflow question I had asked for limiting the bandwidth.
ifconfig -a
eth0      Link encap:Ethernet  HWaddr fa:16:3e:b4:22:7c
          inet addr:10.0.1.190  Bcast:10.0.1.255  Mask:255.255.255.0
          inet6 addr: fe80::f816:3eff:feb4:227c/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1454  Metric:1
          RX packets:603022138 errors:0 dropped:0 overruns:0 frame:0
          TX packets:132788011 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:633486216278 (633.4 GB)  TX bytes:798520828666 (798.5 GB)

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:367293839 errors:0 dropped:0 overruns:0 frame:0
          TX packets:367293839 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:547056723183 (547.0 GB)  TX bytes:547056723183 (547.0 GB)

Answer: The solution was the following:
sudo tc qdisc del dev eth0 root
sudo tc qdisc add dev eth0 root netem delay 100ms

Answer: shorter solution:
sudo tc qdisc replace dev eth0 root netem delay 100ms


Disabling the hint window that EClipse Editor shows

Question: when I hover over the codes in ECLispe Editor it pops up this yellow hint box for everything that I am on it to show some useful info about it. well it is cool but it is also annoying! is there a way that I can deactivate it as Default setting and then anytime I needed it I hit a hot-key to bring it up...
Answer: If you go:
Window->Preferences
In the tree look for "Hovers" under Java->Editor->Hovers
You can uncheck all the ones you do not want, or add keyboard shortcuts to activate a Hover. Not particularly useful, but may help.


Track Database table changes with Sails.js

Question: My Goal:
Then database table was externally changed, I want to send WebSocket notification to clients.
Question:
Is there a "native" Sails.js way to track changes in database table populated via Model?
Comment: The problem is how to catch model (e.g. database table) change event? The point is what table can change externally. Is I need periodically fetch table, compare from previous state and then, if it change, broadcast message? Or sails has more elegant way?
Answer: I only dabble in sails but I'm not aware of a way.  You might make a "model-listener" service that utilizes your adapter of choice's socket/channel capabilities.  You'll have to start the listeners at some point via a hook or in the bootstrap file.
The problem you're going to run into is determining if the event(create, update, drop/delete) was external or sails.  I'm more familiar with PGSQL and know you can provide an application name to your connection and could include it in your publish message so your listener/subscribe handler can ignore non-sails related events.
PGSQL trigger/notify/listen

Event Triggers
Notify
Listen

MongoDB

Capped Collections
Tailable Cursors

Of course waterline supports more adapters than the two I've listed here but I tried to pick the two I assume are the most popular.  I know this might be the answer you had hoped for but it might give you some ideas to try.
Sorry, I'm a new poster so I'll try to provide some links in comments if it will stackoverflow will allow me.
Comment: Capped Collections and Tailable Cursors explained with an example (includes links to mogo docs for each concept) - http://tugdualgrall.blogspot.fr/2015/01/how-to-create-pubsub-application-with.html
Comment: PSQL Event Triggers [postgresql.org/docs/event-triggers](http://www.postgresql.org/docs/current/static/event-triggers.html),
PSQL Notify [postgresql.org/docs/sql-notify](http://www.postgresql.org/docs/current/static/sql-notify.html) PSQL Listen [postgresql.org/docs/sql-listen](http://www.postgresql.org/docs/current/static/sql-listen.html) and Using the node-postgres module for notifications (same one waterline adapter uses) - [github.com/brianc/node-postgres/wiki/Client#notification--object-message](https://github.com/brianc/node-postgres/wiki/Client#notification--object-message)


Problemas em achar o erro!

Question: Galera eu fiz um código e depois realizei um scanner e deu que o código deixa o site com uma brecha, não estou conseguindo encontrar onde esta o erro e se ele e grave ou não. Esse é o código:
var $K2 = jQuery.noConflict();

$K2(document).ready(function(){

  // Generic function to get URL params passed in .js script include
    function getUrlParams(targetScript, varName) {
        var scripts = document.getElementsByTagName('script');
        var scriptCount = scripts.length;
        for (var a = 0; a < scriptCount; a++) {
            var scriptSrc = scripts[a].src;
            if (scriptSrc.indexOf(targetScript) >= 0) {
                varName = varName.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
                var re = new RegExp("[\\?&]" + varName + "=([^&#]*)");
                var parsedVariables = re.exec(scriptSrc);
                if (parsedVariables !== null) {
                    return parsedVariables[1];
                }
            }
        }
    }

Comment: @wmsouza Marcou a resposta que nada tem a ver com a pergunta.
Comment: Que scanner usou? Qual a mensagem inteira de erro? Copia e cola tudo aqui, precisamos de detalhes.
Comment: Qual **brecha** ?
Comment: O Scanner, me alertou sobre uma possivel brecha que possibilita alguem invadir  o site atraves desse codigo, e tambem diz q o JQuery nao esta definido. eu queria ajuda pra saber se o codigo esta correto ou nao? Se precisa de alguns ajustes ou o Scanner me informou errado, infelizmente nao sei qual a brecha tambem, so a questao se o codigo esta correto.
Comment: Em relação do *jQuery* não estar definido, é porque falta importar ele: ``
Comment: obrigado vlw mesmo
Comment: Guilherme usei o Scanner Shadow Security Scanner. Primeiro ele me informa o script com erro com um link, diz q o erro esta na linha 9 cujo ea primeira linha do codigo que eu postei, tambem vem com caractere 1. ERRO:'jQuery' não esta definido Codigo: 800A1391 Origem: Erro em tempo de execuçao do Microsoft JScript. Essas sao as informaçoes que ele me passa
Answer: No código que você postou falou um fechamento de chave } no fim do código pra encerrar a primeira função:

var $K2 = jQuery.noConflict();

$K2(document).ready(function(){

  // Generic function to get URL params passed in .js script include
    function getUrlParams(targetScript, varName) {
        var scripts = document.getElementsByTagName('script');
        var scriptCount = scripts.length;
        for (var a = 0; a < scriptCount; a++) {
            var scriptSrc = scripts[a].src;
            if (scriptSrc.indexOf(targetScript) >= 0) {
                varName = varName.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
                var re = new RegExp("[\\?&]" + varName + "=([^&#]*)");
                var parsedVariables = re.exec(scriptSrc);
                if (parsedVariables !== null) {
                    return parsedVariables[1];
                }
            }
        }
    }
}); // Faltou

Comment: Obrigado @GuilhermeNascimento, não tinha notado. @dvd eu já tinha testado em 2 navegadores (Firefox e Opera) e não deu nenhum erro, coloquei várias TAGs com scripts puxados de outros sites e nenhum erro aconteceu, acredito que a brecha esteja em alguma script `listada` no HTML pela função. De resto o código funciona.
Comment: Amigo, quando for assim pergunte via comentário, talvez seja somente na pergunta que esteja faltando e no código real não.
Comment: o vlw pela resposta tbm
Comment: @dvd onde está errada, têm que ser mais claro amigo? Mas então quem marcou como correta? Você tem privilégio pra reverter a situação? Agradecido.
E pra constar faltava a chave sim.Deve ter sido um erro do solicitante.
Comment: falta `);` no após o `}`, claro que na pergunta também falta, mas por usar o stacksnippet para testar seria melhor adicionar

Problemas em achar o erro!


Right quotient of $a^*baa^*$ with $ab^*$

Question: Hello i am new to this concept.
Take two languages:-
$$L_1=a^*baa^*$$
$$L_2=ab^*$$
and $L_1/L_2$ (right quotient) would be $(a^*b + a^*baa^*)$?
Does this mean that suffix of $L_1$ and anything from $L_2$ I mean 'a' in $L_2$ which would be suffix of $L_1$ and hence we would remove it.)?
I searched internet and found this link but it is not clear to me how $L_1/L_2$ is $(a^*b + a^*baa^*)$.
Answer: If $w_2\in L_2$ ends in $b$, $w_2$ can never be a suffix of any word $w_1\in L_1$ because $w_1$ must end with one or more $a$s. So $w_2$ must be $a$ to be a suffix of some $w_1$, and indeed $a$ is a suffix of every possible $w_1$, with the remainder consisting of the same $w_1$ but with one $a$ chopped off at the end.
From one or more $a$s at the end we get to zero or more $a$s. So the right quotient $L_1/L_2$ is $a^*ba^*$, which your $(a^*b+a^*baa^*)$ simplifies to.
Comment: That makes sense but i checked it both the languages are correct.


Inner Join using COUNT(*)

Question: I am selecting the user's information from my MySQL database as shown below:
SELECT * FROM `Users` WHERE `$user_or_id` = ?

However, I would like to add an extra bit off information to the returned data. The extra bit of data is the total number of records in a table named 'Venues' where the rows' field, 'user_id' is the same as the 'id' field in the table, 'Users'.
Please can you tell me where I am going wrong with the following query? Here is the error I am receiving:

You have an error in your SQL syntax; check the manual that
  corresponds to your MySQL server version for the right syntax to use
  near '*) FROM Users AS u INNER JOIN Venues AS v ON u.id =
  v.user_id WHERE u.id = '' at line 1

SELECT u.*, v.count(*) FROM `Users` AS u INNER JOIN `Venues` AS v ON u.id = v.user_id WHERE u.$user_or_id = ?

Comment: probably `count(v.*)` (if even possible).
Comment: you have to use GROUP BY statement
Answer: SELECT u.*, COUNT(v.*) FROM `Users` AS u INNER JOIN `Venues` AS v ON u.id = v.user_id WHERE u.$user_or_id = ?

COUNT is a MySQL function, not a member of table v. Pass it an argument representing what you want to count-- in this case, v's rows.
Answer: It should be COUNT(v.*). Otherwise it's interpreted as "function count inside table V", which isn't valid.
Answer: Just use count(*) instead of v.count(*).

Inner Join using COUNT(*)


Array size problem while testing mergesort

Question: I have to test Mergesort with different sizes of data. The problem I encounter is that if the array of ints is around the size of 5000000 my code is crashing but without giving an error. I calculated the amount of space the array would take and if I'm not wrong this would be about 0,02 GB and my RAM is 8GB. I also searched if there is a max size for an array and didnt find anything useful. So where is the problem?
     /* C program for Merge Sort */
#include<stdlib.h>
#include<stdio.h>
#include <time.h>

#define MAX 2000000
int arr[MAX];

// Merges two subarrays of arr[].
// First subarray is arr[l..m]
// Second subarray is arr[m+1..r]
void merge(int l, int m, int r)
{
int i, j, k;
int n1 = m - l + 1;
int n2 =  r - m;

/* create temp arrays */
int L[n1], R[n2];

/* Copy data to temp arrays L[] and R[] */
for (i = 0; i < n1; i++)
    L[i] = arr[l + i];
for (j = 0; j < n2; j++)
    R[j] = arr[m + 1+ j];

/* Merge the temp arrays back into arr[l..r]*/
i = 0; // Initial index of first subarray
j = 0; // Initial index of second subarray
k = l; // Initial index of merged subarray
while (i < n1 && j < n2)
{
    if (L[i] <= R[j])
    {
        arr[k] = L[i];
        i++;
    }
    else
    {
        arr[k] = R[j];
        j++;
    }
    k++;
}

/* Copy the remaining elements of L[], if there
   are any */
while (i < n1)
{
    arr[k] = L[i];
    i++;
    k++;
}

/* Copy the remaining elements of R[], if there
   are any */
while (j < n2)
{
    arr[k] = R[j];
    j++;
    k++;
}
}

/* l is for left index and r is right index of the
sub-array of arr to be sorted */
void mergeSort(int l, int r)
{
if (l < r)
{
    // Same as (l+r)/2, but avoids overflow for
    // large l and h
    int m = l+(r-l)/2;

    // Sort first and second halves
    mergeSort(l, m);
    mergeSort(m+1, r);

    merge(l, m, r);
}
}

/* UTILITY FUNCTIONS */
/* Function to print an array */
void printArray()
{
int i;
for (i=0; i < MAX; i++)
    printf("%d ", arr[i]);
printf("\n");
}

/* Driver program to test above functions */
int main()
{
srand(time(NULL));
for (int var = 0; var < MAX; ++var) {
    arr[var] = rand() % 100;
}
clock_t t1, t2;
//printf("Given array is \n");
// printArray();
t1 = clock();
mergeSort(0, MAX - 1);
t2 = clock();
printf("\nSorted array is \n");
printArray();
float timetaken = t2 - t1;
timetaken /= CLOCKS_PER_SEC;
printf("Time spend:  %f\n", timetaken);
return 0;
}

Comment: Don't use local temp space for this. Non-in-place merge sort requires 2N space. You can make that happen by declaring *another* N-sized variable static (alongside `arr`), using that for temp storage. That avoids the stack-hungry problems you're having now while simultaneously avoiding the cost of dynamic memory management.
Comment: OT: for ease of readability and understanding: 1) variable (and parameter) names should indicate `content` or `usage (or better, both)  Names like 'l' 'm' 'r' 'n1' 'n2'  etc are meaningless, even in the current context.  2) please consistently indent the code.  Indent after every opening brace '{'.  Unindent before every closing brace '}'.  Suggest each indent level be 4 spaces  3) separate code blocks: `for` `if` `else` `while` `do...while` `switch` `case` `default` via a single blank line. 4) separate functions by 2 or 3 blank lines (be consistent)
Comment: Following up on WhozCraig's comment, look at [wiki merge sort](https://en.wikipedia.org/wiki/Merge_sort) for examples that use a one time allocated working array. Also top down merge sort is mostly used for learning. Most implementations of merge sort in libraries are variations of bottom up merge sort (wiki explains these as well).
Answer: in

void merge(int l, int m, int r)
{
int i, j, k;
int n1 = m - l + 1;
int n2 =  r - m;

/* create temp arrays */
int L[n1], R[n2];
...

Probably L and R are too large to be placed in the stack, the size of the stack is limited, do ulimit-a to see the limit.
If this is the reason you will have to allocate them in the heap (malloc), and don't forget after to free them ;-)

When you need a big array whose size if a constant (this is not the case here) and the function using it is not directly nor indirectly recursive, you can use a static var, I mean for example : void foo() { ... static int v[4096]; ... } rather than void foo() { ... int v[4096]; ... }