Simple Mean/Average

Question: I have results from a likert scale 1 - strongly disagree-5 - strongly agree. I also had a N/A and a Not Sure category. How do I calculate the average response?
I am thinking to not include the n/a's and not sure's in my calculation because we only want to be evaluated by people who know about my company.
Please help!!!
Comment: There are several questions on the site that hit on various aspects of your question. In addition to @PeterFlom's answer below (+1), I would suggest you read through several of the highest voted threads under the likert tag ([list](http://stats.stackexchange.com/questions/tagged/likert?sort=votes&pagesize=30)).
Comment: http://stats.stackexchange.com/questions/31598/is-amazons-average-rating-misleading contains discussion of the main disagreement, between those who say that you should not use means, as a matter of principle, and those who do this and assert that it works well in practice (consider grade-point averages in universities). One simple practical point is that the median must necessarily be one of the original values and may well give the same answer for several different questions. In practice, I would often take the mean and the median and then compare carefully, looking at graphs too.
Answer: With a single Likert question, you can't really take the mean at all. If your interest is purely descriptive, just give a table or a chart of the number of people who gave each answer. Or, if you want, you could give the median, but that probably won't be as useful.
The reason you can't take the mean is because you don't know if the gaps between categories are equal.
I agree about excluding the NA and NS responses in your case.
EDIT - Example of calculating the median. Suppose your data are:
<code>1 - 100
2 - 150
3 - 300
4 - 250
5 - 200
</code>
total = 1000. The median is, of course, the number that splits the data in half. One method would be to just note that that 250 cases are 1 or 2, while 550 are 1, 2, or 3 so the median is 3. This treats the numbers as strictly ordinal.
Another method is to assume that the numbers are somehow representations of an underlying continuous variable and say that the 500th case occurs 200/250 = .8 of the way through level 3, and say the median is 3.8. I don't like this method. It's better for binned data, in my view.
Comment: thank you! How can I calculate the median? My manager wants one number that is the average response to the question. We are being evaluated on this one number each year.
Comment: I will update my answer to respond.
Comment: "*The reason you can't take the mean is because you don't know if the gaps between categories are equal.*" --- however, if you regard it as acceptable to add the individual items together, you have already assumed this. If you can add Likert items, you can calculate means of said items. If you regard calculating means as unacceptable, you have no basis on which to add items.
Comment: It's strange, but people see to accept *adding* Likert variables but not taking the mean of individual ones. In part, I think this comes from the fact that they aren't really ordinal or interval, but in between.
Answer: We all might benefit from distinguishing between "Likert" scales and "Likert-like" scales, or "Likert-appearing" scales.  They really are not quite the same.  Here's a brief background that I hope will help.
The specific procedures for constructing scales were developed before the 1960s so they are not "new" or "modern" topics to teach in college nowadays.  However, the psychometric procedures of scale development always included quite a number of specific steps which, collectively, ensured that the final scales were truly interval scales at the least. (Some practitioners argued that they might even produce ratio measurement scales.)
I suggest you find a couple old references on scale construction and development if you really want to learn why any particular scale is interval instead of ordinal or nominal. I think Likert developed his scale around 1950, and Thurstone (equally-appearing intervals) developed his in the 1930s or thereabouts.  Guttman developed his scalogram analysis procedures around the same general time period.
None of the final "short-cut" scaling products (e.g., Likert-like or Thurstone-like) by themselves can convey the logic or validity that a full set of scaling procedures build into those scales.  By the end of the 1960s, however, most scale construction procedures were discontinued.  By then, sufficient research had demonstrated that "Likert-like" shortcuts could produce results equivalent to the full scale development process.
In the late 1960s or early 1970s, the Journal of Applied Psychology devoted a full issue to this very topic.  Findings showed a very strong consensus among psychologists and psychometricians that the considerable time and expense of scale construction could be safely eliminated when scales were written by people with sufficient psychometric education and training.
From time to time, the final condition of "sufficient psychometric" background has perhaps been taken a little too much for granted.  Without a firm psychometric foundation, some simple-but-vital qualities that help to ensure scale validity can easily be missed during development.  Just like anything else that can become complex, people who lack a sufficient background might very well produce invalid scales through a simple lack of knowledge.
People who use scale products as part of their professional careers should certainly have at least a moderate level of psychometrics in their educational preparation. If a college fails to recognize that connection then that college is producing graduates were don't understand an important part of their professional practice (an opinion).
Comment: +1 Welcome to our site!  Thank you for an interesting and helpful answer.  It's especially nice to learn some of the historical background.

Simple Mean/Average


How to use multiple CSV files for machine learning anomaly detection

Question: I have a question about how to get my data in a shape that I can use for my ML model. I have multiple CSV files that I want to fit in an algorithm for anomaly detection. My data consists of many files with each being the recorded data from a sensor with two features (intensity and depth) and one timestamp per data point. Each file is labeled with 0 = faulty data and 1 = good data.
Let's say I have 20 files: y should be the label per file y = [[1], [0], ...] and X should be all the data from the sensor X = [[data_file0], [data_file1], ..., [data_file19]] that I can use to train my models. What can I do to get my data in the right format? I tried appending the data frame of every file to a list and transformed it to a dataset and a np.array and so on. I tried different shapes too.
    all_files = glob.glob(path + "/*.txt")

    df_list = []
    snr_list = []
    for filename in all_files:
        #Für jede Datei wird ein df angelegt und unwichtige features entfernt
        #try with dataset with filename and all_files
        dataset = tf.data.Dataset.from_tensor_slices(all_files)

        def parse_fn(filename):
            return tf.data.Dataset.range(10)

        dataset = dataset.interleave(lambda x:
             tf.data.TextLineDataset(x).map(parse_fn, num_parallel_calls=1),
             cycle_length=4, block_length=16)

        #try df_list
        df = pd.read_csv(filename, index_col=0, header=0, decimal = '.', delimiter = ';')
        df.drop(columns=['ET_original', 'Auslenkung_ET', 'ET_unkorrigiert'], axis = 1, inplace = True)

        #Zu jedem Zeitpunkt wird der Startzeitpunkt abgezogen: t0 = 1 ... tn = t_n - t0

        starttime = df.Zeit_ET[0]
        for row in df.itertuples():
            df.at[row.Index, 'Zeit_ET'] = df.Zeit_ET[row.Index] - starttime
        df.Zeit_ET[0] = 1

        #alle arrays einer List hinzufügen
        df_list.append(df.to_numpy().reshape(-1, 1700, 3))

        #other testings
        #test = tf.constant(pd.DataFrame(dic, columns=['1', '1', ' 1']))
        #ps=pd.DataFrame(dic, index=['dsf'])

    #df_list, test_df (1 df), und tf_const (1 df) zurückgeben
    return df_list, df.to_numpy().reshape(-1, 1700, 3), tf.constant(df.to_numpy().reshape(1, 1700, 3), dtype = tf.float32)

#nur für Testzwecke
df_list, test_df, tf_const = Alle_OCT_txt_Daten()

Comment: Before I can help you with the answer, I need to clarify a few things. Do each of the sensors take readings at the same exact times in a way that we can line them all up with a single time column?
Comment: No, each pair (each row) of  data point has its own timestemp.
Comment: And each file has multiple timestamped datapoints?
Comment: As I wrote above, i have multiple data, here are the first 6 data points of one of my file
note: Zeit_ET = a timestamp preprocessed to ns with t0 = 1 (see Code)
`columns = ['timestamp', 'Intensity', 'depth'],  array([[  1.        ,  79.        ,  -0.5273184 ],
       [ 14.        ,  94.        ,  -0.56211778],
       [ 29.        , 102.        ,  -0.59692583],
       [ 43.        , 109.        ,  -0.57392274],
       [ 57.        , 111.        ,  -0.55091889]])`

there are 6 rows from 1700
Answer: It sounds like the files are the same, but each has a distinct time stamp, right. Juts load everything into a dataframe and run your AI or ML algo on the dataframe.
# import necessary libraries
import pandas as pd
import os
import glob

# use glob to get all the csv files
# in the folder
path = 'C:\\your_path_here\\'
csv_files = glob.glob(os.path.join(path, "*.csv"))

li = []

for filename in csv_files:
    df = pd.read_csv(filename, index_col=None, header=0)
    li.append(df)

frame = pd.concat(li, axis=0, ignore_index=True)
print(frame)

Comment: hey, sry for the late reply. And nope, that did not worked
Comment: It worked fine for me. What's the exact issue?


Is there a way to check if a tag name exists in a Document? (DOM - Jython)

Question: Here's my code:
'''
Created on 27/05/2015
@author: Rederick Deathwill
'''

from java.io import File
from java.io import IOException
from javax.xml.parsers import DocumentBuilder
from javax.xml.parsers import DocumentBuilderFactory
from org.w3c.dom import Document
from org.w3c.dom import Element
from org.w3c.dom import Node
from org.w3c.dom import NodeList
from org.xml.sax import SAXException

class JXLLoader():

    def __init__(self, fileName):
        self.fileName = fileName
        self.file = File(self.fileName)
        self.dbFactory = DocumentBuilderFactory.newInstance()
        self.dBuilder = self.dbFactory.newDocumentBuilder()
        self.doc = self.dBuilder.parse(self.file)
        self.doc.getDocumentElement().normalize()

class JXLReader(JXLLoader):

    def __init__(self, fileName):
        JXLLoader.__init__(self, fileName)
        self.mainNodeList = self.doc.getElementsByTagName("main") # Here <<

if __name__ == '__main__':

    jxl = JXLReader("x.xml")
    print(jxl.mainNodeList)

    for i in range(jxl.mainNodeList.getLength()):
        node = jxl.mainNodeList.item(i)
        if (node.getNodeType() == Node.ELEMENT_NODE):
            e = node
            print(e.getElementsByTagName("value").item(0).getTextContent())

Is there a way to check if the "TagName" exists within the Document object? I don't know how to check if the tag "main" is not present. For example:
The result of that print(jxl.mainNodeList) is:
com.sun.org.apache.xerces.internal.dom.DeepNodeListImpl@58a63629

Nevertheless, if I do this with a tag that does not exist:
self.mainNodeList = self.doc.getElementsByTagName("maix")

The result when I print is an address/object just like that one (Instead of a null / None or something). The point is, how am I going to know if "" is really in the Document so that I can raise an Exception in case it isn't?
Here's the XML:
<?xml version="1.0" encoding="UTF-8"?>

    <value>100</value>
    <name>Rederick Deathwill</name>

