pytest - How can I pass pytest addoption value to pytest parameterize?

Question: I have to to pass an argument in my pytest command which I am storing in pytest addoption. I want to use these values in the pytest parametrize function.
Command:
pytest --range-from 3 --range-to 5 test.py

conftest.py:
def pytest_addoption(parser):
    parser.addoption("--range-from", action="store", default="default name")
    parser.addoption("--range-to", action="store", default="default name")

test.py:
@pytest.mark.parametrize('migration_id', migration_list[range-from:range-to])
def test_sync_with_migration_list(migration_id):
    migration_instance = migration.parallel(migration_id=migration_id)
    migration_instance.perform_sync_only()

I want to use the value of range-from and range-to inside parametrize.
I am not able to use these values. Please suggest how can this can be done.
Answer: One simple way is assign your command line argument to environment variable and use wherever you want. I am not sure in which manner you want to use the variables then so here i am putting simple print statement inside test.
conftest.py
def pytest_addoption(parser):
    parser.addoption("--range-from", action="store", default="default name") #Let's say value is :5
    parser.addoption("--range-to", action="store", default="default name") #Lets's say value is 7

def pytest_configure(config):
    os.environ["range_from"]=config.getoption("range-from")
    os.environ["range_to"]=config.getoption("range-to")

test.py:
@pytest.mark.parametrize('migration_id', [os.getenv("range_from"),os.getenv("range_to")])
def test_sync_with_migration_list(migration_id):
    print(migration_id)

Output :
5
7

Hope it would help !!
Comment: One small correction: `config.getoption("range_from")`, replacing `-` by `_`. See: https://docs.python.org/3/library/argparse.html#dest
Answer: You cannot directly access the options from parametrize, because they not available at load time. You can instead configure the parametrization at run time in pytest_generate_tests, where you have acces to the config from the metafunc argument:
test.py
@pytest.hookimpl
def pytest_generate_tests(metafunc):
    if "migration_id" in metafunc.fixturenames:
        # any error handling omitted
        range_from = int(metafunc.config.getoption("--range-from"))
        range_to = int(metafunc.config.getoption("--range-to"))
        metafunc.parametrize("migration_id",
                             migration_list[range_from:range_to])

def test_sync_with_migration_list(migration_id):
    migration_instance = migration.parallel(migration_id=migration_id)
    migration_instance.perform_sync_only()


Taylor expansion of $\sin(x-y)$

Question: A question asks me to find the partial derivatives of $f: \mathbb{R}^2 \to \mathbb{R}$ with $f(x, y) = \sin(x-y)$ then asks me to give the taylor expansion of $f(\pi/2+h, k)$ in powers of $h$ and $k$ upto and including second order terms. My trouble is I don't understand what the question is asking. I keep evaluating the partial derivatives of $f$ at $(x, y) = (\pi/2+h, k)$ and that gives me an equation that doesn't simplify.
Answer: The formula to use is the following
\begin{align*}
f(\pi/2+h,k) & \approx f(\pi/2,0)+h\frac{\partial f}{\partial x}(\pi/2,0)+k\frac{\partial f}{\partial y}(\pi/2,0)+\frac{h}{2}\frac{\partial^2 f}{\partial x^2}(\pi/2,0)\\
& + \frac{k}{2}\frac{\partial^2 f}{\partial y^2}(\pi/2,0)+ hk \frac{\partial^2 f}{\partial x \partial y}(\pi/2,0).
\end{align*} This is simply the Taylor's formula at $(\pi/2,0)$ expanded to order $2$. Can you now finish the exercice ?
Comment: Thank you. Could I ask something, though, what's the purpose of $h$ and $k$ here, if they wanted the expansion of $f$ at $(\pi/2, 0)$? That's what confused me. In other words, what's the difference between $f(\pi/2, 0)$ and $f(\pi/2+h, k)$?
Comment: You assume that $h$ and $k$ are small. Hence $f(\pi/2+h,k)$ is the value of $f$ near $f(\pi/2,0)$. Of course these are not equal and the error of this approximation can be quantified thanks to the derivatives.

Taylor expansion of $\sin(x-y)$


How to use less code for this situation

Question: Currently, I have code like this:
    static void Main()
    {
        int whichClass = 0;
        if (whichClass == 0)
        {
            //repeat code
            TestAbstract clTest = new ClassA();
            clTest.MainFunc();
        }
        else if (whichClass == 1)
        {
            //repeat code
            TestAbstract clTest = new ClassB();
            clTest.MainFunc();
        }
        else if (whichClass == 10)
        {
            //repeat code
            TestAbstract clTest = new ClassX();
            clTest.MainFunc();
        }
    }

As you see, I have to write code 3 times for initial and call function at 3 different classes.
What I want is we just call 1 time with dynamic class. How can it is possible?
Comment: Belongs on http://codereview.stackexchange.com/ ?
Answer: Well, you could have a Dictionary<int, Type>, or a Dictionary<int, Func<TestAbstract>:
var typeMapping = new Dictionary<int, Type>
{
    { 0, typeof(ClassA) },
    { 1, typeof(ClassB) },
    { 10, typeof(ClassX) }
};

...
Type type;
if (typeMapping.TryGetValue(whichClass, out type))
{
    TestAbstract test = (TestAbstract) Activator.CreateInstance(type);
    test.MainFunc();
}

Using a Func<TestAbstract> would give more flexibility for how you created the TestAbstract instances, and provide more compile-time type safety, but be more long-winded:
var factoryMapping = new Dictionary<int, Func<TestAbstract>>
{
    { 0, () => new ClassA() },
    { 1, () => new ClassB() },
    { 10, () => new ClassX() }
};

...
Func<TestAbstract> factory;
if (factoryMapping.TryGetValue(whichClass, out factory))
{
    TestAbstract test = factory();
    test.MainFunc();
}

It's not clear where the integer values are coming from, by the way - you might want an enum for that. Heck, the enum names could even be the names of the types:
TestClass whichClass = TestClass.ClassA;

...

Type type = Type.GetType("SomeNamespace." + whichClass);
TestAbstract test = (TestAbstract) Activator.CreateInstance(type);

Comment: Damn it, Skeet... you edited in the second half of the post just as I was writing out that version. +1
Comment: yes. You definately help me a lot. Thank you.
Answer: You can create a Factory class, which would return the object according to the parameter
passed.
public static TestAbstractFactory
{
  public static TestAbstract GetTestAbstract(int whichClass)
  {
      switch(whichClass)
      {
      case 0:
        return new ClassA();
      case 1:
        return new ClassB();
      case 10:
        return new ClassX();
      default:
        return null;
      }
  }
}

Comment: yes. Thank you. I'll try to apply this.
Answer: static void Main()
{
        int whichClass = 0;
        TestAbstract clTest = null;
        if (whichClass == 0)
            clTest = new ClassA();
        else if (whichClass == 1)
             clTest = new ClassB();
        else if (whichClass == 10)
             clTest = new ClassX();
        if(clTest != null)
             clTest.MainFunc();

}
Comment: yes. Thank you. I'll try to apply this.
Answer: Assuming ClassA to C derives from TestAbstract and assuming MainFunc is a virtual method on TestAbstract, you can use the following code
static void Main()
{
    int whichClass = 0; // 0 to 2
    Type type = new[] { typeof(ClassA), typeof(ClassB), typeof(ClassC) } [ whichClass ];
    TestAbstract clTest = (TestAbstract) Activator.CreateInstance(type);
    clTest.MainFunc();
}

Comment: yes. Thank you. I'll try to apply this.
Answer: static void Main()
{
  int whichClass = 0;
  TestAbstract clTest ;
  if (whichClass == 0)
  {
   //repeat code
   clTest = new ClassA();
  }
  else if (whichClass == 1)
  {
   //repeat code
   clTest = new ClassB();
  }
 else if (whichClass == 10)
 {
  //repeat code
   clTest = new ClassX();
  }

  clTest.MainFunc();
}

Comment: yes. Thanks, but I've already knew about this approach.
Answer:
static void Main()
{
    int whichClass = 0;
    TestAbstract clTest;

    if (whichClass == 0)
    {
        //repeat code
         clTest = new ClassA();
    }
    else if (whichClass == 1)
    {
        //repeat code
        clTest = new ClassB();
    }
    else if (whichClass == 10)
    {
        //repeat code
        clTest = new ClassX();
    }
    if(clTest != null)
        clTest.MainFunc();
}

Comment: yes. Thanks, but I've already knew about this approach.
Answer: you can use reflection.
string whichClass = "className";
Type t = Type.GetType(whichClass);
TestAbstract o = (TestAbstract)Activator.CreateInstance(t);
o.MainFunc();

Comment: yes. Thank you. I'll try to apply this.

How to use less code for this situation


Is there an Input Filter without built-in restrictions?