EDIT: Also, I've checked the docs. There's not method like "hasTagName()".
Answer: Check the length of the return value of the getElementsByTagName call.
If self.mainNodeList.getLength() == 0 then the getElementsByTagName call found nothing.
Comment: You're right! Now I can raise a RuntimeError if the main tag is not in the file. Thanks!


Integrability of derivative of indefinite integral

Question: Let $G(x)=\int_a^xg(t)dt$ for some $g(t):[a,b]\rightarrow \mathbb{R}$  ($g(t)$ is Riemann integrable on $[a,b]$) , and suppose we know that $G(x)$ is differentiable on $[a,b]$. Does it follow that $G'(x)$ is Riemann integrable on $[a,b]$?
I believe this is true, but I'm completely at a loss on how to prove it, and would really appreciate any hints.
Edit: I would like to know if this is true even if $g$ is discontinuous (but still integrable). The continuous case is clear from the fundamental theorem of calculs
Comment: @SimonS I don't want to restrict $g$ to be continuous, because that case is clear from the Fundamental Theorem of Calculus (Part II). I don't think you can use FTC when $g$ is discontinuous
Answer: Your suspect is well-founded: in fact $G'$ is continuous where $g$ is continuous.
Then, since $g$ is continuous a.e. on $[a,b]$, so also $G'$ is $\dots$
Let $x_0$ be a point of continuity for $g\,$: why is $G'$ continuous in $x_0$ ?
Informally, the reason is that, if $x$ is close to $x_0$ and $h$ is small, then $\frac {G(x+h)-G(x)}h$ is close to $g(x_0)$.
The $\varepsilon-\delta$ argument starts from $$|G'(x)-g(x_0)| \le \left|G'(x)- \frac {G(x+h)-G(x)}h \right| + \left|\frac {G(x+h)-G(x)}h - g(x_0) \right|$$ knowing that $$\frac {G(x+h)-G(x)}h - g(x_0)=\frac1h \int_x^{x+h} (g(t)-g(x_0))\,dt$$Let me know if you can't conclude.
Comment: Thanks! I proved it using Darboux criterion for integrability, but didn't realise that in fact $G'$ is continuous where $g$ is, so I really appreciate your answer!


Circular reference detected for service "http_kernel" with middleware having the correct number of arguments

Question: I'm pretty confused by this.
I am experimenting with using an HTTP middleware to try to send Google Analytics page views from the server instead of the client.
However, after adding a basic middleware, I'm getting the following error:

Circular reference detected for service "http_kernel", path:
"jsonapi.file_upload -> http_kernel -> http_middleware.negotiation ->
http_middleware.reverse_proxy -> http_middleware.page_cache ->
http_middle ware.kernel_pre_handle -> http_middleware.session ->
MYMODULE.analytics_middleware".

In services.yml:
  MYMODULE.analytics_middleware:
    class: Drupal\MYMODULE\Middleware\MyModuleAnalytics
    arguments: ['@http_kernel', '@path.current', '@logger.factory' ]
    tags:
      - { name: http_middleware, priority: 180, responder: true }

MyModuleAnalytics.php:
class MyModuleAnalytics implements HttpKernelInterface {
  /**
   * The wrapped HTTP kernel.
   *
   * @var \Symfony\Component\HttpKernel\HttpKernelInterface
   */
  protected $httpKernel;

  /**
   * The current path.
   *
   * @var \Drupal\Core\Path\CurrentPathStack
   */
  protected $currentPath;

  /**
   * Logger factory.
   *
   * @var \Drupal\Core\Logger\LoggerChannelInterface
   */
  protected LoggerChannelInterface $loggerFactory;

  /**
   * Creates a HTTP middleware handler.
   *
   * @param \Symfony\Component\HttpKernel\HttpKernelInterface $kernel
   *   The HTTP kernel.
   */
  public function __construct(HttpKernelInterface $kernel, CurrentPathStack $current_path, LoggerChannelFactoryInterface $logger_factory) {
    $this->httpKernel = $kernel;
    $this->currentPath = $current_path;
    $this->loggerFactory = $logger_factory->get(MyModuleLoggerChannel::Analytics->value);
  }

  /**
   * {@inheritdoc}
   */
  public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = TRUE) {
    // Custom logic goes here.
    $current_path = $this->currentPath->getPath();
    $this->loggerFactory->info("Current path: $current_path");

    return $this->httpKernel->handle($request, $type, $catch);
  }

I can remove the circular error by removing the @http_kernel argument in services.yml:
  MYMODULE.analytics_middleware:
    class: Drupal\MYMODULE\Middleware\MyModuleAnalytics
    arguments: ['@path.current', '@logger.factory' ]
    tags:
      - { name: http_middleware, priority: 180, responder: true }

However, PHPStorm complains because the number of arguments are wrong. (But the site loads and the logger functions correctly, so maybe it's ok...?)  The documentation states:

The Drupal\Core\DependencyInjection\Compiler\StackedKernelPass
compiler pass implicitly prepends the inner kernel as first
constructor argument of the middleware. Thus, you do not need to
define arguments in your modules *.services.yml definition for the
middleware unless your middleware depends on another registered
service.

Does this mean I should never pass @http_kernel to the middleware?  Because the wording suggests to me that "you do not need to include the argument if it is the only argument, but if there are multiple arguments, you should include them all."
What is the correct way to pass arguments to a middleware service?
Answer: The kernels are stacked, so you can't add the kernel as container argument, this results in  a circular reference. Only the compiler pass can determine the inner kernel, which the outer middleware has to invoke if it doesn't return a response.
The IDE looks at the static container, it can't tell what compiler passes are adding to the service arguments, unless there is an IDE plugin adding a little extra intelligence.


select results from two tables but choose one field over another

Question: I have two tables.
tblEmployee                  tblExtraOrMissingInfo

id nvarchar(10)              id nvarchar(10)
Name nvarchar(50)            Name nvarchar(50)
                             PreferredName nvarchar(50)
                             UsePreferredName bit

The data (brief example)
 tblEmployee                 tblExtraOrMissingInfo
 id     Name                 id     Name         PreferredName   UsePreferredName
 AB12   John                 PN01   Peter        Tom             1
 LM22   Lisa                 YH76   Andrew       Andy            0
 PN01   Peter                LM22   Lisa         Liz             0
 LK655  Sarah

I want a query to produce the following result
 id     Name
 AB12   John
 LM22   Lisa
 PN01   Tom
 YH76   Andrew
 LK655  Sarah

So what I want is all the records from tblEmployee returned and any records in tblExtraOrMissingInfo that are not already in tblEmployee.
If there is a record in both tables with the same id I would like is if the UsePreferredName field in tblExtraOrMissingInfo is 1 for the PreferredName to be used rather than the Name field in the tblEmployee, please see the record PN01 in the example above.
Comment: @TabAlleman -- Not only is it obnoxious to tell people to google, you are wrong UNION does not help in this case.
Comment: Please google and learn about the UNION keyword in SQL Server.
Comment: Apologies, I did not see the bit about the UsePreferredName flag in my first read-thru.   A UNION **could** be used to reach a solution, but it would not be the best way to go.
Answer: It is slightly faster to use a left join and coalesce than to use the case statement (most servers are optimized for coalesce).
Like this:
 SELECT E.ID, COALESCE(P.PreferredName,E.Name,'Unknown') as Name
 FROM tblemployee E
 LEFT JOIN tblExtraOrMissingInfo P ON E.ID = P.ID AND P.UsePreferredName = 1

The ,'Unknown' is not needed to answer your question, but I added
  here to show that you can enhance this query to handle cases where the
  name is not available in both tables and you don't want nulls in your result
Comment: . . This is the right answer, but I would leave out the `Unknown` and just let the value be `NULL` with no match.
Comment: @GordonLinoff -- yeah... that is how I originally had it, but I wanted to show the user that this solution can be "enhanced" simply to handle the unknown case... added a comment to make that clear
Answer: left join on the employee table and use a case expression for name.
select e.id
,case when i.UsePreferredName = 1 then i.PreferredName else e.name end as name
from tblemployee e
left join tblExtraOrMissingInfo i on i.id=e.id

Answer: You can LEFT OUTER JOIN the tables together, then use a CASE statement and COALESCE() formula to get this:
SELECT
    tblEmployee.id,
    CASE WHEN UsePreferredName = 1 THEN COALESCE(PreferredName, tblEmployee.Name) ELSE tblEmployee.name
FROM
    tblEmployee
    LEFT OUTER JOIN tblExtraOrMissingInfo
        ON tblEmployee.id = tblExtraOrMissingInfo.id

CASE checks that usePreferredName value, and the COALESCE() then grabs PreferredName unless it's NULL. Then it grabs the employees name from tblEmployee.
Answer: select id ,name
from
(
select  id ,name from tblEmployee
union all
select id ,name from tblExtraOrMissingInfo
)group by id,name

Comment: This also will give the wrong result since there is no handing of the flag
Comment: With UNION instead of UNION ALL, the Group by is unnecessary.   And by the way, this will produce an error since the derived table is not aliased.
Comment: Although this code may answer the question, providing
additional context regarding _why_ and/or _how_ it answers
the question would significantly improve its long-term
value.  Please [edit] your answer to add some explanation.
Answer: This is an other way you can achieve the results. You can also use CTE to get the same result.
CREATE TABLE #tblEmployee
    (
      id NVARCHAR(10)
    , Name NVARCHAR(50)
    );

CREATE TABLE #tblExtraOrMissingInfo
    (
      id NVARCHAR(10)
    , Name NVARCHAR(50)
    , PreferredName NVARCHAR(50)
    , UsePreferredName BIT
    );

INSERT  INTO #tblEmployee
        ( id, Name )
VALUES  ( N'AB12'  -- id - nvarchar(10)
          , N'John'  -- Name - nvarchar(50)
          ),
        ( N'LM22'  -- id - nvarchar(10)
          , N'Lisa'  -- Name - nvarchar(50)
          ),
        ( N'PN01'  -- id - nvarchar(10)
          , N'Peter'  -- Name - nvarchar(50)
          ),
        ( N'LK655'  -- id - nvarchar(10)
          , N'Sarah'  -- Name - nvarchar(50)
          );

INSERT  INTO #tblExtraOrMissingInfo
        ( id, Name, PreferredName, UsePreferredName )
VALUES  ( N'PN01'  -- id - nvarchar(10)
          , N'Peter'  -- Name - nvarchar(50)
          , N'Tom'  -- PreferredName - nvarchar(50)
          , 1  -- UsePreferredName - bit
          ),
        ( N'YH76'  -- id - nvarchar(10)
          , N'Andrew'  -- Name - nvarchar(50)
          , N'Andy'  -- PreferredName - nvarchar(50)
          , 0  -- UsePreferredName - bit
          ),
        ( N'LM22'  -- id - nvarchar(10)
          , N'Lisa'  -- Name - nvarchar(50)
          , N'Liz'  -- PreferredName - nvarchar(50)
          , 0  -- UsePreferredName - bit
          );

SELECT  R.id
      , CASE WHEN tbl.UsePreferredName = 1 THEN tbl.PreferredName
             ELSE R.Name
        END AS NAME
FROM    #tblExtraOrMissingInfo tbl
        RIGHT JOIN ( SELECT id
                          , Name
                     FROM   #tblEmployee
                     UNION
                     SELECT id
                          , Name
                     FROM   #tblExtraOrMissingInfo
                   ) AS R
        ON R.id = tbl.id
           AND R.Name = tbl.Name;

Comment: Because you are using a union here you will get the wrong results even if you fix the bugs (the join is wrong).  Also your comment is wrong, you are not using a CTE for anything but creating test data.
Comment: @Hogan: Thank you for taking time to write a comment. Could you please explain what's wrong in the join. I was trying to say you can use CTE to get the desired result. I was not saying that I am using CTE to get my result. This is the result I am getting with my query above.        id NAME
AB12 John
LK655 Sarah
LM22 Lisa
PN01 Tom
YH76 Andrew
Comment: you are not using a cte to get any part of this result.  in order for there to be a cte there would need to be a "with" keyword.
Comment: this query can't be correct your join is as follows `ON R.id = tbl.id  AND R.Name = tbl.Name;`  There is **nothing in the model** that suggests joining on name would be correct.  id is clearly the key.  *Why are you joining on name?*
Comment: Thank you for the response. About the CTE. I am not saying that I am using a CTE, I am just saying you can use the concept of CTE.  I understand what you mean by the incorrect join now. Thank you for the explanation.


No Activity Found to Handle Intent? What am I doing wrong?

Question: I am taking a class that requires a build of an app in Android Studio. The professor is no help and I can't get the app to work. I have never used Android Studio before and I did this entire project purely on Google searches. I am using an emulator to display my app if that helps.
Can someone help me?
Here is my manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.ashly.recipeapp">

<application
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme"
    android:fullBackupContent="true"
    android:allowBackup="true">

    <activity
        android:name=".SplashScreen"
        android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity
        android:name=".MainActivity"
        android:label="@string/app_name">
        <intent-filter>
            <action     android:name="com.example.ashly.recipeapp.MainActivity" />
            <category android:name="android.intent.category.DEFAULT" />
            <action android:name="android.intent.action.VIEW"/>
            <category android:name="android.intent.category.BROWSABLE"/>

            <data android:scheme="http//"
                android:host="recipe-app.com"
                android:pathPrefix="/recipes"/>
        </intent-filter>
    </activity>

</application>

Here is my main activity:
package com.example.ashly.recipeapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Intent openMainActivity = new Intent ("com.example.ashly.recipeapp.MainActivity");
    startActivity(openMainActivity);

}
}

Here is my splash screen:
package com.example.ashly.recipeapp;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

public class SplashScreen extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    setTheme(R.style.splashTheme);
    super.onCreate(savedInstanceState);

    Intent intent = new Intent(SplashScreen.this, MainActivity.class);
    startActivity(intent);
    finish();

}
}

And the error I'm getting:
01-12 12:17:34.255 1824-1824/com.example.ashly.recipeapp E/AndroidRuntime:

FATAL EXCEPTION: main
Process: com.example.ashly.recipeapp, PID: 1824
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ashly.recipeapp/com.example.ashly.recipeapp.MainActivity}: android.content.ActivityNotFoundException: No Activity found to handle Intent { act=com.example.ashly.recipeapp.MainActivity }
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2184)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.content.ActivityNotFoundException: No Activity found to handle Intent { act=com.example.ashly.recipeapp.MainActivity }
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1632)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1424)
at android.app.Activity.startActivityForResult(Activity.java:3424)
at android.app.Activity.startActivityForResult(Activity.java:3385)
at android.app.Activity.startActivity(Activity.java:3627)
at android.app.Activity.startActivity(Activity.java:3595)
at com.example.ashly.recipeapp.MainActivity.onCreate(MainActivity.java:15)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)

Answer: Why are you starting Mainactivity in the onCreate method of Mainactivity?
Just remove the following two lines from your Mainactivity onCreate method:
Intent openMainActivity = new Intent ("com.example.ashly.recipeapp.MainActivity");
startActivity(openMainActivity);

Answer: Remove this code from MainActivity and it's work
 Intent openMainActivity = new Intent ("com.example.ashly.recipeapp.MainActivity");
    startActivity(openMainActivity);


Taxonomy hierarchy in filter block of views isotope?

Question: How can I set the filter block to show a hierarchical taxonomy? As far as I can see there is only a flat list being built by default. How can I change this and apply the hierarchy of a taxonomy?
This is the link of the module, of course do not answer if you do not know what is views isotope Module.
Answer: First, I'm confused about what you mean by views isotope?
But if you're asking to build a hierarchical taxonomy in view select, there's Simple hierarchical select module.

Simple hierarchical select defines a new form widget for taxonomy fields to select a term by "browsing" through the vocabularies hierarchy.
Comment: haven't any of you used views isotope? https://www.drupal.org/project/views_isotope
Comment: Oh that's a cool module, but haven't used it yet since it's still in development mode. No proper release yet.
Answer: Try the Views Term Hierarchy Weight Field module

This module allows you to display, filter or sort terms according to their hierarchical order or hierarchical depth.


Tratamento de exceção não funcionando

Question: Olá, estou estudando C# e estava tentando fazer tratamento de exceção usando middleware, para enviar a mensagem e o código da exceção para o client, porém não está dando muito certo.
Debugando, o breakpoint está passando normalmente no middleware, porém não está enviando o erro para o client. O código do middleware é este:
app.UseExceptionHandler(errorApp =>
        {
            errorApp.Run(async context =>
            {
                context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                context.Response.ContentType = "application/json";

                var error = context.Features.Get<IExceptionHandlerFeature>();

                if (error != null)
                {
                    var ex = error.Error;

                    await context.Response.WriteAsync(new ErrorDto()
                    {
                        StatusCode = context.Response.StatusCode,
                        Message = ex.Message
                    }.ToString(), Encoding.UTF8);
                }
            });
        });

public class ErrorDto
{
    public int StatusCode { get; set; }

    public string Message { get; set; }

    public override string ToString()
    {
        return JsonConvert.SerializeObject(this);
    }
}

e meu Startup.cs está assim:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
            app.UseCors("Desenvolvimento");
        else
            app.UseHsts();

        app.UseDefaultFiles();
        app.UseStaticFiles();
        app.UseHttpsRedirection();
        app.ExceptionHandler();

        app.UseMvc(opts =>
        {
            opts.MapRoute(
                name: "default",
                template: "api/{controller}/{action}/{id?}");
        });
    }

Comment: Não seria `app.UseExceptionHandler()`?
Answer: Para criar um Middleware de exception, estou usando esse tratamento aqui
Crie uma classe middleware
     public class ErrorHandlingMiddleware
        {
            private readonly RequestDelegate next;

            public ErrorHandlingMiddleware(RequestDelegate next)
            {
                this.next = next;
            }

// nesse Invoke eh possivel injetar qualquer coisa
            public async Task Invoke(HttpContext context)
            {
                try
                {
                    await next(context);
                }
                catch (Exception ex)
                {
//Capture o erro aqui
                    await HandleExceptionAsync(context, ex);
                }
            }

//Trate o erro aqui
            private static Task HandleExceptionAsync(HttpContext context, Exception exception)
            {
                var code = HttpStatusCode.InternalServerError; // 500 if unexpected
                var result = string.Empty; // coloque qualquer coisa aqui

                context.Response.ContentType = "application/json";
                context.Response.StatusCode = (int)code;
                return context.Response.WriteAsync(result); // retorne o objeto como json.
            }
        }

Depois adicione a classe no seu configure no Startup.cs
//Startup.cs

public virtual void Configure(IApplicationBuilder app)
            {
               // seu codigo aqui

                app.UseMiddleware(typeof(ErrorHandlingMiddleware));

             //Antes de app.UseMvc();
                app.UseMvc();
            }

Answer: No asp.net core você trata isso em "filters". Crie uma classe que implementa a interface "IExceptionFilter". Nela você pode usar o context para realizar todo o tratamento, você também pode injetar normalmente o que precisar no construtor. Exemplo:
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using System.Net;

namespace Exemplo1.API.Infrastructure.Filters
{
    public class HttpGlobalExceptionFilter : IExceptionFilter
    {
        private readonly IHostingEnvironment env;
        private readonly ILogger<HttpGlobalExceptionFilter> logger;

        public HttpGlobalExceptionFilter(IHostingEnvironment env, ILogger<HttpGlobalExceptionFilter> logger)
        {
            this.env = env;
            this.logger = logger;
        }

        public void OnException(ExceptionContext context)
        {
            logger.LogError(new EventId(context.Exception.HResult),
                context.Exception,
                context.Exception.Message);

            var json = new JsonErrorResponse
            {
                Messages = new[] { "Ocorreu um erro. Tente novamente." }
            };

            if (env.IsDevelopment())
            {
                json.DeveloperMessage = context.Exception;
            }

            // Result asigned to a result object but in destiny the response is empty. This is a known bug of .net core 1.1
            // It will be fixed in .net core 1.1.2. See https://github.com/aspnet/Mvc/issues/5594 for more information
            context.Result = new InternalServerErrorObjectResult(json);
            context.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;

            context.ExceptionHandled = true;
        }

        private class JsonErrorResponse
        {
            public string[] Messages { get; set; }

            public object DeveloperMessage { get; set; }
        }

    }

    public class InternalServerErrorObjectResult : ObjectResult
    {
        public InternalServerErrorObjectResult(object error)
            : base(error)
        {
            StatusCode = StatusCodes.Status500InternalServerError;
        }
    }
}

Depois é só adicionar no startup:
services.AddMvc(options =>
        {
            options.Filters.Add(typeof(HttpGlobalExceptionFilter));
        })

Para saber quais filtros são disponibilizados e em que momento eles são executados no pipeline do asp.net core, você pode acessar o seguinte link:
Filtros no ASP.NET Core

Tratamento de exceção não funcionando


c++ function overload resolution regarding templated type and class hierarchy

Question:
Possible Duplicate:
Priority when choosing overloaded template functions in C++