Question: Is there an Input Filter without built-in restrictions? The built-in Drupal filters and some of the other filters I have checked seem to come with their built-in restrictions, eg
The Drupal's own HTML Filter format has its own built in restrictions; a list of HTML tags that can be used. JavaScript event attributes, JavaScript URLs, and CSS are always stripped.
The WYSIWYG Filter has built-in restrictions; the following elements cannot be whitelisted due to security reasons, to prevent users from breaking site layout and/or to avoid posting invalid HTML: applet, area, base, basefont, body, button, embed, form, frame, frameset, head, html, iframe, input, isindex, label, link, map, meta, noframes, noscript, object, optgroup, option, param, script, select, style, textarea, title.`
Is there any input filter module without built-in set of restrictions, or that allows the administrator to override them, for use with the Full HTML text format?
Answer: You can always just make your own text filter through the admin.
If you head to /admin/config/content/formats and click "+ Add text format," you'll be able to customize your own text format, which includes the roles who can use it, what filters you would like to use (using none should allow for any html tag to get through).
If there are some html tags you don't want showing up in your text format, use "limit allowed HTML" tag, and list the tags you want, like this:
<code><a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd> <blink>
</code>
You could event throw (as your example) a  tag in there to let it through. There is however, one big warning I need to leave you with:
====================WARNING ========================
Allowing users to place javascript on your page is a huge, huge security threat. If you decide to give users this privilege, make sure it's only with people you absolutely trust. If a text field allows JS to be placed in it, your basicly opening a door for a cross site scripting atttack.
Same holds true for the PHP filter, in fact the php filter is going away in D8, so I would really advise against using that.
Answer: the "PHP Code" input filter lets you do whatever you want, but that includes PHP too,  use with EXTREME caution.


identify author of an entity

Question: Using Drupal 8 and hooks, I am able to send an email to the current user, thanks to How to send mail programmatically in Drupal 8
and
BCC For drupal mail function.
So, I define my message in hook_entity_update() and send it in hook_mail().
I am trying to send emails in the following case.

user U1 consult a node created by user U2 (the aim is to permit to U1 to give his impression to U2 thanks to a select field). When U1 gave his impression, content is registered.
I need to send a email to U2 (the node author), but since he isn't the current user, I cannot use \Drupal::currentUser().

In hook_entity_update(), how can I identify the author of the current entity, knowing that "author" is not provided by Drupal\Core\Entity\EntityInterface?
Is there a specific service?
Comment: You most likely won't need revision, I guess your entity is also implementing [Drupal/Core/Entity/FieldableEntityInterface.php](https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21FieldableEntityInterface.php/interface/FieldableEntityInterface/8.2.x), which means you can get the author id with `$entity->get('uid')->value`
Comment: You would need to look up the revision of the content and its author. Please see https://drupal.stackexchange.com/questions/116334/preferred-way-of-loading-a-specific-entity-revision, that should give you some direction.
Answer: Afaik, there's no requirement that a Content Entity must store the id of the user who created/edited it. However, many entity types do use a common method to store the owner information - Drupal core's user module provides an EntityOwnerTrait that many entity types use. (At least Node, Media, etc, all use this trait.)
For example, if you're looking for the owner of an entity that uses this trait, you can use the getOwner() method like:
$owner_user_object = $entity->getOwner();

It's unclear if user U2, in your example, would be the owner of the entity or just the author of a particular revision. If your entity is storing revision information, and the entity extends EditorialContentEntityBase (Note that they probably do. Node, Media, etc, all extend this base class) then it's also possible to load the author of a particular revision.
First, load the revision. See @baikho's comment pointing to Preferred way of loading a specific entity revision.
$entity_revision = \Drupal::entityTypeManager()
  ->getStorage('MY_ENTITY_EYPE')
  ->loadRevision($MY_REVISION_ID);

Once you'd loaded the revision, you can get the author of that revision with the getRevisionUser() method like:
$revision_user_object = $entity_revision->getRevisionUser()

Answer: EntityInterface doesn't have any method for getting the user who created an entity because not all the entities have the concept of owner. For example, the User entity is one of those entities.
The entities for which is defined an owner implement EntityOwnerInterface.

An owner is someone who has primary control over an entity, similar to owners in Unix file system access. This may or may not be the entity's original author. The owner may also have less permissions than other users, such as administrators.

If you are implementing hook_entity_update() for a generic entity and you want to check if it has an owner, you should use code similar to the following one.
use \Drupal\Core\Entity\EntityInterface;
use \Drupal\user\EntityOwnerInterface;

function hook_entity_update(EntityInterface $entity) {
  if ($entity instanceof EntityOwnerInterface) {
    // The entity has an owner (a.k.a. an author).
    $author_id = $entity->getOwnerId();
    $autor = $entity->getOwner();
  }
}

If the entity implements RevisionLogInterface (which means it supports revisions, and it usually extends  RevisionableContentEntityBase), then it also defines a revision author, returned from getRevisionUser().

identify author of an entity


Suppose $f:[0,1] \Rightarrow \mathbb{R}$ is continuous and $\int_0^x f(x)dx = \int_x^1 f(x)dx$. Prove that $f(x) = 0$ for all $x$

Question: Suppose $f:[0,1] \Rightarrow \mathbb{R}$ is continuous and $\int_0^x f(x)dx = \int_x^1 f(x)dx$. Prove that $f(x) = 0$ for all $x$.
So, I can intuitively see that this is true. My proof mostly makes sense, I think, but I'm not sure if it covers the case where there are negative and positive values in each segment, resulting in a mean value of 0, but still having nonzero values. Can someone tell me how to cover that, or how this does?
Suppose $f(x) \neq 0$ for all x $\in$ [0,1]. By the mean value theorem, there exist some c and d for which $f(c)(x) = f(d)(1-x) = \int_0^x f(x)dx$. Since x $\neq$ (1-x) for all x $\in$ [0,1], it follows that $f(c) = f(d) = 0$. Therefore, $f(x) = 0$ for all $x \in [0,1]$.
Comment: Differentiate using FTC, to get $f(x)=-f(x)$.
Comment: Note that your $c,d$ depend on $x$. And that $1/2=1-1/2$.
Comment: Minor edit, but when you assume FSOC, negating 'for all' x results in 'for some' x
Comment: See also: [Show $f$ is constant zero function on $[a, b]$ if $\int_a^x f(t) dt = \int_x^b f(t) dt \forall x \in [a, b].$](https://math.stackexchange.com/q/1567147)
Answer: Here is another line of attack:
Since $\int_0^x f(t)dt = \int_x^1 f(t)dt$, we also have $\int_0^y f(t)dt = \int_y^1 f(t)dt$, so subtracting gives
$\int_0^y f(t)dt-\int_0^x f(t)dt = \int_y^1 f(t)dt-\int_x^1 f(t)dt$, or
$\int_x^y f(t)dt = \int_y^x f(t)dt = -\int_x^y f(t)dt$.
In other words, $\int_x^y f(t)dt = 0$ for all $x,y$.
Since $f$ is continuous, if $f(x_0) \neq 0 $ for some $x_0$, then there is some interval $[a,b]$ containing $x_0$ for which $|f(x)| \ge \frac{1}{2} |f(x_0)|$ for all $x \in [a,b]$. If follows that $\int_a^b f(t)dt \neq 0$, a contradiction.
Answer: The Fundamental Theorem of Calculus proof suggested in a comment by Peter Tamaroff is one short line, and one cannot do better.
Here is a more awkward proof that does not use the FTC. Suppose that $f(x)\ne 0$ for some $x$. Say for example that $f(a)=c\gt 0$ for some $a$. By continuity we can assume that $a$ is not $0$ or $1$. Then there is an interval $(a-\epsilon,a+\epsilon)$ contained in $(0,1)$ such that $f(x)\gt c/2$ in this interval.
Note that $\int_{a-\epsilon}^{a+\epsilon}\gt c\epsilon\gt 0$.
Let $x_1=a-\epsilon$, and $x_2=a+\epsilon$. Then if $\int_0^{x_1} f(t)\,dt=\int_{x_1}^1 f(t)\,dt$, we must have $\int_{0}^{x_2} f(t)\,dt \gt \int_{x_2}^1 f(t)\,dt$.
Answer: $\newcommand{\+}{^{\dagger}}%
 \newcommand{\angles}[1]{\left\langle #1 \right\rangle}%
 \newcommand{\braces}[1]{\left\lbrace #1 \right\rbrace}%
 \newcommand{\bracks}[1]{\left\lbrack #1 \right\rbrack}%
 \newcommand{\dd}{{\rm d}}%
 \newcommand{\isdiv}{\,\left.\right\vert\,}%
 \newcommand{\ds}[1]{\displaystyle{#1}}%
 \newcommand{\equalby}[1]{{#1 \atop {= \atop \vphantom{\huge A}}}}%
 \newcommand{\expo}[1]{\,{\rm e}^{#1}\,}%
 \newcommand{\floor}[1]{\,\left\lfloor #1 \right\rfloor\,}%
 \newcommand{\ic}{{\rm i}}%
 \newcommand{\imp}{\Longrightarrow}%
 \newcommand{\ket}[1]{\left\vert #1\right\rangle}%
 \newcommand{\pars}[1]{\left( #1 \right)}%
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\pp}{{\cal P}}%
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,#2\,}\,}%
 \newcommand{\sech}{\,{\rm sech}}%
 \newcommand{\sgn}{\,{\rm sgn}}%
 \newcommand{\totald}[3][]{\frac{{\rm d}^{#1} #2}{{\rm d} #3^{#1}}}
 \newcommand{\ul}[1]{\underline{#1}}%
 \newcommand{\verts}[1]{\left\vert #1 \right\vert}%
 \newcommand{\yy}{\Longleftrightarrow}$
$\ds{%
\totald{}{x}\int_{0}^{x}{\rm f}\pars{\xi}\,\dd\xi
=
\totald{}{x}\int_{x}^{1}{\rm f}\pars{\xi}\,\dd\xi
\quad\imp\quad
{\rm f}\pars{x} = -{\rm f}\pars{x}\quad\imp\quad{\rm f}\pars{x} = 0}$.
Answer: I think this works:
$\int_0^0 f(x)dx =0= \int_1^0 f(x)dx$ ; so that:
$(i) \int_0^x-\int_x^1=0$
Now, we also have:
$(ii)$ $\int_0^x+\int_x^1=\int_0^1=0$ (since $\int_1^0 f(x)dx=0)$
Taking these two:
$\int_0^x-\int_1^x=\int_x^1+\int_0^x$, we get $\int_0^x f(t)dt=0$ for all $x$
So that the function $F(x)=\int_0^xf(t)dt$ is constant in $x$.
Then $\frac{d}{dx}\int_0^xf(t)dt=f(x)=0$ for all $x$
Comment: $f$ is only defined on $[0, 1]$, so $\int_0^2 f$ doesn't make sense.
Comment: Just changed it.


Adding dependencies in intelliJ

Question: I have an android project and an instruction to add this
    compile 'com.github.claucookie.miniequalizer:library:1.0.0'
as a dependency in the project.
I dont know the right options to use after i go to the project structure of the project.
Answer: Step 1:
For adding dependency go to applevel gradle file

Step 2:
Add compile 'com.github.claucookie.miniequalizer:library:1.0.0' in dependency,.after last line before}

ie. I have added your dependency shown below
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'org.greenrobot:eventbus:3.0.0'
    compile 'com.android.support:appcompat-v7:25.1.0'
    compile 'com.android.support:design:25.1.0'
    compile 'com.jakewharton:butterknife:8.4.0'
    compile 'com.android.support:cardview-v7:25.1.0'
    compile 'com.android.support:support-v4:25.1.0'
    compile 'com.squareup.retrofit2:retrofit:2.1.0'
    compile 'com.squareup.okhttp3:logging-interceptor:3.3.1'
    compile 'com.squareup.retrofit2:converter-jackson:2.1.0'
    compile 'com.android.support:recyclerview-v7:25.1.0'
    compile 'com.github.traex.rippleeffect:library:1.3'
    compile 'com.android.support.constraint:constraint-layout:1.0.0-beta4'
    compile 'com.github.bumptech.glide:glide:3.7.0'
    testCompile 'junit:junit:4.12'
    testCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5'
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.4.0'
    debugCompile 'com.squareup.leakcanary:leakcanary-android:1.5'
    releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5'
    compile 'com.github.claucookie.miniequalizer:library:1.0.0'
}

Step 3:
After this click on sync Gradle .
Answer: in your project -->gradle Scripts--> build.gradle (Module:App)
add the dependency like:
    apply plugin: 'com.android.application'

android {
    compileSdkVersion 24
    buildToolsVersion "23.0.3"

    defaultConfig {
        applicationId "rafsan.practice"
        minSdkVersion 15
        targetSdkVersion 24
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:24.2.1'
    compile 'com.github.claucookie.miniequalizer:library:1.0.0'   //add the dependency here
}

Adding dependencies in intelliJ


Is there an analytic solution for $x^r - x + a = 0$?

Question: I am trying to find the solutions to
$$x^r - x + a = 0$$
for
$$r \in \mathbb{R}, \quad 0 \leq r < 1\\
a \in \mathbb{R}, \quad a \geq 0$$
$a$ and $r$ are both fixed and I am trying to solve for $x$.
Is there a way of rewriting this as a closed-form expression? If there isn't, is there an easy way of approximating the solution?
From what I've seen graphing the equation, there is guaranteed to be exactly one root with the constraints given. This matches the context that the equation came from so I am confident that this is true.
For context, this is not homework. I am trying to rewrite an equation and am stuck at this part.
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/132151/discussion-on-question-by-agiltohr-is-there-an-analytic-solution-for-xr-x).
Answer: Background
There is a good accepted answer by @Claude Leibovici, but we use the Inverse of the Regularized Incomplete Beta function $\text I^{-1}_x(a,b)$ defined as the median of the Beta distribution which uses the Regularized Beta function $\text I_x(a,b)$ with the following definitions: $$\text I_x(a,b)=\frac{\Gamma(a+b)}{\Gamma(b)\Gamma(a)}\int_0^x t^{a-1} (1-t)^{b-1}dt,\frac{\int_0^{\text I^{-1}_x(a,b)}t^{a-1} (1-t)^{b-1}dt }{\text B(a,b)}=\text I_{\text I^{-1}_x(a,b)}(a,b)\mathop=^{0\le x\le1}x$$ Now note that when: $$\text I_{1-x}(2,r)=rx^{r+1}-(r+1)x^r+1$$ for example let's solve for $x$: $$\text I_{1-x}(2,e)= ex^{e+1}-(e+1)x^e+1=\frac12\implies 2ex-2(e+1)+x^{-e}=0\implies x=0.587686… =1-\text I^{-1}_\frac12(2,e)$$ with this verification.
If a special case of the Regularized Beta function can be solved in closed form for its subscripted $x$ value, then you can derive many special cases for the Inverse of the Regularized Beta function in terms of other functions. Unfortunately there is a small domain, little research on the inverse function, and a limited amount of polynomials that we can use it for, but let's try the following to get a general, but slightly complicated, closed form for $x$ in $x^r-x+a$ in terms of $\text I^{-1}_x(a,b)$ which may simplify into simpler functions if the $a,b,x$ are not too complicated.
Solution Derivation:
Assume the equation is in the form of:
$$\text I_{1-ax}(2,-r)+b=(ax)^{-r}((ax)^r-arx+r-1)+b=0\implies (ax)^r-arx+r-1+(ax)^rb=(b+1)(ax)^r-arx+r-1=0\implies x^r-\frac{ar}{(b+1)a^r}x+\frac{r-1}{(b+1)a^r}=0$$
The goal is to have the coefficient of $x$ to be $-1$, so let:
$$\frac{ar}{(b+1)a^r} =1\implies b=ra^{1-r}-1; a^r,ar\ne 0$$
Now that we have gotten rid of one variable:
$$x^r-\frac{ar}{(b+1)a^r}x+\frac{r-1}{(b+1)a^r}= x^r-\frac{ar}{(ra^{1-r}-1 +1)a^r}x+\frac{r-1}{(ra^{1-r}-1 +1)a^r}=x^r-x+\frac{r-1}{ar}=0 $$
Now we can let $\frac{r-1}{ar}=A$ to solve for $x^r-x+A=0$. Let's see what happened to the other side of the equation:
$$(ax)^r \text I_{1-ax}(2,-r)+b(ax)^r = (b+1)(ax)^r-arx+r-1=0\implies \frac x{b+1} \text I_{1-ax}(2,-r)+\frac{bx}{b+1}  = x^r-\frac{ar}{(b+1)a^r}x+\frac{r-1}{(b+1)a^r}=0 \implies \frac x{ra^{1-r}-1 +1} \text I_{1-ax}(2,-r)+\frac{ra^{1-r}-1 x}{ra^{1-r}-1 +1} = \frac{xa^{r-1}}{r}\text I_{1-ax}(2,-r)+\left(1-\frac{a^{r-1}}r\right)x=x^r-x+\frac{r-1}{ar}=0 $$
Finally:
$$\frac{xa^{r-1}}{r}\text I_{1-ax}(2,-r)+\left(1-\frac{a^{r-1}}r\right)x=x^r-x+\frac{r-1}{ar}=0 $$
Notice that both sides will always equal zero, so we can split them up and do each case separately which works:
$$ x^r-x+\frac{r-1}{ar} =0, \frac{a^{r-1}}{r}\text I_{1-ax}(2,-r)+1-\frac{a^{r-1}}r=0  \implies \text I_{1-ax}(2,-r)+  \frac r{a^{r-1}} - 1 =0$$
Old Series Approximation Method:
$$\boxed{x^r-x+\frac{r-1}{ar} =0\implies x=\frac{1-\text I^{-1}_{1-r a^{1-r}}(2,-r)}a} ,0\le 1-r a^{1-r} \le 1,r<0$$
using the "Inversebetaregularized$(z,a,b)$" command in Wolfram Alpha or Mathematica for $\text I^{-1}_z(a,b)$.
It looks like you may need complex $a,r$, but let me see later.
The formula itself looks useless, but here is proof of how it could be used with multiple domain extensions.
Here is an example using the series expansion
Now use $$x^r-x+\frac{r-1}{ar}=\sqrt[e]x-x+\frac1e-\frac1{e^2}=0, a=e^2,r=\frac1e\implies x=0.592109…, 0.0250461…$$
Using our derived formula:
$$\sqrt[e]x-x+\frac1e-\frac1{e^2}=0 \implies x=\frac{1-\text I^{-1}_{1-e^{1-\frac2e}}\left(2,-\frac1e\right)}{e^2}$$
Now plug into our series from Wolfram Functions:

First term+second term

Third term

Fourth term

Final result after adding terms, coefficients, and constants

After 4 terms in the Inverse Regularized Beta series, we get that $x≈0.02547$ when the root is actually $x=0.02504…$. Please correct me and give me feedback.
Therefore when we use the series expansion for $\text I^{-1}_z(2,b)$, we have the following final solution:
$$\boxed{x^r-x+a=0\implies x=\frac{ar\left(1-\text I^{-1}_{1-r\left(\frac{r-1}{ar}\right)^{1-r}}(2,-r)\right)}{r-1},\text I^{-1}_z(2,-r)= -\frac{2(r+1)z}{3r(r-1)}+\sqrt{\frac{2z}{r(r-1)}}+\frac{(r+1)(11r+2)\left(\frac z{r(r-1)}\right)^\frac32}{18\sqrt 2} -\frac{(r+1)(43r^2+5r-2)}{135r^2(r-1)^2}+…\in\Bbb R}$$
"Closed form:"
Transforming $$x^{-r}-x+a=0\implies x=\frac{ar\left(1-\text I^{-1}_{1+r\left(\frac{r+1}{ar}\right)^{-1-r}}(2,r)\right)}{r+1},-1\le r\left(\frac{r+1}{ar}\right)^{-1-r}\le0 $$
does not need any slow series for:
$$\boxed{x^r-x+a=0\implies x=\frac{br}{(1-r)\left(\text I^{-1}_{\frac{1-r}b\left(\frac{br}{r-1}\right)^r+1}(2,r-1)-1\right)},-1\le \frac{1-r}b\left(\frac{br}{r-1}\right)^r \le 0}$$
Test here or see formula $1$ here
Comment: Thanks! This looks like it could work. $0^r = 0$ is certainly the right assumption (based on the context the equation comes from, which I have not given to keep the question short). To be honest, this level of math is over my head and I could not say if this helps or not. But if you could find an analytic solution that would be amazing!
Comment: Very interesting approach (as usual). There is one thing which, *may be*, could be explored. Let $a=kr$ and solve for $r$ to get $$r=\frac x k-\frac{W(t)}{\log (x)} \qquad \text{where} \qquad t=\frac{\log (x)}{k}\,x^{\frac{x}{k}}$$
Comment: Your answer is very interesting (and more). What I wrote in comments was just to make a formal bridge between Lambert series and Lambert function. Cheeers :-)
Comment: @ClaudeLeibovici I will consider it, but how would you take the inverse of: $$\text I_{1-krx}(2,-r)=\text I_{\frac x k-\frac{\text W(t)}{\ln(x)}}(2,-r)$$? This requires finding the inverse of $\frac x k-\frac{\text W\left(\frac{\ln(x)}kx^\frac xk\right )}{\ln(x)}$ wrt $x$.
Comment: To all: use $r\in-\Bbb N$ to see the formula work without a sum, but with a small restriction on $a$.
Answer: The question asks

I am trying to find the solutions to $$x^r - x + a = 0$$ for
$$r \in \mathbb{R}, \quad 0 \leq r < 1\\
a \in \mathbb{R}, \quad a \geq 0$$
$a$ and $r$ are both fixed and I am trying to solve for $x$.
Is there a way of rewriting this as a closed-form expression? If there isn't, is there an easy way of approximating the solution?

The Wikipedia article
Lambert W function
section on History states:

Lambert first considered the related Lambert's Transcendental Equation in $1758,^{[3]}$ which led to an article by Leonhard Euler in $1783^{[4]}$ that discussed the special case of $we^w$.
The function Lambert considered was
$$    x=x^{m}+q. $$
Euler transformed this equation into the form
$$  x^{a}-x^{b}=(a-b)cx^{a+b}. $$
Both authors derived a series solution for their equations.

Concerning the Lambert trinomial equation the Wikipedia article
Lagrange inversion theorem
Example section states

For instance, the algebraic equation of degree $p$
$$ x^{p}-x+z=0 $$
can be solved for $x$ by means of the Lagrange inversion formula for the function $f(x) = x − x^p$, resulting in a formal series solution
$$ x=\sum _{k=0}^{\infty }{\binom {pk}{k}}{\frac {z^{(p-1)k+1}}{(p-1)k+1}}.$$
By convergence tests, this series is in fact convergent for
$ |z|\leq (p-1)p^{-p/(p-1)}, $
which is also the largest disk in which a local inverse to $f$ can be defined.

Thus, the solution can be expressed as a power series in terms of
$\,z^{p-1},\,$ hence analytic. Note that here the degree $p$ does
not need to be a positive integer. The binomial coefficient is a
rational function of $p$ and thus the power series solution makes
sense even if it is a real number. In your case, the power series
solution is
$$ x = a + a^r + r a^{2r-1} + \frac{r(3r-1)}2 a^{3r-2} +
 \frac{r(4r-2)(4r-1)}6 a^{4r-3} + \dots. $$
I doubt if it has a closed form.
Comment: Good, but what would the solution for $x$ be in the end?
Comment: I wonder the same. The Lambert W function seems related but not really the solution to my problem. And the history section doesn't talk more about the equation that matches mine, and its possible solutions.
Comment: Nice to recall Lambert series ! (+1)
Comment: Using this series, for the example I worked $(a=\pi,r=e^{-1})$, computing the partial sums, the successive values are $$\{3.14159,4.66526,4.93712,4.94395,4.94130,4.94150,4.94154,4.94153\}$$
Comment: @Somos It is useful to know how to arrive at the formula for the inverse of $x^r-x$, but how does one get the factorial coefficients from $$\left(\frac {d^{n-1}}{dx^{n-1}}\left(\frac{x-1}{x^r+x-2}\right)^n\right)\bigg|_{x=1}$$from the inversion theorem? Maybe a generating function? Thanks
Answer: Consider that you lookk for the zero's of function
$$f(x)=x^r-x+a \qquad \text{with}\qquad 0<r<1 \qquad \text{and}\qquad a>0$$ I shall assume that $r$ is non rational, which means that $x>0$.
The solution is larger than $a$ since $f(a)>0$ and $f(x)$tends to $-\infty$. Using one single iteration of Householder method with $x_0=a$, we have, as an approximation,
$$x_1=a-\frac{3 a^{r+1} \left(r (r+1) a^{2 r}-4 r a^{r+1}+2 a^2\right)}{r \left(r^2+3
   r+2\right) a^{3 r}+18 r a^{r+2}-6 r (2 r+1) a^{2 r+1}-6 a^3}$$ Trying with $a=\pi$ and $r=\frac 1e$, this would give $x_1=4.94840$ while the solution is $x=4.94153$.
Edit
What we can also do is to make two iterations of Newton method and have
$$x=a+\frac{a^{r+1}}{a-r a^r}-\frac{\frac{a^r}{r a^{r-1}-1}+\left(\frac{a^{r+1}}{a-r
   a^r}+a\right)^r}{r \left(\frac{a^{r+1}}{a-r a^r}+a\right)^{r-1}-1}$$ For the worked example, this would give $x=4.94156$.
Update
In fact, the solution is larger than $x_0=a+a^r > a$ (then better).
The first iteration of Halley method will give
$$x_1=x_0-\frac{2 f(x_0) f'(x_0)}{2 f'(x_0)^2-f(x_0) f''(x_0)}$$ with
$$f'(x)=r x^{r-1}-1 \qquad \text{and} \qquad f''(x)=(r-1) r x^{r-2}$$ For the worked example, this would give $x_0=4.66526$ and $x_1=4.94150$
We could even improve the value of $x_0$ drawing the straight line joining points $[a,f(a)]$ and $[a+a^r,f(a+a^r)]$ and have
$$x_0=a+\frac{a^{2 r}}{2 a^r-\left(a+a^r\right)^r}$$ For the worked example, this would give $x_0=4.94813$
Making one iteration of Newton method $\big[$notice that I decreased the order of the method from $4$ (Householder) to $3$ (Halley) and now to $2$ (Newton)$\big]$
$$x_1=a+\frac{a^{2 r}}{2 a^r-\left(a^r+a\right)^r}+\frac{\frac{a^{2 r}}{2 a^r-\left(a^r+a\right)^r}-\left(\frac{a^{2 r}}{2
   a^r-\left(a^r+a\right)^r}+a\right)^r}{r \left(\frac{a^{2 r}}{2
   a^r-\left(a^r+a\right)^r}+a\right)^{r-1}-1}$$ which, for the worked example, gives $x_1=4.9415303$ while the "exact" solution is
$4.9415299$
Answer: There is a multivalued function called Lambert-Tsallis https://doi.org/10.1016/j.physa.2019.03.046, $W_q(z)$. It is the solution of $ W_q(z) \cdot \bigg( 1 + (1-q)\cdot W_q(z) \bigg)^\frac{1}{1-q} = z$
At your problem, one can show that
$x=-\frac{1}{m} \cdot W_{\frac{m-1}{m}}(-m\cdot a^m)$. A few values are provided below
\begin{matrix}
a & m & q & z & W_q(z) & x\\
+5.0 & +0.1 & +2.1111 & +0.2114 & (+0.17421 , -0.00000i) & (+6.20016 , +0.00000i) \\
+5.0 & +0.5 & +3.0000 & +0.2236 & (+0.17913 , -0.00000i) & (+7.79129 , +0.00000i) \\
+5.0 & +0.7 & +4.3333 & +0.1851 & (+0.15027 , +0.00000i) & (+10.01829 , -0.00000i) \\
\end{matrix}
Answer: $$x^r-x+a=0$$
For rational $r$, the equation is related to an algebraic equation over the reals and we can use the known solution formulas and methods for algebraic equations.
Also, the equation is in a form similar to a trinomial equation.
$$x^r-x+a=0$$
$$-x^r+x-a=0$$
$x\to at$:
$$t-a^{r-1}t^r-1=0$$
$a^{r-1}\to y$, $r\to\alpha$:
$$t-yt^\alpha-1=0$$
Now the equation is in the form of equation 8.1 of [Belkic 2019]. Solutions in terms of Bell polynomials, Pochhammer symbols or confluent Fox-Wright Function $\ _1\Psi_1$ can be obtained therefore.
$\ $
Szabó, P. G.: On the roots of the trinomial equation. Centr. Eur. J. Operat. Res. 18 (2010) (1) 97-104
Belkić, D.: All the trinomial roots, their powers and logarithms from the Lambert series, Bell polynomials and Fox–Wright function: illustration for genome multiplicity in survival of irradiated cells. J. Math. Chem. 57 (2019) 59-106
Comment: Interestingly, there is are [Fox H to Meijer G](https://resources.wolframcloud.com/FunctionRepository/resources/FoxHToMeijerG/) and [Meijer G to Hypergeometric function](https://resources.wolframcloud.com/FunctionRepository/resources/MeijerGToHypergeometricPFQ/) repository commands which may simplify the Fox (Wright) function


Views Filter on a subquery custom field

Question: I've defined a global table, like this:
  $data['custom_test']['table']['group'] = t('Custom: Test');
  $data['custom_test']['table']['join'] = array(
    // #global is a special flag which let's a table appear all the time.
    '#global' => array(),
  );

Next I added a custom field:
  $data['custom_test']['test'] = array(
    'title' => t('Test'),
    'help' => t('Show test field'),
    'field' => array(
      'handler' => 'custom_test_handler_test_field',
    ),

With this I could now make a field handler; This field handler adds a subquery:
$this->query->add_field(NULL, "(QUERY)", '(FIELD)');

And with this I can output the result.
However, when I add a filter, (using a default filter handler), the query looks something like:
AND (.test BETWEEN '20' AND '30') ))

So what it does is that it tries to prefix a table, however there are no tables (since it's a subquery).
Is there someway I can fix this by configuration, without having to say build my own filter?
Answer: I ended up creating a filter class, since I use a subquery I needed to use HAVING rather than BETWEEN.
Comment: But how did you solve the problem of it referencing a table?

Views Filter on a subquery custom field


passing main argument to method

Question: I'm trying to pass the array of strings argument from the main into my integerCheck method. The input to the main will never be more than 3 strings long. The code compiles fine, but when I try to enter an input of 3 strings I get this error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3

Where is this coming from?
private static void integerCheck(String[] b)
{
    int i;
    for(i=0;i<4;i++)
    {
        try {Integer.parseInt(b[i]);}
        catch (NumberFormatException e)
        {
        System.err.println("one of inputs not an int");
        System.exit(1);
        }
    }
}

public static void main(String[] args)
{

    integerCheck(args);
}

Comment: Think about how many times the loop will run if you pass just 3 arguments.
Comment: `i` will have the values `0`, `1`, `2`, `3` in your loop. An array with three elements will have the indices `0`, `1`, `2`.
Answer: Should be: for(i=0;i<3;i++) (If you pass 4 elements to your program, it should work with 4, but if you want only 3 inputs, it should be 3).
Why?
Because for(i=0;i<4;i++) is running on 0 1 2 3. So the length of the expected input is actually 4. So you're trying to reach b[3], and this is java.lang.ArrayIndexOutOfBoundsException.
Note: A debugger would help you a lot.. use it and you'll better understand the problem!
Answer: Very simple mistake. If you have 3 elements in the array they are indexed 0, 1 and 2. Your loop goes from 0 to less than 4, which means it tried to access elements 0, 1, 2 and 3. Element 3 does not exist, since you only gave 3 arguments. Another way to think about it is that element number 3 is the fourth element in the array (because the elements are numbered starting from 0)
Answer: Your for(i=0;i<4;i++) has more elements than string[b]
try this and replace
 for(i=0;i<4;i++)

with
 for(i=0;i<b.length;i++)

Answer: Try out this
 private static void integerCheck(String[] b)
    {
        int i;
        for(i=0;i<3;i++)
        {
            try {Integer.parseInt(b[i]);}
            catch (NumberFormatException e)
            {
            System.err.println("one of inputs not an int");
            System.exit(1);
            }
        }
    }

public static void main(String[] args)
{
     if(args.length==3)
    {
    integerCheck(args);
    }
}

Answer: The code is compiling fine because there is no syntactical error in the code you have written.
java.lang.ArrayIndexOutOfBoundsException  is a run time exception , which is encountered when you are trying to access an index which is out of the size of the array.
In the current situation you will face this whenever you pass less than 4 Argumnents while invoking the main method.
Remember Indices in java are 0 based, so you have 0 1 2 and 3 .
As per your statement you said, u are passing 3 args, which are located at 0 1 and 2 respectively, so either pass a 4th value or change your condition to for(i=0;i<2;i++).

passing main argument to method


Alterar Font Awesome com toggle() - JavaScript

Question: Estou fazendo um projeto e, estou fazendo um menu responsivo. Porém, estou com um problema de estética. Eu queria que quando eu clicasse no fa fa-bars queria que fizesse uma animação é alterasse o Font Awesome para o fa-solid fa-x, porém não sei como fazer isso. Vi alguns sites que diziam que dava para fazer isso com o classList.toggle(), porém não cheguei a nenhum resultado, já que quando eu vou colocar o ícone fa-solid fa-x aparece um erro. Aqui está uma parte do código:

function menu(x) {
   x.classList.toggle("fa-solid fa-x")
}

Answer: index.html
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

script.js
var elemento = document.getElementById("eye");
var open = true;
elemento.onclick = function() {
    if(open) {
        elemento.classList.add('fa-eye');
        elemento.classList.remove('fa-eye-slash');
    } else {
        elemento.classList.add('fa-eye-slash');
        elemento.classList.remove('fa-eye');
    }
    open = !open;
}


Similar proof of Peano's Existence Theorem

Question: As many of you will know, Peano's theorem states that if $f(x,y)$ is continuous and bounded in the strip $T: |x-x_0| \le a, |y|\le\infty  $. Then the intitial value problem $y'=f(x,y), y(x_0)=y_0$, has at least one solution in  $|x-x_0| \le a $.
Now, consider the following problem. Let $J= [0,a]$. Let $g(x)$ be a continuous function. Let $k(x,t,z)$ be a function which is continuous and bounded in {${(x,t,z)\in J\times J\times \mathbb{R}: t\lt x}$}. How can I prove that there is (at least) a solution of the equation
$$y(x)= g(x)+ \int_0 ^x k(x,t,y(t))dt, x \in J $$
Comment: What is the variable in the second slot in $k(x,y,y(t))$?
Comment: @timur I think the 2nd variable should be $t$; the OP should clarify. // Introducing $z=y-g$ we get $z(x)=\int_0^x \tilde k(x,t,z(t))\,dt$ and Peano applies. (The function $\tilde k$ differs from $k$ to account for the change we made, but is still continuous.)
Comment: Do not need edit?
Comment: hmm... thats all?
Comment: Yes that variable should be a t, i've edited it
Answer: Let $\tilde k (x,t,z) = k(z,t,z+g(t))$. This is a continuous function. By the Peano theorem, the equation $z(x)=\int_0^x \tilde k(x,t,z(t))\,dt$ has a solution. Then $y=z+g$ satisfies $$y(x)=g(x)+\int_0^x \tilde k(x,t,y(t)-g(t))\,dt = g(x)+\int_0^x k(x,t,y(t))\,dt $$
Comment: How can I see that this function is bounded?
Comment: Can I say that g(x) is bounded, because every function on a compact set is bounded. Also z is bounded? I don't see how this will finish the proof...
Comment: You assumed that $k$ is bounded. Therefore, if I plug another function into $k$, they composition is also bounded.


Why is String.prototype.substr() deprecated?

Question: It is mentioned on the ECMAScript standard here that :

... These features are not considered part of the core ECMAScript
language. Programmers should not use or assume the existence of these
features and behaviours when writing new ECMAScript code. ECMAScript
implementations are discouraged from implementing these features
unless the implementation is part of a web browser or is required to
run the same legacy ECMAScript code that web browsers encounter.

There is also a red warning on MDN : String.prototype.substr() MDN doc
Does anyone know why (ECMAScript standard say that) programmers should not use or assume the existence of String.prototype.substr ?
Comment: So, why not add `substr` to the standards, since many prefer using *substr* over *substring*? (arguing that using a length can be easier than using an index)
Comment: Replace `substr` by `slice`.  Works identical with strings.
Comment: I suspect `substring` is intended to replace it - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substring - substring takes a start and end position which is more conventional than start + number of characters.
Comment: @eddiewould - "Replace" is an odd term here, as `substring` has been in the standardized language since there was one, but `substr` never has. :-)
Comment: @eddiewould That's not my experience at all. Usually I know in advance the length the substring that I want. For example, if I have a date like '03-Mar-2022', I know that the month is always a fixed 3 characters long, so from a code readability and maintenance perspective, specifying "3" for the substring length is way more sensible than having to specify an ending index.
Comment: slice != substr....```> "12345678".substr( -2 , 2)
'78'
vs "12345678".slice( -2 , 2)
''
```
Comment: Don't know, but one reason why I'd avoid it is because the `.substring` method sounds *very* similar, but uses *end index* as a second parameter rather than *length*. Easy to mix up, probably, better to just use one method, if possible
Comment: In addition to what @Mesh said, it appears to me that the second parameter of slice is not a length, but an index.  That being the case, slice is identical to substring (and not substr) for strings.
Answer: Because it's never been part of the standardized language. It wasn't in the ECMAScript 1 or 2 specs at all, and only appears in ECMAScript 3 in Section B.2 ("Additional Properties") (and subsequent editions in similar annexes through to today [ES2022 draft as of this writing]), which said:¹

Some implementations of ECMAScript have included additional properties for some of the standard native objects. This non-normative annex suggests uniform semantics for such properties without making the properties or their semantics part of this standard.

Moreover, substr is largely redundant with substring and slice, but the second argument has a different meaning.
In pragmatic terms, I'd be surprised if you found a full mainstream JavaScript engine that didn't provide it; but I wouldn't be surprised if JavaScript engines targeted at embedded/constrained environments use didn't provide it.

¹ That wording has changed more recently to:

The ECMAScript language syntax and semantics defined in this annex are required when the ECMAScript host is a web browser. The content of this annex is normative but optional if the ECMAScript host is not a web browser.

NOTE
This annex describes various legacy features and other characteristics of web browser ECMAScript hosts. All of the language features and behaviours specified in this annex have one or more undesirable characteristics and in the absence of legacy usage would be removed from this specification. However, the usage of these features by large numbers of existing web pages means that web browsers must continue to support them. The specifications in this annex define the requirements for interoperable implementations of these legacy features.
These features are not considered part of the core ECMAScript language. Programmers should not use or assume the existence of these features and behaviours when writing new ECMAScript code. ECMAScript implementations are discouraged from implementing these features unless the implementation is part of a web browser or is required to run the same legacy ECMAScript code that web browsers encounter.
Comment: Is there any reason why deprecating it is better than adding it to the standardized language?  If one knows the desired length of the new string, `foo.substr(startPos, newLen);` seems cleaner than `foo.substring(startPos, startPos+newLen);`; that would be especially true of `startPos` were a more complicated expression.
Comment: Uncertainty of direction is a major problem of design by committee.  It's especially bad with C, where it's unclear whether the Standard is trying to define a core language upon which dialects can be built that are maximally suitable for a wide range of individual purposes, or to define a language that includes everything necessary to serve a majority of use cases (IMHO, the authors of the C89 rationale make it very clear they intended the former, but compiler writers treat the C Standard as the latter).  IMHO, people writing language standards need to either recognize current practices...
Comment: I much prefer substr() over substring() for most of my work - it would be nice if this was just codified into the language. It would also be nice if MDN indicated that it was technically non-standard vs. deprecated. Deprecated fully suggests that it *was* valid at some point. Grep indicates a mere 9,036 references to `.substr(` in my code... yeah this needs codification of the Cow Path.
Comment: @supercat - It isn't deprecated, it's never been part of the standard library in the first place. As for whether it would be better to just put it in the standard library, well, that's a judgement call for TC39. Since TC39 has no policy on the standard library (e.g., should it be large or small)... (I asked once. The answer is: They can't agree on a direction, so it's all case-by-case and [externally] which way the wind is blowing and whether it's a Tuesday or not. :-) )
Comment: ...or explicitly state that responsibility for doing so lies with implementations, or else perhaps recognize what current practices are while and indicate that quality implementations should uphold practices when doing so would be useful and practical, but that doing so is not required for conformance if, in an implementer's judgment, the cost of upholding a particular practice would exceed the benefits thereof.
Answer: The main advantage of substr is that you can specify a negative start position!
To do the same with substring is awful.
Comment: `.slice` supports negative start (and end) positions.
Comment: @NicoleAshley and now we have 2 functions doing almost the same thing (`slice` and `substring`), but not exactly. Yeeyyy! I will continue with `substr` if no one cares. Also, this "answer" should be a comment because it does not answer the question ^^'
Comment: Can I go _arrrrrrgh!!!!..._ on this?
Answer: I've added this declaration as an ambient declaration in a top-level ambient.d.ts file:
interface String {
  /**
   * Gets a substring beginning at the specified location and having the specified length.
   * (deprecation removed)
   * @param from The starting position of the desired substring. The index of the first character in the string is zero.
   * @param length The number of characters to include in the returned substring.
   */
  substr(from: number, length?: number): string;
}

I find substr very useful. It's often a lot more concise to specify how long you want a string to be rather than the end index of the string. If substr really ever is removed from browser or Node.js JavaScript support, I suspect many of us will simply monkey-patch substr back into existence anyway.
Comment: While I support your notion for monkey-patching it back in I'd not recommend your approach without a polyfill to jump into place in case `.substr` is suddenly not supported anymore.
Simply "hiding" the deprecation notice is just reckless.
Answer: If substr will be dropped in the future, then you can use this replacement, instead of rewriting all your JavaScript codes. It is written according to ECMA specification: https://tc39.es/ecma262/multipage/additional-ecmascript-features-for-web-browsers.html#sec-string.prototype.substr

B.2.2.1 String.prototype.substr ( start, length ) This method returns
a substring of the result of converting the this value to a String,
starting from index start and running for length code units (or
through the end of the String if length is undefined). If start is
negative, it is treated as sourceLength + start where sourceLength is
the length of the String. The result is a String value, not a String
object.
It performs the following steps when called:

Let O be ? RequireObjectCoercible(this value).
Let S be ? ToString(O).
Let size be the length of S.
Let intStart be ? ToIntegerOrInfinity(start).
If intStart = -∞, set intStart to 0.
Else if intStart < 0, set intStart to max(size + intStart, 0).
Else, set intStart to min(intStart, size).
If length is undefined, let intLength be size; otherwise let intLength be ? ToIntegerOrInfinity(length).
Set intLength to the result of clamping intLength between 0 and size.
Let intEnd be min(intStart + intLength, size).
Return the substring of S from intStart to intEnd.

String.prototype.substr = function (start, length)
{
    const S = this.toString(); // step 1 and 2
    const size = S.length; // step 3
    let intStart = Number.isNaN(Number(start)) ? 0 : Number.parseInt(start); // step 4
    if (intStart === -Infinity) intStart = 0; // step 5
    else if (intStart < 0) intStart = Math.max(size + intStart, 0); // step 6
    else intStart = Math.min(intStart, size); // step 7
    let intLength = length === undefined ? size : (Number.isNaN(Number(length)) ? 0 : Number.parseInt(length)); // step 8
    intLength = Math.max(Math.min(intLength, size), 0); // step 9
    let intEnd = Math.min(intStart + intLength, size); // step 10
    return S.substring(intStart, intEnd); // step 11
};

.. and tested using this script (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr):
const aString = "Mozilla";

console.log(aString.substr(0, 1)); // 'M'
console.log(aString.substr(1, 0)); // ''
console.log(aString.substr(-1, 1)); // 'a'
console.log(aString.substr(1, -1)); // ''
console.log(aString.substr(-3)); // 'lla'
console.log(aString.substr(1)); // 'ozilla'
console.log(aString.substr(-20, 2)); // 'Mo'
console.log(aString.substr(20, 2)); // ''


MySQL query for two users with common responses to a survey

Question: I have a MySQL table with users who have completed a survey - in some cases, they have complete the survey multiple times. So it looks like this:
users|survey_attempt|question_num|response
---------------------------------------------
john  | 1                             | 1                            | cat
john  | 1                                 | 2                            | dog
john  | 1                                  | 3                            | frog
john  | 2                                  | 1                            | dog
john  | 2                                  | 2                            | frog
john  | 2                                  | 3                            | dog
jim     | 1                                  | 1                            | frog
jim    | 1                                  | 2                            | bat
jim     | 1                                  | 3                            | bat
jim    | 2                                  | 1                            | cat
jim    | 2                                  | 2                            | frog
jim    | 2                                  | 3                            | bat
In this case, how would I find users who had common responses within the same attempt at the survey? So for instance, if I wanted to know who answered "frog" and "cat" within a unique attempt at the survey (regardless of which specific question the answer was for)?
Answer: In general, the database layout has flaws. I would suggest to use unique survey submission IDs. Because right now, you need to check user name AND survey attempt to determine if two or more rows belong to the same submission.
Anyways, you would need to self join the table and check for the answer you want but disregard the question:
<code>SELECT A.users, A.survey_attempt
FROM table A
  INNER JOIN table B ON A.users = B.users AND A.survey_attempt = B.survey_attempt
WHERE A.response = 'frog'
  AND B.response = 'cat';
</code>
The table is matched with itself, in each result table you'll have all columns two times. Then the query will only select these rows where both user names and survey attempt numbers are equal. Finally, the WHERE statement checks for the answers you wanted. Nowhere, the question number is checked as you wanted to get the result regardless of specific questions.


How to check if field is null or empty in MySQL?

Question: I am trying to figure out how to check if a field is NULL or empty. I have this:
SELECT IFNULL(field1, 'empty') as field1 from tablename

I need to add an additional check field1 != "" something like:
SELECT IFNULL(field1, 'empty') OR field1 != ""  as field1 from tablename

Any idea how to accomplish this?
Answer: Either use
SELECT IF(field1 IS NULL or field1 = '', 'empty', field1) as field1
from tablename

or use the following code, which I copied from another answer (by Himanshu) to this same question, at https://stackoverflow.com/a/17833019/441757 —

SELECT case when field1 IS NULL or field1 = ''
            then 'empty'
            else field1
       end as field1  from tablename

If you only want to check for null and not for empty strings then you can also use ifnull() or coalesce(field1, 'empty'). But that is not suitable for empty strings.
Comment: You should not add an alternative way when it is already given in other answers.
Comment: Note that if you want also to consider the strings as empty those with only spaces, you could use the TRIM function like `SELECT IF(field1 IS NULL or TRIM(field1) = '', 'empty', field1) as field1 FROM tablename`.
Answer: Using nullif does the trick:
SELECT ifnull(nullif(field1,''),'empty or null') AS field1
  FROM tablename;

How it works: nullif is returning NULL if field is an empty string, otherwise returns the field itself. This has both the cases covered (the case when field is NULL and the case when it's an empty string).
Comment: nullif(field, '') is usefull
Comment: This is very useful, but to be more clear, the second argument of ifnull() in the example should be 'empty or null'.
Answer: Alternatively you can also use CASE for the same:
SELECT CASE WHEN field1 IS NULL OR field1 = ''
       THEN 'empty'
       ELSE field1 END AS field1
FROM tablename.

Answer: You can use the IFNULL function inside the IF. This will be a little shorter, and there will be fewer repetitions of the field name.
SELECT IF(IFNULL(field1, '') = '', 'empty', field1) AS field1
FROM tablename

Answer: You can create a function to make this easy.
create function IFEMPTY(s text, defaultValue text)
returns text deterministic
return if(s is null or s = '', defaultValue, s);

Using:
SELECT IFEMPTY(field1, 'empty') as field1
from tablename

Answer: By trimming and comparing, we ensure we also take care of empty or tab or space character content in the field.
SELECT
    CASE
        WHEN LTRIM(RTRIM(col_1))='' or col_1 IS NULL THEN 'Not available'
        ELSE col_1
    END AS col_alias
FROM
    my_table

Answer: SELECT * FROM (
    SELECT  2 AS RTYPE,V.ID AS VTYPE, DATE_FORMAT(ENTDT, ''%d-%m-%Y'')  AS ENTDT,V.NAME AS VOUCHERTYPE,VOUCHERNO,ROUND(IF((DR_CR)>0,(DR_CR),0),0) AS DR ,ROUND(IF((DR_CR)<0,(DR_CR)*-1,0),2) AS CR ,ROUND((dr_cr),2) AS BALAMT, IF(d.narr IS NULL OR d.narr='''',t.narration,d.narr) AS NARRATION
    FROM trans_m AS t JOIN trans_dtl AS d ON(t.ID=d.TRANSID)
    JOIN acc_head L ON(D.ACC_ID=L.ID)
    JOIN VOUCHERTYPE_M AS V ON(T.VOUCHERTYPE=V.ID)
    WHERE T.CMPID=',COMPANYID,' AND  d.ACC_ID=',LEDGERID ,' AND t.entdt>=''',FROMDATE ,''' AND t.entdt<=''',TODATE ,''' ',VTYPE,'
    ORDER BY CAST(ENTDT AS DATE)) AS ta

Comment: here anybody can find there qry's solution.its a runing qry and hope it will b usefull for everyone
Answer: SELECT IF(TRIM(COALESCE(field1, '')) = '', '[ empty ]', field1) FROM tablename

field1 is null or any length of whitespace
See TRIM COALESCE and IS NULL for more info.
Also Working with null values from the MySQL docs
Answer: If you would like to check in PHP , then you should do something like :
$query_s =mysql_query("SELECT YOURROWNAME from `YOURTABLENAME` where name = $name");
$ertom=mysql_fetch_array($query_s);
if ('' !== $ertom['YOURROWNAME']) {
  //do your action
  echo "It was filled";
} else {
  echo "it was empty!";
}

Comment: `$isnull = (empty($ertom['YOUROWNAME']) ? empty : not empty);`

That's a little shorter..


Azure. Adding a certificate from GoDaddy CA to an Azure hosted website

Question: I am following instructions from this website on how to add a certificate to my azure hosted website. That seems to be the most common method people use to add https to their azure website
I created a  CSR in IIS manager and have it fulfilled by the CA(Godaddy in this case) I get a .crt and a .p7b. I hit "Complete Certificate Request" in IIS manager and the cert gets added. From the added certificate I'm supposed to export it as a .PFX but IIS manager has no option to export.

Instead all i see is renew. If I try to do this through MMC exporting the certificate as a .pfx is just grayed out.
What am I Doing wrong?
Comment: try this https://superuser.com/questions/1098614/how-can-i-export-a-certificate-from-mmc-as-a-pfx-file
Answer: On the IIS Machine that you created the certificate on, you will need to connect to the Local Computer Certificate manager and export the certificate from there.
Steps:
Start -> Run -> MMC
Once the MMC is up to go
File -> Add/Remove Snapin..
Select the Certificate Snap-in and follow prompts to added local computer.
Adding Local computer Certificate Manager
Once Local Computer certificate manager has been added, navigate to the personal certificate store.  You should see the certificate you created with a key next to it indicating its a certificate with private key.
Certificate with private key
From that section you should be able to export certificate.
Hope this helps.


Crop image from the left side when scaling window size

Question: Current situation: I'm using bootstrap and I have 2 columns next to each other. When I scale the browser window, the image scales with it.
Section on a large display
Section on a smaller screen
The problem:  The image that I'm working on is responsively scaling when I scale my browser window.
What I want:  Make sure that the image stays full height with the div and crop from the left side.
Comment: Try using `object-fit: cover;` in your `img` tag
Answer: At its its simplest you can display the image as a background and use the various properties to make sure it stays anchored to the right, with full height and therefore gets cropped from the left as the window decreases in size.

.image {
  width: 50vw;
  height: 50vh;
  background-image: url(https://i.stack.imgur.com/SepTG.png);
  background-size: auto 100%;
  background-position: right center;
  background-repeat: no-repeat no-repeat;
}

Note: for more modern browsers you could consider an img element and object-fit instead, but this does not work on Internet Explorer.
Comment: Thank you for you reply. I have tried to make it as a background image, but sadly that does not work. It's a Shopify template and I am limited on what I can change in the html.
Comment: Hi, you need to post the minimum HTML to show the situation then. Did you you try object-fit instead as I suggested in the answer?


Filtro com NSPredicate com herança

Question: Eu tenho uma estrutura no Core Data assim:
Cliente
--- id = inteiro
--- dados = Pessoa

Pessoa
--- nome = string

PessoaFisica < Pessoa
--- cpf = string

PessoaJuridica < Pessoa
--- cnpj = string

Como eu posso filtrar Cliente baseado nos documentos dependendo do tipo de pessoa? Por exemplo, buscar um cliente de acordo com o cpf.
Se eu fizer direto assim, ele não entende a herança e diz que não encontrou cpf em Pessoa:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"dados.cpf = %@", cpf];

Precisava de uma espécie de "casting" de dados para PessoaFisica. Alguma sugestão?
Answer: Sugiro usar o sistema de blocos:
NSPredicate *predicate = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
    Cliente *cliente = evaluatedObject;
    PessoaFisica *pessoa = cliente.dados;
    return [pessoa isKindOfClass:[PessoaFisica class]] && [pessoa.cpf isEqualToString:cpf];
}];

O truque está em [pessoa isKindOfClass:[PessoaFisica class]], que retorna YES casso pessoa seja uma instância de PessoaFisica.
Também existe o método isMemberOfClass:. A diferença dos dois é que isMemberOfClass: só retorna YES se pessoa for realmente do tipo PessoaFisica, se for uma sub classe já retornará NO. Enquanto isKindOfClass: retorna YES se pessoa for do tipo PessoaFisica ou de uma sub classe.
Espero que ajude ;)

Filtro com NSPredicate com herança


Remove empty P tags from HTML?

Question: I am trying to strip empty
 tags from a block of HTML within a Shopify theme. For some reason the remove filter is not detecting whatever the space character is inside the tag. I've even tried copy/pasting from source code into my command and it's not working.
{{ article.content | remove: '

' | remove: '

' }}

With this, it still remains:

Copy/paste of the pesky tag:

Comment: Sure, copy/paste into the message one of the P tags that won't remove.
Comment: Did you check final rendered HTML code. How empty   are rendered? It might help.
Comment: I have tried replacing all occurances of space with another character but still ` ` remains in the HTML. It seems to be some other kind of space character coming out of Shopify.
Comment: That's not what I've asked ;). On the front of the website, how these empty  tags are displayed in source code?
Comment: There is a screenshot of the source code in the original answer. The P tags appear normally.
Comment: Would you please post code instead of screenshot?
Comment: I think I found somtehing (answer below).
Answer: You can just hide all empty paragraphs with the following CSS:
p:empty {
    display: none;
}

Answer: replace
Replaces all occurrences of a string with a substring.
{{ article.content | replace: '

', '' }}

Comment: I've also tried to replace them, it doesn't work. What looks like a standard space (even in View Source) seems to be something else that the command is not matching.
Comment: I tried this method and it worked in my testing store. Since it is not working for you, maybe you could try encoding the string before rendering to see if you can work out what character is being rendered between your tags?
Answer: I think I found something by copying source code from article editor in Sublime Text.
If you try this (not tested) does it work better?
{{ article.content | remove: '
<0xa0>
' }}

Comment: Not working either. Tough one.

Remove empty P tags from HTML?


Reducing staff numbers in LilyPond

Question: I have a choral piece where some of it is 4-part divisi SATB, and some of it is unison (true unison, not octaves).  I would love to notate this in LilyPond with the two (women's & men's) staves combining visually into one staff - when in the middle of a printed line, I'd like it to actually converge to the single staff, something like this (which I just pasted together crudely in an image editor):

Is that possible in LilyPond?
Answer: Short answer: yes, or pretty close.
Basic template:
top = {
  \repeat unfold 4 { b'4 }
}
mid = {
  \stopStaff s1 \startStaff
  g'4^\markup "Tutti" 4 4 4
}
low = {
  \clef bass
  \repeat unfold 4 { e4 }
}
words = \lyricmode {
  hel -- lo good -- bye
}
otherwords = \lyricmode {
  new staff is here
}
\score {
  <<
    \new ChoirStaff <<
      \new Staff \top
      \new Lyrics \words
      \new Voice = "new" <<
        \override Staff.TimeSignature.stencil = ##f
        \override Staff.Clef.stencil = ##f
        \override Staff.KeySignature.stencil = ##f
        \mid
      >>
      \new Lyrics \lyricsto "new" \otherwords
      \new Staff \low
    >>
  >>
}

I achieved the following given the image you provided. If I look further, there's probably a way to create that spanner bar between the top and bottom staves where there isn't one previously.

Long answer: it seems to me that if you're going for an unconventional manner to instruct all voices to sing in unison (and not octaves), then there are less strange ways of showing it. For instance, if the voices need to be in unison in the middle of the page, why not continue two staves until the line break, and then cut it down to one staff and write something like "all voices in unison"? That would seem to me to be less ambiguous.
Perhaps something like:
Answer: That's pretty awful.  The usual way to typeset this is to keep the voices split while on the same line, then merge them.  LilyPond has the VerticalAxis.remove-layer property for that sort of thing.  Using it is sort-of complex.  The regression test "divisi-staves" demonstrates how to do this.
If you indeed want to change in mid-line, \stopStaff and \startStaff are your friends.  They should enable you to replace one staff setup with a different one.
Comment: By "that's pretty awful," do you mean it's going to be an awful process, or you just don't like the idea?

Reducing staff numbers in LilyPond


Loading third party PHP SDK library from a custom module drupal 7

Question: I am writing a custom drupal module (my first one in my life), and I am trying to load an external library (https://github.com/jwilsson/spotify-web-api-php), and until now I used these methods:

Loaded file array in info file
files[] = spotify-web-api-php/vendor/autoload.php,spotify-web-api-php/src/Request.php,spotify-web-api-php/src/Session.php,spotify-web-api-php/src/SpotifyWebAPI.php,spotify-web-api-php/src/SpotifyWebAPIException.php
I made this function based on another answers here (Copied the library in libraries folder)
function blve_spotify_registry_files_alter (&$files, $modules)
{
  if (!class_exists('SpotifyWebAPI\Session')) {
    $library_path = function_exists('libraries_get_path') ?
      libraries_get_path('spotify-web-api-php') : 'sites/all/libraries/spotify-web-api-php';
$files[$library_path . '/vendor/autoload.php'] = array(
  'module' => 'blve_spotify',
  'weight' => 0,
);

}
}
I used require_once but will only work on one function

None of these methods worked, when I made a function to call all the loaded files any of the methods or files I need are loaded, please help me to made it work with the required php files. Thanks in advance
Answer: Use libraries module to load 3rd party dependencies (easier way), or composer manager to load composer package (better way).
Here you can find some details and examples how to start with libraries module.
Answer: Instead of
files[] = spotify-web-api-php/vendor/autoload.php,spotify-web-api-php/src/Request.php,spotify-web-api-php/src/Session.php,spotify-web-api-php/src/SpotifyWebAPI.php,spotify-web-api-php/src/SpotifyWebAPIException.php

Try:
files[] = spotify-web-api-php/vendor/autoload.php
files[] = spotify-web-api-php/src/Request.php
files[] = spotify-web-api-php/src/Session.php
files[] = spotify-web-api-php/src/SpotifyWebAPI.php,
files[] = spotify-web-api-php/src/SpotifyWebAPIException.php

Comment: Still not working
Comment: I just  tried  and it worked but in your case is better to use composer to load that files, take a look at this: http://drupal.stackexchange.com/a/149598/4362
Answer: in Drupal 7 i used to do a quick & dirty way, surely it's not recommended, but perhaps can help you or give you inspiration:
In the following example i load a class called Carbon

create a function, i.e. : _get_carbon()

function _get_carbon() {
$carbon_path = function_exists('libraries_get_path') ? libraries_get_path('Carbon') : 'sites/all/libraries/Carbon';
$c = $carbon_path . '/src/Carbon/Carbon.php';
require($c);
$GLOBALS['carbon'] = new Carbon\Carbon();

}

everytime you need this class, call that function _get_carbon(), you'll find the class at $GLOBALS['carbon']


What exactly does M/monit mean?

Question: what exactly does M/monit mean?
Answer: Monit by itself is a standalone software monitoring application.  For example, it can restart Apache if it stops responding.
M/Monit is a somewhat centralized control panel.  You still use Monit on the individual servers, but you get an extra control panel/GUI with it.
Monit is free, M/Monit is not.
Comment: And for total peace of mind use Monit with Munin and all your server reporting tools are complete!
Comment: ok, is it possible to configure mmonit web interface and access the monit services to it
Comment: how exactly mmonit web interface can be installed?
Comment: It's a commercial product, I'm sure if you were to purchase it they would be able to help you.  I've never used it, so I really can't say.
Answer: I always assumed it stands for "multiple Monit" but I couldn't find anything to support that assumption on their website or manuals.
Comment: That's correct.
Comment: @ewwhite -> I don't question your statement, nor the Nic's, it really makes sense but, do you have some source for it?
Answer: If you're referring to the etymology of M/Monit, one of my colleagues noted that the name sounds like "I'm not it.".

What exactly does M/monit mean?


Postgresql How extract date

Question: I need get only the date from now() at my time zone, I have this query:
SELECT now() AT TIME ZONE 'America/Santiago'

And I'm getting something like this "2015-06-08 23:59:34.142569"
but I need extract only the date, how can I get it?
Thanks.
Answer: If you want the server's date,
SELECT current_date;

If you need the date for any timestamp, eg the one you've gotten into your timezone, use date().
SELECT date(now() AT TIME ZONE 'America/Santiago');

Docs: http://www.postgresql.org/docs/current/static/functions-datetime.html
Comment: Thanks for the better doc link, @a_horse_with_no_name!
Answer: For postgres you want
select current_date;

if you need to extract any of those fields out of the returned value you can use extract
EXTRACT (field FROM source)

Postgresql How extract date


Fetch Array display

Question: So i got this for display in row my sql select:
$result = mysql_query("SELECT nome_sitio, horario, contato, morada, imagem FROM sitio where id_tipo=1");

echo "

Nome
Horário
Contato
Morada
Imagem

";

while($row = mysql_fetch_array($result))
  {
  echo "
";
  echo "" . $row['nome_sitio'] . "	";
  echo "" . $row['horario'] . "	";
  echo "" . $row['contato'] . "	";
  echo "" . $row['morada'] . "	";
  echo "" . $row['imagem'] . "	";
  echo "
";
  }
echo "
";

mysql_close($con);

But i made a design in html, that with html and css looks like this:
https://i.stack.imgur.com/gb1s9.png
And the html code is:

$nome_sitio

Morada:
 $morada

Horário:
 $horario

Contato:
 $contato

Freguesia:
 $idfreguesia

Can someone help me replacing the text with the vars?
Comment: Can you do print_r($result) and post the results here
Answer: You need to escape back to PHP to display the variables:

<a href="backoffice/images_sitios/<?php echo $imagem; ?>" rel="lightbox"><img src="backoffice/images_sitios/thumbnails/<?php echo $imagem; ?>"/>

<?php echo $nome_sitio; ?>

Morada:
 <?php echo $morada; ?>

Horário:
 <?php echo $horario; ?>

Contato:
 <?php echo $contato; ?>

Freguesia:
 <?php echo $idfreguesia; ?>

Comment: i put that code here: while($row = mysql_fetch_array($result))
  {
  echo "yourcode";

and its not working ..
Comment: If you use `echo` then you don't need the `<?php` escapes, your original code should work. But you need to set all the variables from `$row`, e.g. `$nome_sitio = $row['nome_sitio'];`
Comment: what is the best way to display the select i made to the db and format the result with that design?

i just want to see all my "places", like this:http://i.stack.imgur.com/gb1s9.png

im not being able to do it
Comment: Use the first code you wrote in your question, just change things like `` to ``. I don't understand why this is a problem.
Comment: yes i know. but the " and ' screw everything. can you help me right this in an echo?
Comment: i got it working! just a question te query select the id_freguesia that is a foreign key on the table, how can i do to go get the freguesia name from the freguesias table instead of display the id of it?
Comment: Use a JOIN, of course. That's a basic SQL technique, if you don't understand then you need to review your SQL tutorials.

Fetch Array display


Diverging random walk

Question: I have a process $X_{n+1} = X_n\xi_n$ where $\xi_n\sim\mathcal N(1,1)$ and $\xi_n$ is independent of $X_n$. I need to prove that if $X_0\neq0$ then
$$
\mathsf P\{|X_n|>1\text{ for some }n\geq0\} = 1.
$$
From this I construct a random walk: $Y_n = \log|X_n|$ so
$$
Y_{n+1} = Y_n+\eta_n
$$
where $\eta_n = \log|\xi_n|$. I guess that from here I should apply the Law of Large Numbers - but I'm stacked with it. Could you help me? For now I should prove that $Y_n$ will eventually be positive a.s. starting from any point.
On the other hand, $X_n$ is a martingale which maybe also useful for deriving the desired result. If it helps, one can take $\xi_n\sim\mathcal N(m,1)$ for some $m\geq1$.
Comment: The random variable $\log|\xi|$ **is** integrable.
Comment: So your question reduces to determining whether $E\log|\xi|$ is $\ge0$ (you win) or $<0$ (you lose).
Comment: WolframAlpha? Yes you lose for $m=1$, but you win for $m\ge1.3$ or something, though.
Comment: Are you sure that the normal is $\mathcal N(1,1)$ (mean 1)?
Comment: Yes, it's not a misprint.
Comment: @Didier: Sorry, you're right.
Comment: @Didier: for $m=1$ it seems to me I lost. Could you please tell me the way of proof if $E\log|\xi|\geq 0$?
Comment: Sure, but for $m=2$ it thinks for 15 minutes already. Anyway, what about the proof for $m>1.3$?
Comment: No it does not: integral(log(x)*(exp(-(x-2)^2/2)+exp(-(x+2)^2/2)),x=0..infinity) yields 1.30433 in about two seconds.
Comment: @Didier: Does the way of taking this integral matter for this question?
Answer: Didier Piau perfectly showed an equivalence of this problem and unboundness of a random walk and also gave a solution for the latter problem in this question: When random walk is upper unbounded
Answer: Hint:
$E(x_{n} | x_{n-1}) = x_{n-1} E(\xi_{n}) = x_{n-1}$
$E(x_n) = E( E(x_{n} | x_{n-1})) = E(x_{n-1})$
Hence  $E(x_n)=x_0$
Doing the same for $E(x_n^2)$ we can show that the variance tends to infinity with $n$. Then, you are done (we are not done, we need more than this).
Comment: Do you mean I should apply Chebyshev inequality?
Comment: MMmm no, come to think of it, we need something stronger than that.  For example, a Cauchy variable has infinite variance but the probability that it's modulus is above 1 is certainly not 1. So my "you're done" sentence is false.
Answer: What is the relationship between the $\xi_n$ sequence and the $X_n$ sequence? The statement is clearly false when $\xi_n = 1/X_n$.
Comment: I assume $\xi_n$ is independent of $x_n$
Comment: Yes, they are. Edited.
Comment: Is the r.v. $\xi_n$ independent of r.v. $X_n$ or the sequence $\{\xi_n\}$ independent of the sequence $\{X_n\}$? These are different conditions. Also, are the $\xi_n$ assumed to be i.i.d? Again, the statement can be false if the $\xi_n$ have some sort of relationship among themselves.
Comment: $\xi_n\perp \mathcal F_n = \sigma\{X_k,k\leq n\}$ and $\xi_n$ are iid r.v.

Diverging random walk


Match the end of the string in Sphinx

Question: i am new to Sphinx, that's why I need a little help,
Is it possible to search only those strings whose end matches to what is passed in the parameter?
For example we have this strings in db: "12345678", "123456788" and "324233423" and we need to find strings that end with "5678", it will be "12345678".
Answer: Do need to enable 'infix' matching to match part words, with min_infix_len
http://sphinxsearch.com/docs/current.html#conf-min-infix-len
... can then use * as a wildcard
... WHERE MATCH('*5678')

Match the end of the string in Sphinx


Diophantine equation $(x+y)(x+y+1) - kxy = 0$

Question: The following came up in my solution to this question, but buried in the comments, so maybe it's worth a question of its own.  Consider the Diophantine equation
$$ (x+y)(x+y+1) - kxy = 0$$
For $k=5$ and $k=6$ the positive integer solutions are given by successive terms of OEIS sequences A032908 and A101265 respectively.
Are there positive integer solutions for any other positive integers $k$?
I know there are solutions if you remove the positivity requirement, but I've been unable to find any with positive integers.
If my programming is correct, I've been able to rule out all $k \le 500$.
Comment: Completing the square gives $(k-4)(2x+(2-k)y+1)^2-k((k-4)y-1)^2+4=0$ (for $k\neq4$)
Answer: I think it can be proven using Vieta jumping method that in order for
$k=\dfrac{(x+y)(x+y+1)}{xy}$
to be an integer for positive integers $x$ and $y$ the only values $k$ can take are $5, 6$.
Ok, we have
$x^2+y^2+x+y=(k-2)xy$
Vieta jumping is the key of the solving this problem. The idea of this method is that if $(x_0, y_0)$ is a solution to the equation, we will create another smaller solution $(x_1, y_1)$ in terms of $x_0$ and $y_0$, in a way that $x_1+y_1<x_0+y_0$ and then we make a smaller pair $(x_2, y_2)$ in terms of $x_1$ and $y_1$, and so on. We can't repeat this jumping downwards indefinitely, because natural numbers are limited from down. Hence we must end this procedure at some point, say $x_n, y_n$. If we can find $x_n, y_n$ then we can finally reconstruct $x_0, y_0$ by jumping upwards from $x_n, y_n$.
To apply this method to the equation, rewrite the equation as a quadratic in terms of $x$
$x^2+(1-my)x+y^2+y=0$
where $m=k-2>0$. Suppose that $(x_0, y_0)$ is a solution to the above equation, with $x_0 \ge y_0$. If we let $y=y_0$ in the quadratic, equation will have two solutions for $x$: $x=x_0$ and $x=x^*$. Then we will have: $x_0+x^*=my_0-1$ and $x_0 x^*=y_0^2+y_0$ from the first one, you can see that $x^*=my_0-1-x_0$ is an integer, and from second $x^*=\frac{y_0^2+y_0}{x_0}$ is positive.
Therewith, if $x_0 \ge  \frac{y_0^2+y_0}{y_0}=y_0+1 $, then $x^*=\frac{y_0^2+y_0}{x_0} \le y_0$, and we can choose $ (x_1, y_1)=(y_0, x^*)$ as a smaller solution to the equation.
Repeating this procedure as mentioned above, we will encounter a solution $(x_n, y_n)$ where $x_n< \frac{y_n^2+y_n}{y_n}=y_n+1$, and we can no longer jump downwards. Now we must find the possible values of smallest solutions i.e. possible values of $(x_n, y_n)$. Note that $y_n \le x_n <y_n+1$. It follows that $x_n=y_n$, put this back in the original equation:
$x_n^2+(1-m x_n)x_n+x_n^2+x_n=0$
$x_n+1-m x_n+x_n+1=0$
$m=\frac{2(x_n+1)}{x_n}$
Therefore $x_n |2(x_n+1)$ or $ x_n| 2(x_n+1)-2x_n=2$ which gives us $x_n=1, 2$ with $m=4, 3$ and $k=6, 5$, respectively. So we must reconstruct solutions using two cases: $(x_n, y_n)=(1, 1)$ with  $k=6$ and  $(x_n, y_n)=(2, 2)$ with $k=5$.
Note that $(x_n, y_n)=(y_{n-1}, (k-2)y_{n-1}-x_{n-1}-1)$ and since $x_n=y_{n-1}$ we get $(x_{n-1}, y_{n-1})= ((k-2)x_n-y_n-1, x_n)$.
These result will reproduce OEIS sequences A032908 and A101265.
Answer: This really is Vieta Jumping, I ought to have put that first line. I put about five pictures of the relevant hyperbolas at the end of this post.
Actual reference: In 1907, A. Hurwitz wrote Über eine Aufgabe der unbestimmten Analysis, in Archiv der Mathematik und Physik, pages 185-196. I give a summary and a little discussion at https://mathoverflow.net/questions/84927/conjecture-on-markov-hurwitz-diophantine-equation
We will be carefully examining the part $x,y > 0$ in the graph of
$$ x^2 - q x y + y^2 + x + y = 0, $$ especially what happens as we get near the origin. Note that for $q=3$ we get the integer point $(2,2),$ for $q=4$ we get the lattice point $(1,1),$ but for $q=5$ we seem to miss any integer points. It turns out that is all that needs to be proved, that for $q \geq 5$ we get no lattice points near the origin. Technique written out very well in Hurwitz (1907).
In the fourth image, we see how the Hurwitz fundamental solutions lie between $y = \frac{qx-1}{2}$ and  $x = \frac{qy-1}{2}$ along the curve
$ x^2 - q x y + y^2 + x + y = 0, $ and that both $x,y < 1$ there. So that proves it.
Part of a careful proof is to confirm that the Hurwitz mappings below, also called Vieta Jumping, do not magically take us from the hyperbola branch in the first quadrant to the other branch, which passes through the origin and contains other integer solutions as well. It suffices to show that the largest value of $y$ on that branch is smaller than $1.$ This occurs, by implicit differentiation, where $2x-qy+1 = 0,$ or $$y = \frac{1}{q}(2x+1),$$ with $q \geq 3$ no matter what. When $x < 0,$ $2x+1 < 1,$ finally $ \frac{1}{q}(2x+1) < 1.$ That is, while there really is a solution at $(0,0),$ there are no integer solutions with $xy < 0.$
Hurwitz: given a solution with $x,y > 0$ integers, we get a solution that usually shrinks $x+y$ with either
$$ (x,y) \mapsto (qx-y-1,x),  $$ or
$$ (x,y) \mapsto (y,qy-x-1).  $$
I should add that Hurwitz did not bother about the order of the variables, he passed very quickly over the case of two variables. I wrote the "jumps" this way so as to keep on the same half-branch ($y \geq x$ or $x \geq y$) of the hyperbola in the first quadrant, so as to fit in with some presentations I found of Vieta jumping; I will leave them written this way, but it hardly matters.
Since $x,y>0,$ we know that both $qx-y-1,$ $qy-x-1$ are positive as well; there are no solutions with $xy<0,$ and when one of $x,y$ is $0,$ the other is $0$ or $-1.$
We keep applying these transformations to get a sequence of solutions, until we reach a fundamental solution, at the minimum of $x+y,$ i.e.  $qx-y-1 \geq y$ and $qy-x-1 \geq x,$
or
 $$ y \leq \frac{qx-1}{2} \; \; \mbox{AND} \; \;  x \leq \frac{qy-1}{2}, $$
which are the extra pair of lines I drew in the final two pictures. We do not need to pay much attention to whether $x$ or $y$ is larger, really.
I added in a picture with my $q=9,$ the entire arc is even more firmly within the strict standard unit square, that is $x,y < 1.$
The $y$ coordinate at $x = (2y+1)/ q$ satisfies
$$   (q^2 - 4)y^2 - (2q+4)y - (q+1) = 0. $$
For $q=3,4$ the positive root exceeds $1.$ However, for $q \geq 5,$ the positive root is smaller than one. For $q=5,$ $y = \frac{14 + 10 \sqrt 7}{42} \approx 0.963,$ so  true for $q=5.$
Then
$$ y < \frac{1 + \sqrt{q+2}}{q-2}, $$
 and that inequality finishes the proof for $q \geq 6.$
Wednesday, September 2. I found a prettier way to to the final bound on the positive value of $y,$ or, rather, show that it is strictly below $1.$ We have, where the Hurwitz bounding line $x = (2y+1)/ q$ meets the hyperbola in the first quadrant,
$$   (q^2 - 4)y^2 - (2q+4)y - (q+1) = 0. $$ Subtract $1$ from both sides, we have
$$   (q^2 - 4)y^2 - (2q+4)y - (q+2) = -1. $$ Next divide through by $(q+2),$ for
$$   (q - 2)y^2 - 2y - 1 = \frac{-1}{q+2} < 0. $$
For the left hand side to be negative with $y$ positive, the quadratic formula says we need strict
$$ \color{blue}{ y < \frac{1 + \sqrt{q-1}}{q-2}}. $$
For $q=5$ this says $y<1,$ exactly what we need. For $q > 5$ the restriction is stronger still.
Answer: For the equation:
$$(x+y)(x+y+1)=kxy$$
Use the standard approach of using Pell equations.  If you use solutions of this equation.
$$p^2-k(k-4)s^2=1$$
Decisions can be recorded.
$$x=-(p^2+2kps+k(k-4)s^2)(p^2+2(k-2)ps+k(k-4)s^2)$$
$$y=-4ps(p^2+2kps+k(k-4)s^2)$$
If this equation Pell.
$$p^2-k(k-4)s^2=\pm1$$
Then decisions can be recorded.
$$x=\pm2(p-ks)s$$
Or.
$$x=\mp(p^2+2(k-1)ps+k(k-2)s^2)$$
For this.
$$y=\mp2(p+ks)s$$
Number  $p,s - $  can have any sign.
An interesting case of when.  $k=4$
The formulas can be seen that while the $s$ can be anything. And  $p=\pm1$
Comment: So what is your conclusion? Are there positive integer solutions for any other positive integers $k$?
Comment: @barto  I don't understand the question.  I wrote the decision.  What's not clear?
Comment: It's hard to deduce from your answer whether the answer to `Are there positive integer solutions for any other positive integers k?` is 'yes' or 'no'...
Comment: @barto  I wrote a formula which set the solution using the solutions of Pell equations. $p^2-k(k-4)s^2=\pm1$
Answer: What I got so far:
First, solve for $x$:
$$
x=\frac{k y-2 y-1\pm\sqrt{k^2 y^2-4 k y^2-2 k y+1}}{2}
$$
$x$ is only an integer, if the discriminant is a perfect square, so:
$$
k^2 y^2-4 k y^2-2 k y+1=z^2
$$
Solving this for $y$:
$$
y=\frac{k\pm\sqrt{k^2 z^2-4 k z^2+4 k}}{k^2-4 k}
$$
This can only happen if:
$$
k^2 z^2-4 k z^2+4 k=w^2\Rightarrow w^2-(k-4)kz^2=4k
$$
Which is a Pell equation.
If we have $w$ and $z$, then (if I made no mistakes):
$$
x=\frac{1}{4} \left(\frac{4-w}{k-4}-\frac{w}{k}+2 z\right)\qquad y=\frac{k-w}{(k-4) k}
$$
$$
x=\frac{1}{4} \left(\frac{w}{k}+\frac{w+4}{k-4}-2 z\right)\qquad y=\frac{k+w}{(k-4) k}
$$
Will give us the solutions


Laravel 5 unable to generate where conditions in foreach loop

Question: I want to generate where conditions within a foreach loop.
$query = \App\Model\ModelName::where('offerId', 3)->where('keyword', 'demo')->get();
$arr = [['setno', '=', '1'], ['deleted', '=', '0']];
$query->where(function($q) use ($arr){
  foreach($arr as $condition){
    $q->where($condition[0], $condition[1]);
  }
}

But when I dd($query); it show me the below error:

Parse error: syntax error, unexpected 'dd' (T_STRING), expecting ',' or ')'
Comment: `where` can just take that array itself, you dont have to iterate and add the wheres .... `where($arr)`
Answer: You are missing the closing bracket:
$query->where(function($q) use ($arr){
  foreach($arr as $condition){
    $q->where($condition[0], $condition[1]);
  }
}); // <-- here

Answer: You forgot the closing ); for the where call.
$query = \App\Model\ModelName::where('offerId', 3)->where('keyword', 'demo')->get();
$arr = [['setno', '=', '1'], ['deleted', '=', '0']];
$query->where(function($q) use ($arr){
    foreach($arr as $condition){
        $q->where($condition[0], $condition[1]);
    }
});
dd($query);