A templated function gives me the convenience to operate on a variety of types:
template<typename T> void destroy(T* obj) {
    delete obj;
}

But at some point I want to do some specialization on a class hierarchy:
class Base { virtual void doSomething(); };
class Derived : public Base {};
void destroy(Base* obj) {
    obj->doSomething();
    delete obj;
}

The intended specialized function did invoked if I a pass the exact type Base*, however the rules of overload resolution seems to prefer the generic templated version instead of performing a static up cast if I a pass Derived* to void detroy().
Certainly I can make all the overloaded functions for all possible derived types, but it's less maintainable.
I am using Visual C++ 2008, is there any way around the above problem?
Comment: Just found a neat answer of the same problem in stack overflow: [Priority when choosing overloaded template functions in C++](http://stackoverflow.com/questions/1332678/priority-when-choosing-overloaded-template-functions-in-c)
Comment: However your destroy function has a problem. It will be called for a 1D array type as well and you can land up doing 'delete' instead of 'delete []' which is undefined behavior.
Comment: The Op admits this Q should be closed as a duplicate.
Answer: All things being equal, overload resolution prefers nontemplate functions to function templates.  However, in this case, all things are not equal.  To match your overload for Base*, a derived-to-base pointer conversion is necessary; no conversion is necessary to match the function template.  Thus, the function template is selected for Derived*.
The "simple," albeit probably error-prone, solution would be to cast your Derived* to a Base* before you call the function.
You could, in theory at least, take an SFINAE approach as Ben suggests, but you would have to explicitly disable the generic function template for any types for which you provide specializations, otherwise you'll end up with overload ambiguities.  This is even more unmaintainable and error-prone than the explicit cast approach.  (Though, someone here may know of another way to get around the overload ambiguity; I'd certainly be interested to know if there was).
Answer: There's no such thing as Visual C++ 2009.
You may be able to specialize your function with another template and use SFINAE to only match subtypes of Base.  But I don't know any reason the compiler would prefer the second version, usually a specialization has to be "better" in some way to be selected.
Alternatively, you could use SFINAE and a helper traits class to prevent the generic version from matching subclasses of Base.  If you need an example of this, ask.
And of course your specialization will only be used where it's visible.  Templated functions are always inline, they and specializations need to be in header files included by the caller.


'onEventDeleted' trigger when click on cancel button on the event editor

Question: Im using DHTMLX scheduler and I'm trying to delete an event when click on the delete button in the popup event editor, below is my code reference.
scheduler.attachEvent("onEventDeleted", function(id,ev){
    $.ajax({
         url : "calendar.php",
         type: 'post',
         data: { event_id : id},
         success: function(e){
             if($.trim(e) === "success"){
                 alert("Event was successfully deleted");
             }
         }
  });
});

the above code works (The event was deleted successfully) but the problem is, the 'onEventDeleted' did also trigger when i click the cancel button from the popup editor. Any ideas, help, suggestions, recommendations, help please?
Answer: It happens only if you press cancel while creating a new event. In this case triggering onEventDeleted is expected since it removes a newly created event from a calendar.
In order not to send that update to the backend you can use this method
http://docs.dhtmlx.com/scheduler/api__scheduler_getstate.html
So if you update code like following everything should be good:
scheduler.attachEvent("onEventDeleted", function(id,ev){
    if(scheduler.getState().new_event)
      return;

    $.ajax({
         url : "calendar.php",
         type: 'post',
         data: { event_id : id},
         success: function(e){
             if($.trim(e) === "success"){
                 alert("Event was successfully deleted");
             }
         }
  });
});


What is the difference in State API and Config API?

Question: It is a bit confusing to understand the difference in State API and Config API in Drupal 8. I went through the documentation of both on drupal.org but it is not clear to me yet.
Do we define both State config and Config variables in config/install directory?
And How are they both distinguished?
Comment: State is environment-specific - the stuff you _don't_ push around your environments. For example the last time cron ran is specific to an environment - that's state. The list of entity types available to a site is global to all instances of that site, and so is regarded as config
Comment: Clive covered it all really, but to directly answer your question, no you don't add both State and Config to the config/install directory. There are no .yml files for State values (as state is never meant to be moved between environments). Only config files go into config/install.
Answer: Configuration is a place to store information that you want to synchronize from development to production. This information is often created during site building and is not typically generated by regular users during normal site operation.
You should use the State API, not Configuration API, for storing local variables that shouldn't travel between instances.
The State API provides a place for developers to store information about the system's state.
State information differs from configuration in the following ways:

It is specific to an individual environment.
You will never deploy to deploy it between environments.
Configuration is stored in the database, and can be exported to files (allowing migration). State is stored in the database, and cannot be exported.


Inequality based on square

Question: We need to find the range of $x$ for the following problem:
$$\frac{(x+6)(x-4)^2}{(x-6)(x+4)^2} + \frac{(x-6)(x+9)^2}{(x+6)(x-9)^2} < \frac{2x^2 + 72}{x^2 - 36}$$
They invlove the use of squares, which we have to avoid while solving inequalities.....And sadly, I cannot think of ways for trying this question. Can someone please give me hints/suggestions for solving? Formatting edits/suggestions are gladly welcomed! Question edits/suggestions are welcomed too!

EDITs:
So as discussed in the comments, I had got this for problem 1:
$$\frac{(x+6)(x-4)^2}{(x-6)(x+4)^2} + \frac{(x-6)(x+9)^2}{(x+6)(x-9)^2} < \frac{2x^2+72}{x^2-36}$$
which exapands to
$$\frac{(x+6)(x-4)^2(x+6)(x-9)^2}{(x-6)(x-4)^2(x+6)(x-9)^2} + \frac{(x-6)(x+9)^2(x-6)(x+4)^2}{(x+6)(x-9)^2(x-6)(x+4)^2} = \frac{2x^2+72}{x^2-36}$$
which simplifies to
$$\frac{(x+6)(x-4)^2(x+6)(x-9)^2 + (x-6)(x+9)^2(x-6)(x+4)^2}{(x-6)(x+4)^2(x+6)(x-9)^2} = \frac{2x^2+72}{x^2-36}$$
and right now, I am stuck. I don't dare to open up that numerator (I have no guts in front of those brackets). There has to be a much elegant and simple looking solution than this brute-force.....But the problem is.....I can't find it! Anyone who would like to show some sympathy on me after this :(
Comment: "They invlove the use of square roots and squares, which we have to avoid while solving inequalities" : What does this mean?
Comment: Please see [this article on MathSE protocol](https://math.meta.stackexchange.com/questions/33190/how-to-avoid-downvotes-for-beginners-questions/33236#33236).
As onerous as the article may appear to you, it provides a defense mechanism against the MathSE forum being used as a *do my homework* forum.  In particular, please see the **Edit-Tools** section of the article, and the portion of the article that discusses *showing work*.  It is **irrelevant** whether the problem is homework.  What counts is whether the protocol is observed.
Comment: In problem (1), what happens when you multiply everything out?  Please show your work.
Comment: Going forward with your future MathSE questions, in a similar situation, please post the problems as separate questions.  In general, there should be one Math problem presented for each posted question.
Comment: @user I meant that in general we tend to eliminate square roots and squares first in an inequality, to make it easier to comprehend and all......
Comment: @user thank you for your suggestions, i clearly understand i should post out anything that i have tried so that time is not wasted. basically i just used brute force and tried to simplify all those terms but in the end it was too overwhelming so i just stopped going further. there has to be some better approach than just brute force......
Comment: Are you saying that in problem (1), you have already attempted to
manipulate the three fractions so that they each have the common denominator of
$$(x-6) \times (x+6) \times (x+4)^2 \times (x-9)^2 ~?$$
If so, what was the result?
Comment: @user , yes, i did attempt (i wont deny that) but there are a few reasons why i did not mention it at the first place - 1) I am not happy with what I got, a long chain of terms it feels as if i have made a new polymer! (2) the place where i did all this "rough" requires extensive amounts of glue as every single page comes off that notebook (3) this is again, not a very efficient thing to do and chances of getting it incorrect is hugeeee, also i donot feel like it is even possible to solve since i have already encountered fourth degree terms on the way
Comment: I don't understand what you mean by "...requires extensive amounts of glue".  You simply proofread/organize your work, and then type it directly into the posting via [MathJax](https://math.stackexchange.com/help/notation).  Also, often, even when there is a more elegant approach, the brute force method will reveal the corresponding simplifications.  That is, you may wish to double check whether arithmetic errors have prevented you from finding a simplification.  Personally, while there may be a more elegant approach, I am unsure why you would feel that a more elegant approach must exist.
Comment: @user I am sorry for any incovience caused....i have re-edited the question now.....expanding the brackets does help simplifying a lot of things and sometimes it also reveals what the question wants! sadly, i have almost lost hope in this :(
Comment: It's not clear to me what you mean by _'the range of $x$ for the following problem'_. Are you interested in the domain, i.e. a set of $x$-es for which the inequality makes _sense_ (aka it is _defined_)? Or rather in the set of $x$-es which _satisfy_ the inequality (values, for which it is _true_)...?
Answer: Some thoughts:
Let $u = \frac{x + 6}{x - 6}$.
We have $x = \frac{6(u + 1)}{u - 1}$.
We have
$$\frac{x-4}{x+4} = \frac{u + 5}{5u + 1}, \quad \frac{x + 9}{x - 9} = \frac{5u - 1}{5 - u},
\quad \frac{2x^2 + 72}{x^2 - 36}
= \frac{(x+6)^2 + (x-6)^2}{(x - 6)(x + 6)} = u + \frac{1}{u}.$$
The inequality is written as
$$\frac{u(u+5)^2}{(5u+1)^2}
+ \frac{(5u-1)^2}{u(5-u)^2} < u + \frac{1}{u}$$
or
$$\frac{1}{u}\left(\frac{(5u-1)^2}{(5-u)^2} - 1\right) < u \left(1 - \frac{(u+5)^2}{(5u+1)^2}\right)$$
or
$$\frac{1}{u} \cdot \frac{24(u^2 - 1)}{(5-u)^2} < u \cdot \frac{24(u^2 - 1)}{(5u+1)^2}$$
or
$$24(u^2 - 1)\left(\frac{u}{(5u+1)^2} - \frac{1}{u(5-u)^2}\right) > 0$$
or
$$\frac{24 (u + 1)u(u-1)(u^2 + 1)(u^2 - 10u - 1)}{(5u+1)^2(5-u)^2u^2} > 0$$
or
$$\frac{24(u^2 + 1)}{(5u+1)^2(5-u)^2u^2}
 (u + 1)(u - 5 + \sqrt{26})u(u-1)(u - 5 - \sqrt{26}) > 0.$$
Comment: we are supposed to deduce that $u^2 + 1$ is always positive and remove all the squares in the denominator with the conditions  $u \neq \frac{-1}{5} , 5 , 0$ ??
Comment: @CuckooBeats Alternatively, you can insert $u = (x+6)/(x-6)$ back to the last inequality. You will get something like $(x-a)(x-b)(x-c)(x-d)(x-e) > 0$. For example, $(x+3)(x+1)(x-1) > 0$, the solution is $(-3, -1)\cup (1, \infty)$. But don't forget the zeros of the denominator, as you pointed out.
Comment: well this indeed was a good solution, but can we substitute better variables to the inequality? i just want to know.....although this might be the best known solution for this question, can we still try it out?
Comment: @CuckooBeats Do you mean that first the last inequality has solution $u \in (-1, -1/5)\cup (-1/5, 5 - \sqrt{26})\cup (0, 1) \cup (5+\sqrt{26}, \infty)$, then convert this solution into $x$?
Comment: no i meant the whole question......like you did $u = \frac{x+6}{x-6}$, can there be a better substitution as the solution seems lengthier, isn't it? also it would be better to first replace the value of $u$ in your last inequality and then simplify and solve for $x$.....
Comment: @CuckooBeats OK. Yes, it is simpler to replace $u$ with $x$.
Comment: hello, i have added my solution to the problem, the trick i found useful was $2a^2 +2b^2 = (a+b)^2+(a-b)^2$
Comment: @CuckooBeats It is the same as mine? You may give a complete detailed solution with final answer as an accepted answer.
Comment: oh definetly it is going to come the same, but i feel mine a bit more comfortable than yours, no offence, but it seems we need to work out more in your approach, although i had never thought the same earlier, thanks!
Comment: @CuckooBeats Your $\frac{(x+6)}{(x-6)}\cdot\left[\frac{(x-4)^2}{(x+4)^2}-1\right]+\frac{(x-6)}{(x+6)}\cdot\left[\frac{(x+9)^2}{(x-9)^2}-1\right] < 0$ is the same as my $\frac{1}{u}\left(\frac{(5u-1)^2}{(5-u)^2} - 1\right) < u \left(1 - \frac{(u+5)^2}{(5u+1)^2}\right)$. So basically the same thing.
Comment: oh yess, i did not notice that step, basically we could replace $u$ back and get the same equation.......actually i would want to do the same thing as yours when nothing strikes at my head.....
Answer: Thank you to everyone who took much time and helped me to solve the questions. Here's the solution to the first problem after a lot of research and hints from teachers. Note that this solution is analogus to @RiverLi 's solution....

We can simplify $2x^2 + 72$ as $$2\cdot x^2 + 2\cdot6^2 + 2\cdot x\cdot6 - 2\cdot x\cdot6$$
or $$(x+6)^2 + (x-6)^2$$
now, we can easily simplify the RHS
$$\frac{2x^2+72}{x^2-36} = \frac{(x+6)^2+(x-6)^2}{(x+6)(x-6)} = \frac{(x+6)}{(x-6)}+\frac{(x-6)}{(x+6)}$$
sweet! plugging this outcome in the original question:
$$\frac{(x+6)(x-4)^2}{(x-6)(x+4)^2} + \frac{(x-6)(x+9)^2}{(x+6)(x-9)^2} < \frac{(x+6)}{(x-6)}+\frac{(x-6)}{(x+6)}$$
or
$$\frac{(x+6)}{(x-6)}\cdot\left[\frac{(x-4)^2}{(x+4)^2}-1\right]+\frac{(x-6)}{(x+6)}\cdot\left[\frac{(x+9)^2}{(x-9)^2}-1\right] < 0$$
after that, you can easily simplify and go on to find the range of $x$. Make sure to not encounter fourth degree polynomials and instead eliminate terms like squares, $x^2 + 36$ as they are never negative. Also make sure to intersect the domain of $x$ while cancelling terms in the denominator.
here's the working after this:

$\frac{(x+6)}{(x-6)}\cdot\left[\frac{((x-4)+(x+4))((x-4)-(x+4))}{(x+4)^2}\right]+\frac{(x-6)}{(x+6)}\cdot\left[\frac{((x+9)+(x-9))((x+9)-(x-9))}{(x-9)^2}-1\right] < 0$

or

$\frac{(x+6)}{(x-6)}\cdot\left[\frac{(2x)(-8)}{(x+4)^2}\right]+\frac{(x-6)}{(x+6)}\cdot\left[\frac{(2x)(18)}{(x-9)^2}\right] < 0$

cancel $4$ both sides, we get

$\frac{9x(x-6)}{(x+6)(x-9)^2} - \frac{4x(x+6)}{(x-6)(x+4)^2} < 0$

this simplied result gives me eternal satisfaction I needed for this question XD
simplifying further, we get

$x\cdot\left[\frac{9(x-6)^2(x+4)^2 - 4(x+6)^2(x-9)^2}{(x+6)(x-6)(x+4)^2(x-9)^2}\right] < 0$

or

$x\cdot\left[\frac{(3x^2-6x-72)^2 - (2x^2-6x-108)^2}{(x+6)(x-6)(x+4)^2(x-9)^2}\right] < 0$

sweet!

$\frac{(5x^2-12x-180)(x^2+36)}{(x+6)(x-6)(x+4)^2(x-9)^2} < 0$

now,

$5x^2-12x-180$ has no integer roots, so we shall apply the quadractic formula to find the roots of x. Don't lose hopes though as we can now freely eliminate x^2 + 36 , (x+4)^2 . (x-9)^2 (they are never negative :D)

this simplifies the equation to

$\frac{(5x^2-12x-180)}{(x+6)(x-6)} < 0$

too many spoilers right? i am providing the solution now :D
domain:
$$x \in (-\infty , -4) \cup (-4 , 9) \cup (9 , \infty)$$
range:
$$x \in (-\infty , -6) \cup \left(\frac{12 - \sqrt{3744}}{10} , 0\right)\cup \left(6 , \frac{12 + \sqrt{3744}}{10}\right)$$
intersecting the domain and the range, the finalllll answerrrrr:
$$x \in (-\infty , -6) \cup \left(\frac{12 - \sqrt{3744}}{10} , -4\right) \cup (-4 , 0) \cup \left(6 , \frac{12 + \sqrt{3744}}{10}\right)$$

eternal satisfaction reached
Comment: It is nice. (+1). Actually, now you can accept your answer.
Comment: @river its fine.....your solution seems more intuitive to find

Inequality based on square


Significance test for a pattern in union of sets given that the pattern is significant in the individual sets

Question: We have a pattern like $P = \{f_{A},f_{B}\}$ which is statistically significant in multiple sets $S = \{S_{1}, S_{2}, S_{3}, ...\}$.
We can think of the features $f_{i}$ to be retail establishments & the sets $S_{i}$ to be geographic regions like counties.
The features $f_{A}, f_{B}$ are related by some association measure like geographic distance. Now the statistical significance of the pattern is computed against a null hypothesis which models the intensity of the features in the sets ($S_{i}$) but are randomly populated in the regions ($S_{i}$).
From experiments I have ensured that the pattern is statistically significant in some of the sets $S_{j}$ which is a subset of $S_{i}$.
Now if I have to check for the significance of the pattern in the union of the sets $S_{j}$, i.e. the region obtained by combining the individual regions within which the pattern is statistically significant, I am again calculating the p-value of the pattern in the new region obtained by the union of $S_{j}$.
Is there any property of p-value/significance tests via which I can check if the pattern is statistically significant in the union of the $S_{j}$ sets given that I know that the pattern is statistically significant in the individual regions $S_{j}$?
Thanks for your suggestions!
Answer: It is not clear from your question whether you appreciate that by selecting $S_j$ in that way you have to also allow for the remainder of $S_i$ but just in case, yes you do.
I think you may find one of the methods for dealing with thresholding helpful. Specifically Zhang and colleagues in a paper at arXiv:1801.04309 entitled "TFisher tests: optimal and adaptive thresholding for combining $p$-values" refer to a number of methods and present them in the framework of thresholding $p$-values. In your case presumably the threshold would be 0.05 or whatever significance level you chose. Their paper is far too long and complex to summarise here.
Zhang and colleagues provided an R package for this https://cran.r-project.org/package=TFisher. In my CRAN package metap I provide a wrapper for a subset of what their package provides


Problema no Visual Studio 2013 XAML

Question: Os Objetos não aparecem no Visual do XAML.

Eles só aparecem se for um projeto usando Silverlight.

Mas no Emulador ao Compilar exibir normal, é ruim só pra editar Visual do Aplicativo.
Answer: A resposta para o problema é o visual studio 2015.
No visual studio 2015 o erro não ocorre mais.

Problema no Visual Studio 2013 XAML


Is there a name for this kind of a transition in songs?

Question: In ALL ABOUT THAT BASE parody (Star Wars Parody - Meghan Trainor's All About That Bass), there's a certain transition / change near the linked time after "places" (the video has lyrics shown). I'm not sure how to describe it in more detail, but it's audible in the singing first and foremost though the instrumental part changes as well. It feels like a change in tempo maybe.
Time stamps with corresponding lyrics:
00:21 "Yeah, it's pretty clear..."
00:27 "Boom, Boom"
00:28 "That blow all places"
00:30 "Like Alderaan chunks"
Answer: At the point you mention the drums drop out and the vocals pick up the next phrase with a syncopated 'push'.  The underlying tempo doesn't change though.


Getting discord access token[Discord.js]

Question: Im still trying to authorize my discord bot with my website with this guide but i dont really understand how to get the access token.
My code

const http = require('http');
const fs = require('fs');
const port = 53134;

http.createServer((req, res) => {
 let responseCode = 404;
 let content = '404 Error';

 if (req.url === '/') {
  responseCode = 200;
  content = fs.readFileSync('../HTML/index.html');
 }

 res.writeHead(responseCode, {
  'content-type': 'text/html;charset=utf-8',
 });

 res.write(content);
 res.end();
})
 .listen(port);

everytime I run this i get the'404 error' and I feel like its because of the missing access token
Comment: **UPDATE** i fiqured it out like a week ago
Comment: what url are you trying to reach?
Answer: Error 404 = Not Found
The requested URL was not found on this server.
Error 403 = Forbidden
You don't have permission to access this resource.
So if you are missing access token the error would be 403, not 404.


Show that set is path connected?

Question: How do I show that the set $A = \{(x,y) \in R^2: x \geq 0, y \geq 0\} \cup \{(x,y) \in R^2: x \leq 0, y \leq 0\}$ is path connected. I know that I need to construct a continuous function $f:[0,1] \rightarrow A$ such that $f(0) = x, f(1) = y$ for any pair of points $x, y \in A$ but I don't know how to construct this function.
Answer: You take the segment from $x$ to $(0,0)$, and you paste this with the segment from $(0,0)$ to $y$. It is continuous, using the pasting lemma and being the concatenation of two continuous paths. Writing the exact expression is not diffcult, it is simple vector calculus.

Show that set is path connected?


While loop ends even when the method is not called [Java]

Question: One of the requirements of my project is that the program loops until the user presses the "X" key. I have the method for this, but the program terminates even when the method is not called. Here is my code:
while (terminate == false)
{
    // Ask user for input

    switch (command)
    {
        case "I":
        {
            // Do stuff
        }

        case "X":
        {
            terminateProgram();
        }
    }
}

This is my terminate method:
private static boolean terminateProgram()
{
    terminate = true;
    return terminate;
}

Even if I enter the "I" key, the loop ends after the case for "I" is completed. "I" works normally if terminateProgram(); is commented. How do I get the loop to stop only when I enter "X"?
Comment: For starters...you're not doing anything with the variable after you return from your method call...
Answer: You need a break within each case statement.
Read up on fall-through, which is what your current code is doing.
while (!terminate)
{
    // Ask user for input

    switch (command)
    {
        case "I":
        {
            // Do stuff
            break;
        }

        case "X":
        {
            terminateProgram()
            break;
        }
        default:
            // Do something default if no condition is met.
    }
}

Then here:
private static void terminateProgram()
{
    terminate = true; // if this method simply is to terminate a program
                      // I'm not quite sure why you need a `terminate` variable
                      // unless you're using it in another part of the program.
                      // A simple system.exit(0) would suffice.
    System.exit(0);
}

Comment: And dont make terminate == false, use !terminate
Comment: When you press `X`, `terminateProgram()` sets `terminate` to true. Do you have `terminate` as a global variable? Better question - where do you declare `terminate`? (Consider learning OOP concepts so you don't need to do everything statically ;))
Comment: There's actually more to your code that can be improved. As far as I can tell, your `terminateProgram()` is simply modifying `terminate`, so you don't need a `return` value. Change `bool` to `void`. Unless you plan to do more with `terminateProgram()`, it's unnecessary. A simple `terminate = true` would suffice in place of the method call.
Comment: Feel free to accept the answer if it helped you =).


What are the implications of a nonparametric machine learning algorithm?

Question: I've been looking into the advantages of using a Random Forest classifier and stumbled upon this

random forests are non-parametric

Looking at the definition of what non-parametric statistics mean, I found this on Wikipedia:

The first meaning of nonparametric covers techniques that do not rely on data belonging to any particular parametric family of
  probability distributions.
The second meaning of non-parametric covers techniques that do not assume that the structure of a model is fixed

I'm trying to understand what that means in the context of supervised learning, but I'm left with several questions:
For the first point, does that mean there is no assumption about my features coming from a certain set of distributions or my labels or both?
Does it also imply that I don't assume any relationship between features and labels (e.g. linear, polynomial)? What else is implied?
Also, I do not quite understand the second meaning of non-parametric and would be happy about an example or more intuitive explanation.
Answer:
For the first point, does that mean there is no assumption about my features coming from a certain set of distributions or my labels or both? Does it also imply that I don't assume any relationship between features and labels (e.g. linear, polynomial)? What else is implied?

I think both features and labels are not coming from a certain set of distributions, and I think the relationship can also not be fixed which reflects the second meaning.


Como somar dias a uma data com Moment.js?

Question: Estou tentando calcular o prazo do meu site em dias, ou seja, eu coloco "14 dias" e ele transforma em 00/00/0000.
Estou fazendo dessa forma, mas ela esta pegando a data completa e transformando em dias, quero fazer ao contrário, por exemplo:
Data atual: 08/07/2020 + Entrada (valor do input): 14 = saida esperada 22/07/2020.
onCalcularData(date: any): number {
    return Math.abs(
      moment()
        .startOf('day')
        .diff(moment(date).startOf('day'), 'days'),
    );
  }

Como chegar a isso?
Comment: Sua pergunta está confusa. Dê um exemplo de entrada, saída esperada e saída atual.
Comment: Oi Rafael - seguindo sua proposta, eu preciso pegar a data atual e e preencher em um input um valor decimal, por exemplo: Data atual: 08/07/2020 + Entrada (valor do input): 14  = saida esperada 22/07/2020. Hoje eu faço o calculo pegando duas datas e as transformando em dias
Answer: Para somar determinada quantidade de dias a uma data, basta usar add:
onCalcularData(date: any, dias: number): moment.Moment {
    return moment(date).add(dias, 'days');
}

O retorno será um Moment. Mas se quiser retornar um Date, basta usar toDate():
onCalcularData(date: any, dias: number): Date {
    return moment(date).add(dias, 'days').toDate();
}

Assim, se rodar com a data atual (08/07/2020) e somar 14 dias (onCalcularData(new Date(), 14)), o resultado será 22/07/2020. Lembrando que o horário será mantido (por exemplo, agora são 08:12 da manhã, então o resultado final será 22/07 no mesmo horário).

Aproveitando, acho que vale explicar dois conceitos importantes: datas e durações.
Uma data é um ponto específico no calendário. Por exemplo, 08/07/2020 representa o dia 8 do mês 7 do ano 2020 do calendário gregoriano.
Uma duração é uma quantidade de tempo. Por exemplo, "14 dias" - representa apenas um período, uma quantidade de tempo qualquer, mas sem qualquer relação com o calendário (a duração existe por si só, se eu disser somente "14 dias", não dá para saber quando começou ou terminou).
O que pode confundir é o fato de ambos usarem as mesmas palavras ("dia", "mês", etc), mas são coisas diferentes.
Só que esses dois conceitos estão relacionados. A diferença entre duas datas é uma duração (entre os dias 8 e 22, a diferença - ou a duração entre essas datas - é de 14 dias).
E se eu somar uma data com uma duração, o resultado é outra data (dia 8 + duração de 14 dias = dia 22).
O código da pergunta usa diff, que calcula a diferença entre duas datas e retorna uma duração. Mas você queria somar uma duração e uma data, e é para isso que add serve.

Complementando, se a ideia é somar sempre a partir da data atual, aí ficaria assim:
onCalcularData(dias: number): moment.Moment {
    return moment().add(dias, 'days');
}

Comment: Como seria rodar com NewDate? sou leiga em programação
Comment: @fernanda Do jeito que fiz, vc passa a data como parâmetro: `onCalcularData(new Date(), 14)`. Agora, se quer sempre somar 14 dias na data atual, aí a função seria apenas `onCalcularData(dias: number) { return moment().add(dias, 'days') }`
Comment: eu tentei fazer dessa forma  onCalcularData(newDate(), dias: number), porque os dias ficarão a criterio do usuario, porem recebo um erro do componente angular, por isso a pergunta
Comment: @fernanda `new Date()` tem um espaço depois do "new". De qualquer forma, se quer sempre somar na data atual, não precisa passá-la como parâmetro para a função. Atualizei a resposta com essa opção


Problema com BottonNavigationView

Question:
Como vocês podem ver galera estou com um probleminha de layout nesse form no Android, este form é aberto dentro de um fragment normalmente onde eu vou realizar o envio desses dados.
1- Pra minha surpresa o EditText não se expande pra tela toda. Já tentei usar o LayoutParams setando matchparent mas nada aconteceu...
2- os Botões estão se escondendo atras do BottonNavigationView, já tentei colocar um scrollview ali mas ele não sai dali...
Este componente BottonNavigation tem que ficar fixo na tela por que eu não quero que ele se esconda com a função Behavior...como acontece aqui BottonNavigation
Alguém teria alguma dica pra tentar encaixar este form corretamente ou alguma ajuda do além ?
Este layout está aqui:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:id="@+id/layouparams"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <com.vicmikhailau.maskededittext.MaskedEditText
            android:id="@+id/reg_txt_nome"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Nome Ex.: Pedro Silva"
            android:inputType="text"
            />

        <com.vicmikhailau.maskededittext.MaskedEditText
            android:id="@+id/reg_txt_email"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Email Ex.: email@example.com"
            android:inputType="textEmailAddress"
            />

        <com.vicmikhailau.maskededittext.MaskedEditText
            android:id="@+id/reg_txt_datanasc"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Data Nasc Ex.: 01/01/1980"
            android:inputType="number"
            android:maxLength="10"

            app:mask="##/##/####" />

        <com.vicmikhailau.maskededittext.MaskedEditText
            android:id="@+id/reg_txt_contato"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Contato Ex.: (16)9999-00-99"
            android:inputType="number"
            android:maxLength="14"

            app:mask="(##)####-##-##" />

        <com.vicmikhailau.maskededittext.MaskedEditText
            android:id="@+id/reg_txt_rg"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Rg Ex.: 000000000111"
            android:inputType="text"
            />

        <com.vicmikhailau.maskededittext.MaskedEditText
            android:id="@+id/reg_txt_cpf"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="CPF Ex.: 000-000-000.00"
            android:inputType="number"
            android:maxLength="15"

            app:mask="###-###-####.##" />

        <com.vicmikhailau.maskededittext.MaskedEditText
            android:id="@+id/reg_txt_end"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Endereço Ex.: rua joao paulo 1000"
            android:inputType="text"
            />

        <com.vicmikhailau.maskededittext.MaskedEditText
            android:id="@+id/reg_txt_cep"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="CEP Ex.: 14600-000"
            android:inputType="number"
            android:maxLength="9"

            app:mask="#####-###" />

        <com.vicmikhailau.maskededittext.MaskedEditText
            android:id="@+id/reg_txt_bairro"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Bairro Ex.: centro"
            android:inputType="text"
            android:maxLength="9"
            />

        <com.vicmikhailau.maskededittext.MaskedEditText
            android:id="@+id/reg_txt_cidade"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Cidade Ex.: Parnaíba-PI"
            android:inputType="text"
            />

        <com.vicmikhailau.maskededittext.MaskedEditText
            android:id="@+id/reg_txt_duvidas"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Dúvidas sobre o curso"
            android:inputType="textMultiLine"
            />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <Button
                android:id="@+id/btn_cancel"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="Cancelar" />

            <Button
                android:id="@+id/btn_save"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="Enviar Inscrição" />

        </LinearLayout>

    </LinearLayout>

</ScrollView>

Answer: Não sei qual o seu root layout, mas se for um RelativeLayout você pode utilizar o atributo android:layout_above="@+id/idDoBottomNav".
O root layout é aquele que é o responsável por guardar a view do seu Fragment, a sua Toolbar e o BottomNavigationView.
Com constraintLayout você deve atentar-se aos atributos dele, não do RelativeLayout. O above aqui não funciona e deve ser utilizado o constraintBottom_toTopOf que tem a mesma função do above.
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="br.com.pauloceami.ateliermaisprojetos.MainActivity">

    <FrameLayout
        android:id="@+id/containnersFragments"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toTopOf="@+id/navigation"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />

    <android.support.design.widget.BottomNavigationView
        android:id="@+id/navigation"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="0dp"
        android:layout_marginStart="0dp"
        android:background="@color/colorPrimary"
        app:itemIconTint="@android:color/white"
        app:itemTextColor="@android:color/white"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:menu="@menu/navigation" />

</android.support.constraint.ConstraintLayout>

O problema aqui é que a View responsável por exibir o Fragment ocupa toda a tela e fica por baixo do BottomNavigationView.
Você utilizou um scroll, mas não resolveu pois o scroll "acredita" que já não há mais nada pra ser exibido. Isto pode ser corrigido utilizando a seguinte abordagem:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:id="@+id/layouparams"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <com.vicmikhailau.maskededittext.MaskedEditText
            android:id="@+id/reg_txt_nome"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Nome Ex.: Pedro Silva"
            android:inputType="text"
            />

        <com.vicmikhailau.maskededittext.MaskedEditText
            android:id="@+id/reg_txt_email"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Email Ex.: firstname.lastname@example.com"
            android:inputType="textEmailAddress"
            />

        <com.vicmikhailau.maskededittext.MaskedEditText
            android:id="@+id/reg_txt_datanasc"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Data Nasc Ex.: 01/01/1980"
            android:inputType="number"
            android:maxLength="10"

            app:mask="##/##/####" />

        <com.vicmikhailau.maskededittext.MaskedEditText
            android:id="@+id/reg_txt_contato"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Contato Ex.: (16)9999-00-99"
            android:inputType="number"
            android:maxLength="14"

            app:mask="(##)####-##-##" />

        <com.vicmikhailau.maskededittext.MaskedEditText
            android:id="@+id/reg_txt_rg"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Rg Ex.: 000000000111"
            android:inputType="text"
            />

        <com.vicmikhailau.maskededittext.MaskedEditText
            android:id="@+id/reg_txt_cpf"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="CPF Ex.: 000-000-000.00"
            android:inputType="number"
            android:maxLength="15"

            app:mask="###-###-####.##" />

        <com.vicmikhailau.maskededittext.MaskedEditText
            android:id="@+id/reg_txt_end"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Endereço Ex.: rua joao paulo 1000"
            android:inputType="text"
            />

        <com.vicmikhailau.maskededittext.MaskedEditText
            android:id="@+id/reg_txt_cep"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="CEP Ex.: 14600-000"
            android:inputType="number"
            android:maxLength="9"

            app:mask="#####-###" />

        <com.vicmikhailau.maskededittext.MaskedEditText
            android:id="@+id/reg_txt_bairro"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Bairro Ex.: centro"
            android:inputType="text"
            android:maxLength="9"
            />

        <com.vicmikhailau.maskededittext.MaskedEditText
            android:id="@+id/reg_txt_cidade"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Cidade Ex.: Parnaíba-PI"
            android:inputType="text"
            />

        <com.vicmikhailau.maskededittext.MaskedEditText
            android:id="@+id/reg_txt_duvidas"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Dúvidas sobre o curso"
            android:inputType="textMultiLine"
            />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <Button
                android:id="@+id/btn_cancel"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="Cancelar" />

            <Button
                android:id="@+id/btn_save"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="Enviar Inscrição" />

            <Space
                android:layout_width="0dp"
                android:layout_height="?attr/actionBarSize"/>
        </LinearLayout>
    </LinearLayout>
</ScrollView>

Apenas veja que no final do teu layout eu adicionei o elemento Space que tem essa função de dar um "espaço" entre views. O atributo height eu usei o da ActionBar porque provavelmente o BottomNav utiliza o mesmo valor ou algo próximo.
Com isto teu layout vai ser mostrado corretamente e não será "engolido" pelo BottomNav.

Observação: recomendo o uso da abordagem com o Space, pois parece-me mais limpa.
Observação 2: a abordagem com o Space permite que o usuário possa utilizar o Scroller normalmente e ver o botão. A primeira também, mas o botão não irá mais aparentar estar abaixo do BottomNav, mas sim estar sendo "cortado" por ele.
Comment: Valeu pela dica vou testar... o outro problema voce imagina o que pode ser ? digo aquele espaço na direita da tela
Comment: Não deu certo ... Testei no celular api 16 com android 4.1 nem apareceu nada na tela..as views sumiram...depois tirei e elas voltaram..... muito estranho este comportamento.
Comment: esse tal de above ai tb nao funcionou
Comment: O above não vai funcionar porque teu root layout é um constraint layout, não um relative layout. Quando for fazer uma pergunta, deixe-a completa.
Comment: @PauloCeami editei o código com o teu layout, dá uma olhada aí ;)
Answer:
conforme estou mostrando o primeiro problema foi resolvido com o space mas nao funcionava com o attr talvez seja questao de versao etc etc... mas foi resolvido quando coloquei um valor de 50dp no height...
O segundo problema ainda esta quebrando minha cabeça... ja criei outro layout pelo android studio pra certetificar de que talvez eu pudesse estar fazendo algo errado, mas não... ele continua aparecendo essa margem no android 4 e no 6 tb... será que pode ser algum problema com o fragment ? vejam meus layouts ...
layout com o FrameLayout
form com EditText
Comment: Essa problema com o espaço que apareceu eu resolvi lá na minha resposta, dá uma olhada no primeiro código, que é dó layout principal.

Problema com BottonNavigationView


Best alternative to dynamically highlight my Navbar link using jQuery?

Question: I have an ASP.NET website, on the masterpage I have a basic navigation menu:

Home

Services

How It Works

Contact Us

My goal is to add a JavaScript function on the masterpage that will dynamically add the "active" class to the  tag that represents the page the user is on. For example, if the user is on www.mywebsite.com/default.aspx, than the attribute [class='active'] should be added to the first link in the navbar. The active class basically just highlights the link so the user knows which page they are currently on.
Here is my JavaScript code:

Here is what happens, when the user visits any page on the site, the selectMenuItem() function executes. The function makes a call to getPageName() which returns the name of the page file that the user is viewing (ex: "default.aspx"). The function uses this name string to find which  tag links to the page the user is currently on, when found the class is correctly added.
This code works great, however the process is case sensitive. Basically I'm at the mercy of the user. If they manually type in "mywebsite.com/DefUlT.aspx" than my code will fail because the casing in the substring "default.aspx" does not match the one in the  tag. I could solve this problem by telling the JavaScript function to force the name string to be lower case, however this would mean that whenever I add new menu item I need to be sure I write the href attribute all in lower case, which isn't a big deal but it's not elegant enough for me. It wouldn't be a problem if I was the only one working on this site, but I will hand the work of to a number of other professionals and I feel stupid telling everyone, "be sure the href values are all lowercase or the code will break!"
Can someone interested in a challenge maybe tell me how to work around this? I'm extremely new to jQuery (started last night) so I'm sure there's an elegant solution that involes changing this line of code:
$('#menu a[href="' + name + '"]').addClass("active");
My problem is that I need the "href" attribute to be turned to lower case before the comparison is made to the name variable, I would then just perform "name.toLowerCase()" so that I know the case differences between the href attribute and name variable are irrelevant. Is there an equivalent jQuery selector which allows me to specify an expression perhaps?
Thanks,
-Andrew C.
Answer: try this with .filter()
function selectMenuItem() {
    var name = getPageName();
    if (name)
        $('#menu a').filter(function(){
            return this.href.toUpperCase() == name.toUpperCase();
        }).addClass("active");
}

Comment: Thanks for this method, I can see the logic behind it. I did have a few problems though, when I first ran it every navbar link ended up highlighted, I'm assuming this was because the brackets were left off on the href.toUpperCase == name.toUpperCase, both statements evaluated to null which made the == statement evaluate to true every time. However that was an easy fix :P

The bigger problem I had was for some reason the segment "this.href" returns the absolute path to the filename in the href attribute. It's easy to work around that but I thought that was odd.
Comment: no, I have forgotten `()` in `toUpperCase` haha my bad... :) well, I'm glad you solved it..
Answer: I don't know of a way to do it with a selector, but looping through all your menu links as in the following, you could apply the toLowerCase() method to both the href and name, so you'd know the match would work, no matter what the user entered in the URL:
function selectMenuItem() {
    var name = getPageName();
    if (name){
        $('#menu a').each(function(){
            if($(this).attr('href').toLowerCase() == name.toLowerCase()){
                $(this).addClass('active');
                return;
            }
        });
     }
 }

Comment: Thanks, this worked like a charm! I should have thought about the logic of looping through each element at a time. Can't believe I missed that :D
Comment: You want the attribute selector.
$("menu a[href='"+window.location+"']").addClass('active');
Comment: Key, that code has a potential to fail because it depends on what the programmer typed in the href attribute being compared. The point is there has got to be a way to minimize this risk by forceing the data in the href attribute and the window.location value to the same case (upper or lower) so that the value will match correctly 100% of the time.


Simple proof that stationary birth-death chains are reversible

Question: A Markov chain with state space $\mathbb{Z}$ is a birth-death chain if the transition probabilities satisfy $p(x,y) = 0$ for $|x-y| > 1$.  That is, the only possible transitions are to move one state to the left or right or to stay still.
Suppose such a chain has a stationary distribution $\pi$.  It is then a "well-known" fact that $\pi$ satisfies the detailed balance equation
$$\pi(x) p(x, y) = \pi(y) p(y,x), \quad x,y \in \mathbb{Z}.$$
That is, the chain is reversible.
I am looking for a simple proof of this fact (for a class I am teaching).  The only proofs I've found go via Kolmogorov's criterion for reversibility, which seems like a lot of work.  If possible, the proof should give some insight as to why the particular structure of a birth-death chain causes reversibility to hold.
Thanks!
Comment: The parallel with flows, intensities, voltages and the like, is explained and pushed much further in a small book one can only recommend: P.G. Doyle and J.L. Snell, *Random walks and electric networks*, [now freely available](http://arxiv.org/abs/math/0001057).
Answer: Draw a permeable barrier between the states $x$ and $y$, dividing the number line into two parts. Since your Markov chain is a birth-death chain, the only passage through this barrier is the transition connecting $x$ and $y$. The LHS of your equality is the probability of a particle, at any given time, to be moving from $x$ to $y$; that is, the probability of it going through the barrier in one direction. The RHS of your equality is the probability of a particle, at any given time, to be moving from $y$ to $x$; that is, the probability of it going through the barrier in the opposite direction.
Since $\pi$ is stationary, the total flow through the barrier must be $0$ - that is, the LHS and the RHS must be the same, as desired!
Comment: Thanks, this is very helpful.  I'm adding another answer to expand on it.
Answer: Lopsy's answer has the right idea, I think.  Here's how I worked out the details.
If $x$ and $y$ are not adjacent then the detailed balance equation is trivially true.  If they are, say $y = x+1$, let $L = \{z : z \le x\}$ be the set of states on the left side.  The key, as Lopsy says, is that the only route in or out of $L$ is via the transition between $x$ and $y$.
Consider $P_\pi(X_1 \in L)$.  On the one hand, since $\pi$ is stationary, $P_\pi(X_1 \in L) = P_\pi(X_0 \in L)$.  On the other hand, we can break up the event $\{X_1 \in L\}$ and write
$$\begin{align} P_\pi(X_1 \in L) &= P_\pi(X_1 \in L, X_0 \in L) + P_\pi(X_1 \in L, X_0 \notin L) \\\\ &= P_\pi(X_0 \in L) - P_\pi(X_1 \notin L, X_0 \in L) + P_\pi(X_1 \in L, X_0 \notin L).\end{align}$$
Thus $P_\pi(X_1 \notin L, X_0 \in L) = P_\pi(X_1 \in L, X_0 \notin L)$ which is Lopsy's "total flow" statement.  However, $P_\pi(X_1 \notin L, X_0 \in L) = P_\pi(X_1 = y, X_0 = x) = \pi(x) p(x,y)$, and likewise the other side is $\pi(y) p(y,x)$.
This also makes clear that the essential feature of a birth-death chain is that it is "simply connected".
Answer: Using user abkds and Did 's idea here and modifying, organizing a bit . This simple approach starts directly from definition of stationary distribution and Birth Death chain , but may not be as intuitive as Lopsy's answer .
OP assumed the existence of stationary distribution $\pi$ , by definition
$$
\pi(x) = \sum_{k\in \mathbb{Z}} \pi(k)p(k,x)
$$
by $|x-y|>1 \implies p(x,y)=0 $ ,
$$
= \pi(x-1) p(x-1,x) + \pi(x+1) p(x+1,x) + \pi(x)(1-p(x,x-1)-p(x,x+1))
$$
rearranging yields
$$
\color{red}{ \pi(x)p(x,x-1) } + \pi(x)p(x,x+1)= \color{red}{ \pi(x-1) p(x-1,x) } + \pi(x+1) p(x+1,x) , \; \forall x\in  \mathbb{Z} \tag{*}
$$
$*$ is obtained by pairwise addition of the detailed balance equations , but they are not equivalent , as proven here . We need an additional condition : $\exists n \in \mathbb{Z},\; \pi(n-1)p(n-1,n)= \pi(n)p(n,n-1) $
along with $*$ to imply the detailed balance equations .
Let state space becomes $\mathbb{Z}_{N} = \{-N,..,0,..,N\} \subset \mathbb{Z} $ , we have $ \pi(N-1)p(N-1,N)= \pi(N)p(N,N-1)$ and a version of $*$ with $\mathbb{Z}$ replaced by $\mathbb{Z}_{N}\setminus\{-N,N\} $ . Now let
inetger $N\to \infty$ , we have $\mathbb{Z}_{N} \to \mathbb{Z} $ , so $*$ implies the detailed balance equations now . (I'm unsure if this's rigorous enough) $\qquad \square$
So we only used 3 conditions :

stationary distribution exists
$|x-y|>1 \implies p(x,y)=0 $ (or as OP says : "simply connected")
there exists a pair of state such that the detailed balance equation holds (I think even trivially holds : $0=0$ would work)


How can I solve this recurrence problem?

Question: Given a function
$$
f(n) = f(5n/13) + f(12n/13) + n \;\;\;\;∀n \geq 0
$$
I would like to find a function $g(n)$ such that $f ∈ Ө(g(n))$.
Comment: Try a quadratic function.
Comment: Try a linear function.
Comment: In the tradition of "try": you can try the generating function approach. But the problem is incomplete: you need the initial conditions to solve it.
Comment: Use [Akra-Bazzi](https://en.wikipedia.org/wiki/Akra%E2%80%93Bazzi_method)
Answer: The Akra-Bazzi theorem gives us a way of tackling the complexity of $T$ given a recurrence of the form $$T(n)=g(n) + \sum_{i=1}^k a_i T(b_i n + h_i(n))$$
Here, we have $f(n)=f(5n/13)+f(12n/13)+n$. So our first focus is on solving $p$ such that $a_1 b_1^p+a_2b_2^p=1$ where $a_1=a_2=1$ and $b_1=5/13,b_2=12/13$; equivalenty, we have $$5^p+12^p=13^p$$
Recall that $(5,12,13)$ is a Pythagorean triple so clearly $p=2$.The theorem then tells us $$f(n)\in\Theta\left(n^2\left(1+\int_1^n \frac1{u^2} du\right)\right)$$
Since $\int_1^n\frac1{u^2}du=1-\frac1n$ this gives us $f(n)\in\Theta(n^2)$.
Comment: I just know that I know nothing (Socrates)


conditioning on continuous value

Question: Is there a formula like this $$P(A)=\int P(A|x)p(x)dx $$ where $x$ is a continuous random variable? If yes, what is a good book for learning about this? Thanks!
Comment: This is called the law of total probability
Answer: Yes, there is such a result (or, rather, this is the defining equation of the conditional probability $\mathbb{P}(A|X))$. However, this really naturally belongs to the theory of general conditional expectations, which is firmly measure theoretic, so that is probably a bit far away if you aren't familiar with any measure theory.
René Schilling's Measures, Integrals & Martingales contains both an introduction to measure theory (which is very good) and an introduction to conditional expectations and (as the title hints) some martingale theory (which is one of the best starting points to get acquainted with how conditional expectations work). He doesn't devote a lot of time to regular probability distributions, though.

conditioning on continuous value


hasOne and belongsTo relation tables in laravel

Question: my tables :
users :
id fname email

brands:
id title user_id_made

each brand has a user_id_made that is a foreign key of users table.
in Brand model :
public function user()
{
    return $this->hasOne('App\Models\User','id');
}

in User model:
public function brand()
{
    return $this->belongsTo('App\Models\Brand','user_id_made');
}

I have a list of brands like this :
title of brand       -   email of user that made it

in my controller I write this code :
$data['brands']  = Brand::with('user')->simplePaginate(2);

in foreach of view I got  trying to get non-object property error :
            @foreach($brands as $brand)

                 {{$brand->title_fa}}
                 {{$brand->title_en}}
                 {{$brand->user->fname}}	 // error line

Answer: This will give the brand title and email of the user with this brand.
$brands=Brand::with('user')->get();
foreach($brands as $brand)
{
    print_r($brand->title);
    print_r($brand->user->email);
}

The relation in Brand Model:
public function user()
{
    return $this->hasOne('App\Models\User','user_id_made');
}

Answer: You have used the wrong relationship. hasOne is used on one-to-one relationships but it should be a one-to-many relationship between your Brand and User. (Each brand is made by one user and each user can make more than one brand)
If you state that a Brand hasOne User, Laravel will assume the users table having a foreign key referencing the brands table.
Instead, modify your relationship method to use belongsTo.
public function user() {
    return $this->belongsTo('App\Models\User', 'user_id_made');
}

Answer: Since Brand model has the foreign key, this is the side that the
belongsTo() method should be.
If you used the convention when naming your foreign key user_id things would
be more straight forward.
But if for whatever reason you need to have user_id_made name for the column,
this is what you should pass as a second argument in both sides of the relationship.
The User should have the hasOne('App\Brand', 'user_id_made').
And the Brand should have belongsTo('App\User', 'user_id_made').
https://laravel.com/docs/5.3/eloquent-relationships


Case where Logistic Regression performs better with fewer predictors

Question: In section 4.6.2 (page 156) of An Introduction to Statistical Learning, the authors use logistic regression to predict daily stock price (up or down). First they use all 6 predictors and get a test accuracy of 0.52 (page 160); then they remove the predictors with high p-values, and fit a new model with the best 2 predictors and get a test accuracy of 0.58 (page 160).
They state:

Perhaps by removing the variables that appear not to be helpful in
  predicting Direction, we can obtain a more effective model. After all,
  using predictors that have no relationship with the response tends to
  cause a deterioration in the test error rate (since such predictors
  cause an increase in variance without a corresponding decrease in
  bias), and so removing such predictors may in turn yield an
  improvement.

But I thought logistic regression takes care of unhelpful predictors automatically through shrinkage via the lasso or ridge penalty? I.e. I thought one could have p >> n where a large number of p are just noise; and the model would shrink their coefficients to 0 (lasso) or near zero (ridge). So why does their test accuracy improve when they "manually" remove 4 predictors with high p-values?
Comment: What makes you think there is any shrinkage going on in the GLM fitted on page 156?  "Generalized Linear Model" does not imply regularization.
Comment: Thanks. Is there any reason to not use regularization if only prediction accuracy is of interest?
Comment: @jbowman. You are correct. They are not using regularization. When I use shrinkage and select the tuning parameter alpha via cross validation, I get 0.56 accuracy when using all six predictors.
Comment: The answer to this post https://stats.stackexchange.com/questions/281601/if-your-regression-model-is-not-over-fitting-would-using-regularization-give-be might help with your question about not using regularization.
Answer: At least two points:

A logistic regression (or more generally a generalized linear model) do not imply use of regularization, it is often fitted with mle (maximum likelihood estimation) without any regularization.  And, regularization do not necessarily improve the fit.
You try to evaluate the fitted model by accuracy, which is not a proper scoring rule.  But it is fitted by optimizing another criterion (likelihood.)  By including more variables, the criterion it is fitted on will improve (on the training set, that is), but on some other criterion, like accuracy, it does not need to improve. So there is no contradiction!

Also see the good comments on the question.