Why does minimizing the MAE lead to forecasting the median and not the mean?

Question: From the Forecasting: Principles and Practice textbook by Rob J Hyndman  and George Athanasopoulos, specifically the section on accuracy measurement:

A forecast method that minimizes the MAE will lead to forecasts of the
  median, while minimizing the RMSE will lead to forecasts of the mean

Can someone give an intuitive explanation of why minimizing the MAE leads to the forecasting the median and not the mean? And what does this means in practice?
I have asked a customer: "what is more important for you to make mean forecasts more accurate or to avoid very inaccurate forecasts?". He said that to made mean forecasts more accurate have higher priority. So, in this case, should I use MAE or RMSE? Before I read this citation I believed that MAE will be better for such condition. And now I doubt.
Answer: It's useful to take a step back and forget about the forecasting aspect for a minute. Let's consider just any distribution $F$ and assume we wish to summarize it using a single number.
You learn very early in your statistics classes that using the expectation of $F$ as a single number summary will minimize the expected squared error.
The question now is: why does using the median of $F$ minimize the expected absolute error?
For this, I often recommend "Visualizing the Median as the Minimum-Deviation Location" by Hanley et al. (2001, The American Statistician). They did set up a little applet along with their paper, which unfortunately probably doesn't work with modern browsers any more, but we can follow the logic in the paper.
Suppose you stand in front of a bank of elevators. They may be arranged equally spaced, or some distances between elevator doors may be larger than others (e.g., some elevators may be out of order). In front of which elevator should you stand to have the minimal expected walk when one of the elevators does arrive? Note that this expected walk plays the role of the expected absolute error!
Suppose you have three elevators A, B and C.

If you wait in front of A, you may need to walk from A to B (if B arrives), or from A to C (if C arrives) - passing B!
If you wait in front of B, you need to walk from B to A (if A arrives) or from B to C (if C arrives).
If you wait in front of C, you need to walk from C to A (if A arrives) - passing B - or from C to B (if B arrives).

Note that from the first and last waiting position, there is a distance - AB in the first, BC in the last position - that you need to walk in multiple cases of elevators arriving. Therefore, your best bet is to stand right in front of the middle elevator - regardless of how the three elevators are arranged.
Here is Figure 1 from Hanley et al.:

This generalizes easily to more than three elevators. Or to elevators with different chances of arriving first. Or indeed to countably infinitely many elevators. So we can apply this logic to all discrete distributions and then pass to the limit to arrive at continuous distributions.
To double back to forecasting, you need to consider that underlying your point forecast for a particular future time bucket, there is a (usually implicit) density forecast or predictive distribution, which we summarize using a single number point forecast. The above argument shows why the median of your predictive density $\hat{F}$ is the point forecast that minimizes the expected absolute error or MAE. (To be more precise, any median may do, since it may not be uniquely defined - in the elevator example, this corresponds to having an even number of elevators.)
And of course the median may be quite different than the expectation if $\hat{F}$ is asymmetric. One important example is with low-volume count-data, especially intermittent-time-series. Indeed, if you have a 50% or higher chance of zero sales, e.g., if sales are Poisson distributed with parameter $\lambda\leq \ln 2$, then you will minimize your expected absolute error by forecasting a flat zero - which is rather unintuitive, even for highly intermittent time series. I wrote a little paper on this (Kolassa, 2016, International Journal of Forecasting).
Thus, if you suspect that your predictive distribution is (or should be) asymmetric, as in the two cases above, then if you wish to get unbiased expectation forecasts, use the rmse. If the distribution can be assumed symmetric (typically for high-volume series), then the median and the mean coincide, and using the mae will also guide you to unbiased forecasts - and the MAE is easier to understand.
Similarly, minimizing the mape can lead to biased forecasts, even for symmetric distributions. This earlier answer of mine contains a simulated example with an asymmetrically distributed strictly positive (lognormally distributed) series can meaningfully be point forecasted using three different point forecasts, depending on whether we want to minimize the MSE, the MAE or the MAPE.
Answer: Stephan's answer gives you an intuitive explanation of why minimizing the absolute average error gives you the median. To answer which of the MSE, MAE or MAPE you should minimize:

The MAE is robust, meaning it is less sensitive to outliers. Imagine a series of $n$ points with an error a million times greater that what it should be. The MSE will pull the forecast a million / $n$ times, while the MAE will only be pulled by 1 unit (fig. 1).

Unfortunately, minimizing the MAE can lead to multiple solutions (fig. 2).

So my recommendation is:

Fit a model using the MSE.
Start an MAE-based regression with the fitted parameters.
Compare both forecasts. If they are very different, your data may have anomalies.

Fig. 1:

Fig. 2:
Comment: [This question](https://stats.stackexchange.com/q/573198/1352) asks what you mean by the MAE not being unique. Perhaps you would like to clarify there?
Comment: Q1. What does "pull the forecast a million / $n$ times" mean? If the error equals 1 million ($e=10^6$), the MSE will be 1 trillion ($e^2=10^12$), whereas the MAE will remain 1 million ($e$).
Q2. The MAE [is a convex function](https://math.stackexchange.com/questions/2579595/proof-convexity-of-mean-absolute-error) so its minimization should lead to only one solution. How does it justify your recommendation (using an MSE-based regressor to initialize an MAE-based one)
Answer: All the aforementioned explanations are great, just suggesting a shorter one.
Assuming you would use some value which isn't the median to minimize MAE then there are A examples above the value and B examples below it such that w.l.o.g $A>B$. Then by increasing the value by $\epsilon>0$ the error reduces by $\epsilon$ for all $A$ examples and increases by $\epsilon$ for all $B$ examples, so overall the error was reduced by $(A-B)\epsilon>0$.
This is true for any value where $A \neq B$, I.e. any value but the median.
Comment: This works unless there are also $C>0$ examples at the value being considered.  In that case you would need $A > B+C$ to reduce the error by increasing the value, or $A+C < B$ to reduce the error by decreasing the value; otherwise you would be at the median (or at least at *a* median).


The way of compute $\int_2^\infty\frac{dx}{x\log^s(x)}=\frac1{1-s}\log^{1-s}(x)\Big|_2^\infty$

Question: I am not sure, how proof this integrate $\int_2^\infty\frac{dx}{x\log^s(x)}=\int_2^\infty\frac{\log'(x)}{\log^{s}(x)}=\frac1{1-s}\log^{1-s}(x)\Big|_2^\infty$ without strong intuition and showing the primary function.
Do you have any idea?
Comment: Let $$u=log(x)$$
Comment: What base is the logarithm? e ?
Comment: Are you sure the answer isn't

$=\frac{1}{1-s} \ln^{1-s}(x) \vert_{\ln 2}^{\infty}$
Answer: To prove it,
note that
$(\log^a(x))'
=a\log^{a-1}(x)(\log'(x))
=\dfrac{a\log^{a-1}(x)}{x}
$.
Therefore
$(\log^{1-s}(x))'
=\dfrac{(1-s)\log^{(1-s)-1}(x)}{x}
=\dfrac{(1-s)\log^{-s}(x)}{x}
$
so
$(\dfrac{\log^{1-s}(x)}{1-s})'
=\dfrac{\log^{-s}(x)}{x}
=\dfrac1{x\log^{s}(x)}
$.


setOnClickListener(this) cause error?

Question: Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.user.foody">

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:theme="@style/AppTheme.NoActionBar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:name=".RestaurantDetail"></activity>
</application>
</manifest>

Main Activity
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener,
                                                           android.view.View.OnClickListener {
private boolean viewIsAtHome; // 每次 press back 都回到 about(初始頁面)
Button buttonEditAddYes,buttonEditUorD;
TextView restaurantID;

// ----------- 每當按下Button按下,則跑到OnClick()執行對應Function -----------

@override
public void onClick(View view) {
    if (view== findViewById(R.id.buttonEditAddYes)){ // 確定新增 (Edit_Add內)

        Intent intent = new Intent(MainActivity.this,RestaurantDetail.class);
        intent.putExtra("restaurantID",0);
        startActivity(intent);
    }

    else if (view== findViewById(R.id.buttonEditAddNo) ){ // 清除 (Edit_Add內)
    }

    else if (view== findViewById(R.id.buttonEditUorD)) { // 當按下 (Edit內)

        RestaurantRepo repo = new RestaurantRepo(this);

        ArrayList<HashMap<String, String>> restaurantList =  repo.getRestaurantList();
        if(restaurantList.size()!=0) {
            ListView lv = (ListView) findViewById(R.id.list);
            lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
                    restaurantID = (TextView) view.findViewById(R.id.restaurantID);
                    String idRestaurant = restaurantID.getText().toString();
                    Intent objIndent = new Intent(getApplicationContext(),RestaurantDetail.class);
                    objIndent.putExtra("restaurantID", Integer.parseInt(idRestaurant));
                    startActivity(objIndent);
                }
            });
            ListAdapter adapter = new SimpleAdapter( MainActivity.this,restaurantList, R.layout.edit_fragment_fix_view,
                    new String[] { "id","name","type","price","phone","addr"},
                    new int[] {R.id.restaurantID, R.id.restaurantNAME,R.id.restaurantTYPE,
                            R.id.restaurantPRICE,R.id.restaurantPHONE,R.id.restaurantADDR});
            lv.setAdapter(adapter);
        }else{
            Toast.makeText(this,"No restaurant!",Toast.LENGTH_SHORT).show();
        }
    }
}
// ------------------------------------------------------------------------

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

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setItemIconTintList(null); // 顯示Icon圖案,不會讓他黑黑的
    navigationView.setNavigationItemSelectedListener(this);
    displayView(R.id.menu_about); // 一開始看About

    // -------------------- 新增 / 修改 / 刪除  --------------------

    buttonEditAddYes = (Button)findViewById(R.id.buttonEditAddYes);
    buttonEditAddYes.setOnClickListener(this);// !!!!!!!!!!!!!!!!!!!!!! Here got error

    buttonEditUorD = (Button)findViewById(R.id.buttonEditUorD);
    buttonEditUorD.setOnClickListener(this); // !!!!!!!!!!!!!!!!!!!!!! because of ↑ , so this may cause error too

    // ------------------------------------------------------------
}

RestaurantDetail
public class RestaurantDetail extends Activity implements android.view.View.OnClickListener {

    Button buttonEditUpdate ,  buttonEditDelete;

    EditText editTextNAME;
    EditText editTextTYPE;
    EditText editTextPRICE;
    EditText editTextPHONE;
    EditText editTextADDR;
    //EditText editTextSCORE;

    private int _RestaurantID = 0;

    @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.edit_fragment_fix_uord);
            // buttonEditUorD按下時 跳到 edit_fragment_fix_uord去修改

            buttonEditUpdate = (Button) findViewById(R.id.buttonEditUpdate);
            buttonEditDelete = (Button) findViewById(R.id.buttonEditUpdate);

            editTextNAME = (EditText) findViewById(R.id.editTextUpdateName);
            editTextTYPE = (EditText) findViewById(R.id.editTextUpdateType);
            editTextPRICE = (EditText) findViewById(R.id.editTextUpdatePrice);
            editTextPHONE = (EditText) findViewById(R.id.editTextUpdatePhone);
            editTextADDR = (EditText) findViewById(R.id.editTextUpdateAddr);
            //editTextSCORE = (EditText) findViewById(R.id.ratingBarUpdate);

            buttonEditUpdate.setOnClickListener(this);
            buttonEditDelete.setOnClickListener(this);

            _RestaurantID =0;
            Intent intent = getIntent();
            _RestaurantID =intent.getIntExtra("restaurantID", 0);
            RestaurantRepo repo = new RestaurantRepo(this);
            Restaurant restaurant = new Restaurant();
            restaurant = repo.getRestaurantById(_RestaurantID);

            editTextNAME.setText(restaurant.name);
            editTextTYPE.setText(String.valueOf(restaurant.type));
            editTextPRICE.setText(String.valueOf(restaurant.price));
            editTextPHONE.setText(restaurant.phone);
            editTextADDR.setText(restaurant.addr);
            //editTextSCORE.setText(String.valueOf(restaurant.score));
        }

    @Override
        public void onClick(View view) {
            // TODO Auto-generated method stub
            if (view == findViewById(R.id.buttonEditUpdate)){
                RestaurantRepo repo = new RestaurantRepo(this);
                Restaurant restaurant = new Restaurant();

                restaurant.restautant_ID =_RestaurantID;
                restaurant.name = editTextNAME.getText().toString();
                restaurant.type =  Integer.parseInt(editTextTYPE.getText().toString()) ;
                restaurant.price = Integer.parseInt(editTextPRICE.getText().toString()) ;
                restaurant.phone = editTextPHONE.getText().toString();
                restaurant.addr = editTextADDR.getText().toString();
                //restaurant.score = Integer.parseInt(editTextSCORE.getText().toString());

                if (_RestaurantID==0){
                    _RestaurantID = repo.insert(restaurant);

                    Toast.makeText(this,"New Restaurant Insert",Toast.LENGTH_SHORT).show();
                    finish();
                }

                else{
                    repo.update(restaurant);
                    Toast.makeText(this,"Restaurant Record updated",Toast.LENGTH_SHORT).show();
                    finish();
                }
            }

            else if (view== findViewById(R.id.buttonEditDelete)){
                RestaurantRepo repo = new RestaurantRepo(this);
                repo.delete(_RestaurantID);
                Toast.makeText(this, "Restaurant Record Deleted", Toast.LENGTH_SHORT);
                finish();
            }
        }
}

I decided to make a button to insert information to my SQLite database.
When I click on the button (buttonEditAddYes), it passes parameters to
another activity (RestaurantDetail).
Error happens on this line:
buttonEditAddYes.setOnClickListener(this);

I think maybe I am missing to extend ListActivity on my MainActivity (?)
But I already extended AppCompatActivity ..
Process: com.example.user.foody, PID: 4577
  java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.user.foody/com.example.user.foody.RestaurantDetail}: java.lang.ClassCastException: android.widget.TableRow cannot be cast to android.widget.EditText
      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2693)
      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2758)
      at android.app.ActivityThread.access$900(ActivityThread.java:177)
      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1448)
      at android.os.Handler.dispatchMessage(Handler.java:102)
      at android.os.Looper.loop(Looper.java:145)
      at android.app.ActivityThread.main(ActivityThread.java:5942)
      at java.lang.reflect.Method.invoke(Native Method)
      at java.lang.reflect.Method.invoke(Method.java:372)
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)
   Caused by: java.lang.ClassCastException: android.widget.TableRow cannot be cast to android.widget.EditText
      at **com.example.user.foody.RestaurantDetail.onCreate(RestaurantDetail.java:39)
      at** android.app.Activity.performCreate(Activity.java:6288)
      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2758)
      at android.app.ActivityThread.access$900(ActivityThread.java:177)
      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1448)
      at android.os.Handler.dispatchMessage(Handler.java:102)
      at android.os.Looper.loop(Looper.java:145)
      at android.app.ActivityThread.main(ActivityThread.java:5942)
      at java.lang.reflect.Method.invoke(Native Method)
      at java.lang.reflect.Method.invoke(Method.java:372)

Comment: onClick method should have an override prefix
Comment: Thank you , but it sill has error when i add @override
Comment: You should add the logcat output to your question.
Comment: Its Override not override
Comment: @SoulRayder I'm so sorry. I mean "@Override" sorry
Comment: @se_bastiaan Here is my logcat !
Comment: OMG !!!!!!!! I slove my problem !!!!!!!!
I rebuid the project and it works !!!!!!!!!!!!!!!!
Answer: Log says:
Caused by: java.lang.ClassCastException: android.widget.TableRow cannot be cast to android.widget.EditText

Are you sure all these findViewById are referencing to a TextView? Maybe a typo in an android:id?
Also, I think you should use cases instead of ifs in your onClick method:
switch(view.getId) {
    case R.id.your_id:
    doSomething();
    break;
}

This gives more readability to the code ;)
Answer: @Override
    public void onClick(View view) {
        // TODO Auto-generated method stub
        if (view.getId() == R.id.buttonEditUpdate){
            RestaurantRepo repo = new RestaurantRepo(this);
            Restaurant restaurant = new Restaurant();

            restaurant.restautant_ID =_RestaurantID;
            restaurant.name = editTextNAME.getText().toString();
            restaurant.type =  Integer.parseInt(editTextTYPE.getText().toString()) ;
            restaurant.price = Integer.parseInt(editTextPRICE.getText().toString()) ;
            restaurant.phone = editTextPHONE.getText().toString();
            restaurant.addr = editTextADDR.getText().toString();
            //restaurant.score = Integer.parseInt(editTextSCORE.getText().toString());

            if (_RestaurantID==0){
                _RestaurantID = repo.insert(restaurant);

                Toast.makeText(this,"New Restaurant Insert",Toast.LENGTH_SHORT).show();
                finish();
            }

            else{
                repo.update(restaurant);
                Toast.makeText(this,"Restaurant Record updated",Toast.LENGTH_SHORT).show();
                finish();
            }
        }

        else if (view.getId()== R.id.buttonEditDelete){
            RestaurantRepo repo = new RestaurantRepo(this);
            repo.delete(_RestaurantID);
            Toast.makeText(this, "Restaurant Record Deleted", Toast.LENGTH_SHORT);
            finish();
        }
    }

Change the Onclick method to abouve
Answer: Basically, look at your stack trace

Caused by: java.lang.ClassCastException: android.widget.TableRow cannot be cast to android.widget.EditText

It means you're casting wrong types of Object.
Check your 39th line on RestaurantDetail. Your casting TableRow to EditText!
Regards

setOnClickListener(this) cause error?


How do I use ldapsearch with a cross-realm ticket?

Question: kinit firstname.lastname@example.com
klist -afe

Ticket cache: FILE:/tmp/krb5cc_1000
  Default principal: firstname.lastname@example.com
  Valid starting     Expires            Service principal
  08/04/11 13:14:53  08/05/11 01:14:53  firstname.lastname@example.com
      renew until 08/05/11 13:14:53, Flags: FRI
      Etype (skey, tkt): des3-cbc-sha1, des3-cbc-sha1
      Addresses: (none)

ldapwhoami -h dc1.windows.domain.tld

SASL/GSSAPI authentication started
  ldap_sasl_interactive_bind_s: Local error (-2)
      additional info: SASL(-1): generic failure: GSSAPI Error: Unspecified GSS failure.  Minor code may provide more information (Server email@example.com not found in Kerberos database)

kvno email@example.com
email@example.com: kvno = 65
klist -afe

Ticket cache: FILE:/tmp/krb5cc_1000
  Default principal: firstname.lastname@example.com
  Valid starting     Expires            Service principal
  08/04/11 13:14:53  08/05/11 01:14:53  email@example.com
      renew until 08/05/11 13:14:53, Flags: FRI
      Etype (skey, tkt): des3-cbc-sha1, des3-cbc-sha1
      Addresses: (none)
  08/04/11 13:24:35  08/05/11 01:14:53  email@example.com
      renew until 08/05/11 13:14:53, Flags: FRT
      Etype (skey, tkt): des-cbc-crc, des-cbc-crc
      Addresses: (none)
  08/04/11 13:24:35  08/05/11 01:14:53 firstname.lastname@example.com
      renew until 08/05/11 13:14:53, Flags: FR
      Etype (skey, tkt): arcfour-hmac, arcfour-hmac
      Addresses: (none)

ldapwhoami -h dc1.windows.domain.tld

SASL/GSSAPI authentication started
  ldap_sasl_interactive_bind_s: Local error (-2)
      additional info: SASL(-1): generic failure: GSSAPI Error: Unspecified GSS failure.  Minor code may provide more information (Server firstname.lastname@example.com not found in Kerberos database)
Answer: Insufficient domain realm mapping.
Required either
krb5.conf:
[domain_realm]
windows.domain.tld = WINDOWS.DOMAIN.TLD
.windows.domain.tld = WINDOWS.DOMAIN.TLD
or
DNS:
_kerberos.windows.domain.tld. TXT "WINDOWS.DOMAIN.TLD"
Only had
DNS:
_kerberos.domain.tld.  IN TXT "DOMAIN.TLD"
Answer: the ldapserver needs to be the first entry in /etc/hosts
192.168.1.5  fqdn.of.your.ad.server some.other.name and.another

If everything is correctly in dns, then remove the line from /etc/hosts all together.


log4net log file not visible in Windows explorer in application installation sub folder

Question: I use log4net for my desktop application written in c# and deployed using Visual Studio Extension "Microsoft Visual Studio Installer Projects" (MSI-Installer). After installation I do not see the log subfolder defined for log4net.
The TARGETDIR in "Microsoft Visual Studio Installer Projects" is defined as [ProgramFiles64Folder][Manufacturer]\[ProductName].
The log4net log file is defined as
<appender name="rollingFile" type="log4net.Appender.RollingFileAppender,log4net">
   <param name="File" value=".\log\MyApp.log" />

After installing the application via the "Microsoft Visual Studio Installer Projects"-created setup.exe and msi-installer I do not see
the log-folder in the Windows explorer under Program Files\MyManufacturer\MyProductName
although Show hidden files, folders, ... is set.
For testing purposes I added the following code to my application:
// does log file exist and grow ?
string currdir = Directory.GetCurrentDirectory();
MessageBox.Show(currdir, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
string[] sa = File.ReadAllLines(currdir + "\\log\\MyApp.log");
MessageBox.Show(sa.Length.ToString(), "Error", MessageBoxButton.OK, MessageBoxImage.Error);
// show lines created this year (2019)
string s = "";
for (int i = 0; i < sa.Length; i++)
{
    if(sa[i].Contains("2019"))
        s = s + sa[i] + "\n";
}
MessageBox.Show(s, "Error", MessageBoxButton.OK, MessageBoxImage.Error);

So, the log file under Program Files\MyManufacturer\MyProductName\log\MyApp.log
can be accessed via the application and I see that it grows!
So the question is: Where is the log subdirectory ? How can I make it visible in the Wndows explorer ?
Is this a permission issue ?
Answer:
Short Version: Please see if you have any virtualized folders under:
  %LocalAppData%\VirtualStore.
If you see a redirected file written here, then you are seeing the result of redirected file writes due to lack of permissions to write to the
  original location. It is a policy controlled feature with a number of snags to be aware of. Details below.

Bitness?: Are you sure you are looking in the right folder? Did you check in Program Files (x86) to be sure?

Virtualization / Data Redirection: I am wondering if you have policies enabled that auto-magically redirect failed writes in secured folders to another writable location? User Account Control: Virtualize file and registry write failures to per-user locations.
Data Redirect / Virtualization Policy Entry:

Note: The local security policy applet is available only in professional, enterprise and corporate editions of Windows. It will be lacking in "home editions".

To find and change this policy, please do as follows (or equivalent by other means):

Windows Key + tap R.
Copy & Paste: %windir%\system32\secpol.msc /s.
Click OK or hit Enter.
Navigate to: Local Policies\Security Options. Look for entry: User Account Control: Virtualize file and registry write failures to per-user locations.
Is this setting set to "Activated"?

Prerequisite Conditions: Even if this setting is set to activated, redirection only works under very specific circumstances.
  For a program to be eligible for virtualization it must comply as follow:

Bitness: Program must be 32bit.
Access Rights: Must not run with administrator rights.
Manifest: Must not have been compiled with a manifest file
  (indicating it is for Vista or later). Or you comment out the security
  section.

(see below for technical details on how to create a test application).
  All of this from this source. And here is another SO answer.

Task Manager & Virtualization: You can see the virtualization status of a program by adding the Virtualization column to the Processes page in Task Manager (in Windows 10 use the Details view - it should say something like UAC-Virtualization there):

Where Does It Write?: If this data redirection / virtualization setting is active, the log is redirected to a writable location automatically whilst still showing the original path in your application. Please check under:   %LocalAppData%\VirtualStore. Procedure:

Windows Key + tap R.
Copy & Paste: %LocalAppData%\VirtualStore.
Click OK or hit Enter.
Check sub folders (if any).

Solution: This problem can be dealt with in several ways.

Write Location: Write to a writable location outright - by design. This is the only sane approach for the future in my opinion.
ACL Permissions: You can open write permission to the location in question and allow users or everyone write access. I do
  not like this approach security-wise.
Elevate: I suppose you can run the application with admin rights by using an elevation manifest. I really do not like this
  approach. Elevated applications are given "the keys to the city" and
  represent a major security risk.

There are some flavors of these "solutions", but I think I will
  suggest these three for now. Maybe check the below link(s).

Technical Notes: Just for the record. With regards to the test application I used to debug:

Standard Windows Forms C# application.
On a button click event or directly in the main function: File.WriteAllText(@"C:\Program Files\My folder\TestFile.txt", "Test"); (create path first and adjust "Program Files" part to your language)
Project => Add New Item... => Application Manifest File.
Comment out the whole "Security" section.
Compile a 32-bit executable.

Now try to build and run. You should see the application activated for virtualization in the UAC-Virtualization column of Task Manager (screenshot above). Clicking the button should write to %LocalAppData%\VirtualStore if the data redirect / virtualization policy is active.

Some Links:

System.UnauthorizedAccessException while running .exe under program files
Please explain VirtualStore for non-experts
Inside Windows Vista User Account Control - Mark Russinovich
Force an existing application to always run with UAC virtualization on
Patching Problems: UAC Virtualization – Allowing standard users to update a system protected area
Comment: Yes, virtualization is activated and I found the log file in a sub folder of the VirtualStore.
Regarding your solution variant "Write location": I somehow hesitate to hardcode a writable
location in my application. For the time being I think I leave the application utilizing the VirtualStore.
Comment: OK, I guess the question is if it is OK for each user to have their own copy of the file - which I think they have when it is virtualized? Also see the link on "patching problems" above. Not a perfect match, but you should have a quick peek.
Comment: The drawback of using VirtualStore is that standard users do not see their AppData in the Windows explorer, as I just checked.
So they would have to be aware to either have an admin looking at the log file or to navigate to it in the cmd shell.
The only writeable location for a standard user I can think of would be %PUBLIC%\documents. provided this environment variable is set everywhere.
What do you think ?
Comment: Would it work to write to the event log? I am not too up to speed on this. I suppose the ACL approach is the "least worst" - just open write access to a shared location? Could have problems if multiple users are logged on? All depends on the application. What would a shortcut in the start menu do? Would it open the VirtualStore file? I honestly really don't like any auto-magic redirection. So much confusion can result. Not sure what to "recommend".


Where do I edit the HTML surrounding a field's output?

Question: I am working on a site that has an image Field (machine name: field_resp_media) that outputs images.
I simply need to add an attribute to the  tag this field outputs.
I've run keyword searches in modules/contrib and modules/custom, and I came up with nothing.
Would anyone know what file I need to edit and add this attribute?
Answer: In Drupal, you don't edit any file belonging to a module/theme you didn't create.
Rather, in your case, you use the hooks Drupal makes available to change the output a module or a theme creates with a theme hook.
In the case of an image field created with the field API, the theme hook that outputs the HTML for the image field when it is rendered on page is theme_image_formatter(). What you need to do is overriding that theme hook in a module or in the theme you use for the site.
Since you don't need to totally change the output from that theme hook, you just need to implement hook_preprocess_image_formatter(&$variables) and add your attribute to $variables['item']['attributes'].
Keep in mind that hook_preprocess_image_formatter(&$variables) is invoked for every image field used by Drupal, so you need to be sure you are altering the output of the right image field.
As per implementing hook_preprocess_image_style(), this hook is not necessarily called for an image field, since theme_image_formatter() contains the following code.
  if ($variables['image_style']) {
    $image['style_name'] = $variables['image_style'];
    $output = theme('image_style', $image);
  }
  else {
    $output = theme('image', $image);
  }

It is just invoked when the image field uses an image style. Plus, it would be invoked every time an image style is used, which doesn't necessarily mean when a image field is rendered on a page.
Similar problem there is with hook_preprocess_field(), which would invoked every time a field is rendered with theme('field').
Comment: Ah, thank you very much. As a new Drupal user I really appreciate you taking the time the explain things simply like this.
Answer: It will possible using THEMENAME_preprocess_image_style & THEME_preprocess_field.
Please check this link. https://www.drupal.org/node/2169157 it will help you.
Comment: Thanks. But where would find preprocess_field?
Comment: **THEMENAME_field_field_image**  here my image field name is **Image** (So drupal machine name will be field_image).  assign field machine name after _field_field_name.


How to set nodes to be excluded from a block view based in the url of current node?

Question: I have a view block listing nodes. Let's say I have the following nodes (it's urls)
<code>node/first-node
node/second-node
node/third-node
node/fourth-node
</code>
Then I have the view block listing this 4 nodes. This block is shown in the First sidebar in all pages.
What I need: when the block is shown at the page node/fourth-node, I need to arbitrarily exclude from the view block from the following nodes.
<code>   node/second-node
   node/third-node
</code>
I need to do this in a way so that then after I can do the same thing with other nodes.
I thought of adding a field to the node called: "Exclude from view block at:" to be filled with the paths (one per line) where the node will not be listed in the view block (similar to blocks settings). Then I will need to modify the view.
Is this a correct approach? If so, what do I have to do in the view?
Comment: do you want to exclude the content inside the views block, based on url ?
Comment: @Bala Yes. I need to exclude `node/second-node` from the block if the url is `node/fourth-node`.
Comment: how do you added the content inside the views, meaning its a title field or what? still not get your point
Comment: I think the correct approach is this solution posted by Matt: '"1 - If you're only working with nodes, then you can create Node Reference field, instead of listing the URIs, so if the URIs changes, they will be updated. You can then access the "NID" that you want to exclude from the page loading the current node. Then you make a hook_views_query_alter and add a filter to the listed node ids."'
Comment: But I don't know how to build the `hook_views_query_alter`
Answer: What you could do if you could use either Views Filters and use the view Filter options to set which URL's to exclude based on tokens.
You could also maybe use Views Rule to try and do something similar.
I think the Views Filters may be an easier option. But if you want to do your suggestion (add a field to the node) then what you can do is pretty much exactly what you said, you would add a filter to the view based upon the available tokens and field data.
Comment: Could you elaborate for the Views Filter options?
Answer: I think this sentence is confusing

I need to do this in a way so that then after I can do the same thing with other nodes and pages.

Pages and nodes could means different things, like if you create a "Page" with Views, how do you want to store the list of excluded node? You can't store it in a "field". Also, if there are different nodes displayed on the same page, which page are you going to exclude from your views? Both of them? The first one?
Well, with your description, I see two options:
1 - If you're only working with nodes, then you can create Node Reference field, instead of listing the URIs, so if the URIs changes, they will be updated. You can then access the "NID" that you want to exclude from the page loading the current node.
Then you make a hook_views_query_alter and add a filter to the listed node ids.
2 - You could create a mapping URI to URIs programmatically (it's also possible to store it as variable or somewhere else, but needs more coding).
Then you need to run your view, get the results, check the URIs and exclude some based on your mapping.
I really suggest you don't do the second solution, because it's uggly :) You'll load a lot more nodes that you actually display. In the first solution, you only fetch the nodes you want. Also in the second solution, everytime your URIs changes, you need to change the mapping...
But the first solution might not match all your needs...
Hope this helps !
Comment: You are right. I meant nodes.
Comment: Then definitely go for the first solution, if you have other content types that need to exclude some nodes, you just need to add the same Node Reference field, and it should be working!
Comment: The first option is what I need. I already created the entity reference field. I also added a relationship in my view: Entity Reference: Referenced Entity (A bridge to the Content entity that is referenced via field_entity_my_nodes). I know I have to add now a Contextual Filter, but I get lost here...
Comment: I would stay away from doing 2, but 1 wouldn't be too bad of a idea.


showing scroll down text and arrow at a particular location on the image?

Question: I have an HTML where I have an image on which I want to add this text SCROLL DOWN with down arrow so that if I click that SCROLL DOWN arrow, it should take me down.
Here is my jsfiddle: https://jsfiddle.net/jgf90mh9/12/
In my jsfiddle I have that SCROLL DOWN text but it is not getting shown at the exact location it should be shown (compare with below image) but when I click that arrow it is taking me down so I was able to make that work. Only thing is not working is the exact location where SCROLL DOWN and down arrow should be shown.
Technically it should be like in this image: https://s3.postimg.org/gbxn8hkf7/home1.png
As you can see on that image there is a SCROLL DOWN text and arrow after that and it is on iStock text over that image. I need to put SCROLL DOWN text and arrow exactly at same location. How can I do that? Also I need to match the SCROLL DOWN font and arrow size everything as well just like what I have in the above image link.
Am I supposed to use font-awesome here? I am already using font-awesome for other purpose in my above jsfiddle.

.scroll-down {
  opacity: 1;
  -webkit-transition: all .5s ease-in 3s;
  transition: all .5s ease-in 3s;
}

.scroll-down {
  position: absolute;
  bottom: 28px;
  left: 55%;
  margin-left: -16px;
  display: block;
  width: 32px;
  height: 32px;
  background-size: 14px auto;
  border-radius: 50%;
  z-index: 2;
  -webkit-animation: bounce 2s infinite 2s;
  animation: bounce 2s infinite 2s;
  -webkit-transition: all .2s ease-in;
  transition: all .2s ease-in;
}

.scroll-down:before {
  position: absolute;
  top: calc(50% - 8px);
  left: calc(50% - 6px);
  transform: rotate(-45deg);
  display: block;
  width: 12px;
  height: 12px;
  content: "";
  border: 2px solid white;
  border-width: 0px 0 2px 2px;
}

section.ok {
  position: relative;
  top: 2000px;
}

    SCROLL DOWN

Comment: What is your question? Please be more specific... To me it sounds like "Please send the css so that I don't have to write it."
Comment: No that's not what I meant. Problem is `SCROLL DOWN` text is not getting shown at the exact location where it should be shown and it's font and text size should match with what I have in that image. This is what I am not able to replicate.
Comment: Yes, but what exactly do you have problems with? There are thousands of guides on how to position stuff with css. And for the font use `font-size` and `font-family`. If it's some special font use [@font-face](https://css-tricks.com/snippets/css/using-font-face/)
Answer: Edited:
1) set to scroll-down text div the left position to 50% adding the width of your side bar left: calc(50% + 131px) than use transform: translateX(calc(-50% - 65.5px)) to center it in the right part of the page.
2) remove the 32px width to the scroll-down text and set it as width: auto to prevent wrap on text and remove height property because you needn't to have it set;
3) set the position of the arrow(:before) to bottom: -10px(stay 10px below the main div) and set the left position in this way left: 50%, than add translate to its transform property like transform: rotated(-45deg) translateX(-50%); to center it under the text.

* {
    margin: 0px;
}

body {
    margin: 0px;
    overflow-x: hidden;
}

p,
span,
h1,
h2,
h3,
h4,
h5,
h6,
td,
div,
ul,
li {
    margin: 0px;
    padding: 0px;
    text-decoration: none;
    list-style: none;
}

.login {
    position: relative;
 top: -50px;
    z-index: 9999;
 color: white;
 text-decoration: none;
 padding: 0 10px;
 font-size: 13px;
}

.signup {
    position: relative;
 top: -50px;
    z-index: 9999;
 color: white;
 text-decoration: none;
 padding: 0;
 font-size: 13px;
}

.above {
 position: relative;
    z-index: 9999;
 padding: 0 5px;
}
.above li{
  display:inline-block;
}

.fa {
 color: white;
 margin: 5px;
}

img {
    /* Set max width to be 100% of the containing element */
    max-width: 100%;
    max-height: 100%;
}

body .company-bio p {
    font-family: 'agenda';
    margin-bottom: 20px;
    letter-spacing: .18em;
    font-family: 'agenda';
    font-weight: 400;
    color: rgb(254, 254, 255);
}

div.company-bio {}

body .company-bio {
 position: relative;
 top: -42px;
    padding-top: 40px;
    margin-left: 131px;
    /*Added Just now */
    padding-bottom: 40px;
    max-width: 100%;
    background: url("https://s30.postimg.org/l04wudgs1/grey-bar.png");
    padding-left: 140px;
    padding-right: 155px;
    font-size: 20px;
    font-family: "Adelle PE";
}

.top h1 {
    color: #f86d2c;
    font-style: italic;
    font-size: 37px;
}

.top p {
    color: white !important;
    background-color: black;
}

.mission-statements .programs {
    position: relative;
    top: 60px;
    width: 300px;
    border-style: solid;
    border-width: 4px;
    text-align: center;
    font-size: 19px;
    border-color: #EF7440;
    padding: 25px;
    margin: 25px;
    margin-left: auto;
    margin-right: auto;
    text-shadow: 1.5px 2.598px 7.65px rgba(40, 40, 41, 0.16);
    font-family: "adelle regular";
    color: rgb(40, 40, 41);
    line-height: 1.979;
}

.top h4 {
    font-size: 25px;
    font-family: "ITC Avant Garde Gothic";
    color: rgb(255, 255, 255);
    text-transform: uppercase;
    line-height: 1.792;
    text-align: left;
    -moz-transform: matrix( 1.65479981820633, 0, 0, 1.66565153423699, 0, 0);
    -webkit-transform: matrix( 1.65479981820633, 0, 0, 1.66565153423699, 0, 0);
    -ms-transform: matrix( 1.65479981820633, 0, 0, 1.66565153423699, 0, 0);
    position: absolute;
    left: 684.247px;
    top: 280.77px;
}

.top h2 {
    position: absolute;
    top: 320px;
    left: 450px;
    letter-spacing: .3em;
    font-size: 22px;
    font-family: "Avant Garde", Avantgarde, "Century Gothic", CenturyGothic, AppleGothic, sans-serif;
    color: rgb(255, 255, 255);
    text-transform: uppercase;
    line-height: 1.6;
    text-align: center;
    text-shadow: 0px 3px 6.37px rgba(40, 40, 41, 0.004);
}

body .northmanwild .title {
    /* background-image:url(assets/img/Uploads/insta-pics.png); */
    width: 100%;
    padding-bottom: 40px;
    padding-top: 40px;
    text-align: center;
    font-size: 37px;
    margin-top: 0px !important;
    margin-bottom: 0px !important;
    font-family: "Adelle PE";
    color: rgb(255, 255, 255);
    font-weight: bold;
    font-style: italic;
    line-height: 1.979;
    text-align: center;
    /*text-shadow: 1.5px 2.598px 7.65px rgba(40, 40, 41, 0.5);
opacity: 100%;
fill: 57%;
*/
}

div.leftBar-bottom {
    background-image: url("https://s17.postimg.org/yvv4w2gmn/nav-background.png");
    float: left;
}

div.northmanwild {
    margin-top: -2px;
    width: 90.1%;
    float: right;
    opacity: 0.8;
    margin-bottom: -7px;
}

body .footer {
    width: 90.3%;
    float: right;
    color: rgb(40, 40, 41);
    padding-top: 30px;
    padding-bottom: 20px;
    font-weight: normal;
    background-size: 100% 100%;
    background-repeat: no-repeat;
    background-image: url(assets/img/Uploads/footer-bg.png);
}

/*FIGURE OUT PROBLEM WITH MISSION STATEMENTS*/

body .mission-statements {
    margin-left: 131px;
    padding-bottom: 130px;
    padding-left: 45px;
    padding-right: 45px;
    background-size: 100% 100%;
    background-repeat: no-repeat;
    background-image: url(assets/img/Uploads/bg-trees.png);
}

body .mission-statements .why {
    padding-top: 40px;
    font-family: "Avant Garde", Avantgarde, "Century Gothic", CenturyGothic, AppleGothic, sans-serif;
    padding-bottom: 40px;
    padding-left: 40px;
    position: relative;
    left: -40px;
    top: 30px;
}

body .mission-statements .how {
    padding-top: 40px;
    font-family: "Avant Garde", Avantgarde, "Century Gothic", CenturyGothic, AppleGothic, sans-serif;
    padding-bottom: 10px;
    padding-right: 40px;
}

body .mission-statements .what {
    padding-top: 40px;
    padding-bottom: 40px;
    padding-left: 40px;
    font-family: "Avant Garde", Avantgarde, "Century Gothic", CenturyGothic, AppleGothic, sans-serif;
    position: relative;
    left: -40px;
    top: 30px;
}

body .mission-statements .why pre {
    padding-left: 40px;
}

body .mission-statements .how {
    margin-top: 0px !important;
    padding-right: 0px;
    margin-bottom: 0px !important;
}

/*.top .imgB1
{
  position: relative;
  top: -225px;
}

*/

.top {
    position: relative;
    top: 0;
    left: 0;
    margin-bottom: -7px;
}

.imgA1 {
    position: relative;
    top: 0;
    left: 0;
}

.clippedmain {
    position: absolute;
    top: 0;
    left: 0;
}

#clippedImg {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 2;
}

#clipimgA1 {
    /*Chrome,Safari*/
    -webkit-clip-path: polygon(1px 100%, 131px 100%, 130px 0px, 0px 0px);
    position: absolute;
    top: 0;
    left: 0;
    z-index: 2;
    opacity: 0.5;
}

/*Firefox*/

clip-path: url("#clipPolygon");

/* iOS support inline encoded svg file*/

-webkit-mask: url(data:image/svg+xml;charset=utf-8;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+CjxzdmcgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB2ZXJzaW9uPSIxLjEiIHdpZHRoPSIwIiBoZWlnaHQ9IjAiPgogIDxjbGlwUGF0aCBpZD0ic3ZnQ2xpcCI+CiAgICA8cGF0aCBpZD0ic3ZnUGF0aCIgZD0iTTI1LDI1MCBMNzAsMjUwIDcxLDI4NSAyNjAsMjg1IDI2MSwyNTAgMTYwLDI1MCAxNjAsMTE1IDIyNSwxMTUgMjI1LDkwIDE2MCw5MCAxNjAsNzAgMjUsNzAgeiIvPgogIDwvY2xpcFBhdGg+CiAgPHBhdGggaWQ9InN2Z01hc2siIGQ9Ik0yNSwyNTAgTDcwLDI1MCA3MSwyODUgMjYwLDI4NSAyNjEsMjUwIDE2MCwyNTAgMTYwLDExNSAyMjUsMTE1IDIyNSw5MCAxNjAsOTAgMTYwLDcwIDI1LDcwIHoiICAvPgo8L3N2Zz4=) no-repeat;

}
.imgB1 {
    position: absolute;
    top: -65px;
    left: 70px;
}
.footer .footer-section1 {
    float: left;
    width: 33%;
}
.footer .footer-section2 .block-title {
    position: relative;
    width: 338px;
    left: -140px;
    font-size: 16px !important;
    font-family: "AvantGarde";
    color: rgb(40, 40, 41);
    /* font-style: italic; */

    letter-spacing: 4px;
    border-bottom: 2px solid #000000;
}
.footer .footer-section2 .block-content {
    font-style: italic;
    line-height: 1.52;
    top: 18px;
    left: 52px;
    position: relative;
}
.footer .footer-section3 .block-content {
    position: relative;
    line-height: 1.52;
    left: 12px;
    letter-spacing: 4px;
    top: 15px;
    font-style: italic;
}
.footer .footer-section3 .block-title {
    border-bottom: 2px solid #000000;
    width: 60%;
    left: 14px;
    position: relative;
}
.footer .footer-section1 .block-content {
    position: relative;
    line-height: 1.52;
    top: 67px;
    left: 125px;
    font-style: italic;
}
.footer .footer-section2 {
    position: relative;
    left: -89px;
}
.footer .footer-section2 {
    float: left;
    width: 33%;
}
.footer .footer-section3 {
    float: left;
    width: 33%;
}
.scroll-down {
    opacity: 1;
    -webkit-transition: all .5s ease-in 3s;
    transition: all .5s ease-in 3s;
}
a{
  text-decoration: none !important;
  color: white !important;
}
.scroll-down {
    position: absolute;
    bottom: 35px;
    left: calc(50% + 131px);
    transform: translateX(calc(-50% - 65.5px));
    margin-left: -16px;
    display: block;
    width: auto;
    height: auto;
    background-size: 14px auto;
    border-radius: 50%;
    z-index: 2;
    -webkit-animation: bounce 2s infinite 2s;
    animation: bounce 2s infinite 2s;
    -webkit-transition: all .2s ease-in;
    transition: all .2s ease-in;
}
.scroll-down:before {
    position: absolute;
    bottom: -10px;
    left:50%;
    transform: rotate(-45deg) translateX(-50%);
    display: block;
    width: 12px;
    height: 12px;
    content: "";
    border: 2px solid white;
    border-width: 0px 0 2px 2px;
}
section.ok {
    position: relative;
    top: 2000px;
}
.copy-rights {
    font-size: 16px;
    font-family: "Avant Garde", Avantgarde, "Century Gothic", CenturyGothic, AppleGothic, sans-serif;
    position: relative;
    top: 48px;
    display: block;
    font-size: 12px;
    text-align: center;
    color: rgb(40, 40, 41);
    font-style: italic;
    -moz-transform: matrix( 0.99963252426166, 0, 0, 0.99882633931212, 0, 0);
    -webkit-transform: matrix( 0.99963252426166, 0, 0, 0.99882633931212, 0, 0);
    -ms-transform: matrix( 0.99963252426166, 0, 0, 0.99882633931212, 0, 0);
    font-style: normal;
}
#leftBar {
    background-color: #030303;
    box-shadow: 2.996px 0.157px 7.65px 1.35px rgba(40, 40, 41, 0.25);
    border-right: solid #EF7440;
    border-right-width: 4px;
    top: 0px;
    bottom: 0px;
    left: 0px;
    height: 2278px;
    position: absolute;
    width: 131px;
    /*Commented today */
    /* opacity: 0.5;  */
}

/*

#holder {
  width: 700px;
   margin-left: 263px;
  padding-left: 50px;
  margin-top: 10px;
  height: 100%;
  float: right;
  position: fixed;

}

*/
@font-face {
    font-family: BEBAS;
    src: url("http://webdesigncove.com/fonts/BEBAS___.ttf")
}
h1.logo {
    font-size: 26px;
    font-style: normal;
    font-weight: normal;
    letter-spacing: normal;
    text-transform: uppercase;
    line-height: 1.2em;
    letter-spacing: -3px;
    color: white;
    text-align: center;
    padding-top: 10px;
}
h1.postTitle {
    font-family: BEBAS, Helvetica, Verdana, Sans-Serif;
}
p {
    font-family: Helvetica, Arial, sans-serif;
    font-size: 15px;
    font-style: normal;
    font-weight: normal;
    letter-spacing: .28em;
    line-height: 1.45em;
}
#navigation {
    padding: 0;
    margin: 0;
    text-align: center;
    position: relative;
    z-index: 3;
}
#navigation li {
    list-style-type: none;
    margin-bottom: 5px;
}
#navigation a:link {
    font-family: "ITC Avant Garde Gothic";
    font-size: 15px;
    font-style: normal;
}
#navigation a:visited {
    color: rgb(255, 255, 255);
}
#navigation a:hover {
    color: #FE5B1F;
}
.copy-right-text {
    font: Bold 12px 'Open Sans';
    color: #ffffff;
    padding-top: 10px;
    text-align: center;
}
nav ul {
    list-style-type:none;
    margin:0;
    padding:0;
}

nav ul li {
    display:inline-block;
    position:relative;
}

nav ul li a {
  color: #fff;
  text-decoration: none;
    font-size: 10px;
  cursor: pointer;
  padding: 10px;
  display: block;
  width: 100%;
}
#leftBar{z-index:99;}
/* nav ul li a:hover {
  background: #00648C;
} */

ul.dropdown-content {
  display: none;
}

SCROLL DOWN

  <svg id="clippedImg" width="0" height="0">
   <clipPath id="clipPolygon">
    <polygon points="1 100%,131 100%,130 0,0 0">
    </polygon>
   </clipPath>
  </svg>

     OUR DNA

RISK

     PROGRAMS

PROFESSIONAL

ADVENTURE SPORT

ENTERTAINMENT

COLLEGIATE

INDIVIDUAL

COMMERCIAL

     RESEARCH

CORPORATE SURVEY

INDIVIDUAL SURVEY

     STORIES

Log In    |
Sign Up

Hello World

Nice Text!

Hello David

Comment: I have done exactly that only. I have placed `SCROLL DOWN` in the same div where my image is there. Check my jsfiddle.  Problem is `SCROLL DOWN` text is not getting shown at the exact location where it should be shown and it's font and text size should match with what I have in that image. This is what I am not able to replicate. It should exactly match with what I have in my image.
Comment: check your edited fiddle https://jsfiddle.net/VLK_STUDIO/jgf90mh9/13/ one problem was you set 32px for the scrolldown div so the text was wrapped because it couldn't stay in that space. Another problem was the top position of the arrow placed with a before pseudo. I've edited it.
Comment: by the way I suggest you to not use absolute position for the side-bar. Main template components should be built in relative position.
Comment: thanks got it.. but how can we put `SCROLL DOWN` at the exact location where `iStock` is there. If you look up my image, you will see where it is there? Any thoughts how we can make that work and put it at exact location?
Comment: check my last reviewed answer and try it on the snippet.
Comment: Are you sure? It looks like now scroll down click is not working and also I have arrows on left side bar texts and that is gone too as well?
Comment: sorry maybe I've not understand very well what you need.


When would one use factorials in probability?

Question: What should a question say so that you know you must use factorials to solve it?
Would the word distinguishable be a keyword?
Comment: Well, if I have $n$ indistinguishable balls, I can arrange them in a row in one way only. But if they are distinguishable, I can do so in $n!$ ways.
Comment: @Peter : I've seen a question answered with factorial and nCr . So what's the difference between them? When should I use factorial and when should I switch to nCr? I know nPr is for when order matters.
Answer: Here, the factorials you mention don't have anything to do with probability - rather, they have to do with combinatorics.  This is because in this context, you are talking about uniformly random elements of some set - and so counting up the elements with a specific property is a necessary step of the process.
Factorials are important because $n!$ is the number of ways to list - in order - a set of $n$ objects that are distinguishable. Because of this, it also comes up in other arrangements - such as the number of ways to choose $k$ elements from a set of $n$ (in an order or otherwise).  Further, many other combinatorial constructions can be carried out starting with these basic ideas of arrangements, and so they involve factorials as well.
You are absolutely right that distinguishable is a keyword that screams factorial; however, distinguishability of the objects is often implicit in the problem, rather than explicitly stated.  The big thing: look for any situation in which you are arranging objects in some way.
Comment: I've seen a question answered with factorial and nCr . So what's the difference between them? When should I use factorial and when should I switch to nCr? I know nPr is for when order matters.
Comment: Factorials serve two purposes, both stated above: the number of ways to order a set of $n$ objects is $n!$, and this makes it useful in other formulas. What you call "nCr" stands for _combinations_ - the number of ways to choose $r$ objects from a set of $n$ distinguishable objects, where order doesn't matter. Contrast this with $nPr$, which is the number of ways to choose $r$ objects from a set of $n$ distinguishable objects when order _does_ matter.
Comment: @MethodManX Also note that the formulas for "nCr" and "nPr" both involve factorials.
Comment: Okay so factorial is number of ways to arrange something and NPR and nCr is number of ways to choose something?
Comment: if the question says indistinguishable is it still factorial?
Comment: Factorials still come in to it, but not in this way. For instance, the number of ways to put $n$ indistinguishable balls in to $r$ boxes turns out to be $\binom{n+r-1}{r}$ - or, in your notation, (n+r-1)Cr.
Comment: Okay thanks for your help buddy.


Trouble understanding jQuery.parseJSON JSON.parse fallback

Question: This is the source of $.parseJSON
function (data) {
    if (typeof data !== "string" || !data) {
        return null;
    }

    // Make sure leading/trailing whitespace is removed (IE can't handle it)
    data = jQuery.trim(data);

    // Attempt to parse using the native JSON parser first
    if (window.JSON && window.JSON.parse) {
        return window.JSON.parse(data);
    }

    // Make sure the incoming data is actual JSON
    // Logic borrowed from http://json.org/json2.js
    if (rvalidchars.test(data.replace(rvalidescape, "@").replace(rvalidtokens, "]").replace(rvalidbraces, ""))) {

        return (new Function("return " + data))();

    }
    jQuery.error("Invalid JSON: " + data);
}

I have trouble understanding the following fallbacks
return (new Function("return " + data))();

and also ( this one is not in jQuery )
return (eval('('+ data + ')')

I would like to know these things

How this parsing fallback works really?
Why eval is not used in the fallback? (Is it not faster than new Function())
Answer: new Function() allows you to pass your function as a string.
In this case, the function is created to simply return the object described by the json string.  Since the json is a valid object literal, this function simply returns the object defined in the json.  The new function is immediately invoked, returning that object.
As far as performance, some quick googling found claims that new Function() is faster than eval, though I have not tested this myself.
Comment: +1: thanks. so both eval and new Function makes the string an object right?
Comment: Yes, I believe the overall result of the two should be the same.


Creating a HTTP load balancer in Google Cloud Platform

Question: HTTP load balancer in GCP has lot of moving parts like global forwarding rules, target proxies, URL map, backend services and instance groups.
Since I found difficult in setting up my HTTP load balancer, I have written the below answer that aggregates the steps for setting up HTTP load balancer in GCP.
This question is a part of another question's answer, which is about building an autoscaled and load-balanced backend.
Answer: At first, GCP offers two types of load balancer, namely the Network and HTTP(s) load balancers. You can find the differences between Network Vs HTTP(s) load balancer here. From this point, I will be calling HTTP load balancer as HLB(coz it is too long).
Here is the architecture of HLB taken from GCP:

As you have seen from the above architecture, there are lot of moving parts for setting up the HLB. Now, We are going to build it from backwards starting from Instance template, Instance group to Forwarding rules.
1. Instance Template: Though instance template is not needed to set up HLB, as you can use even unmanaged instance group and attach it with HLB. I prefer having an instance template and managed instance group, so that autoscaling feature can also be added for the group of homogeneous instances. I have written the steps for creating an instance template here.
Lets assume the instance template to be sample-template.

2. Managed Instance Group: Please go through the steps for creating managed instance group and autoscaling here. Autoscaling and load balancing are independent of each other. Both offers health check. From my perspective, setting up the health check for both load balancer and autoscaling are redundant and I think health check for load balancer alone would do good.
Lets assume the managed instance group to be autoscale-managed-instance group, which is autoscaled and created based on sample-template.

3. service Endpoint: You need to specify the service endpoint which will be used by the HLB. The command for setting up the service endpoint in gcloud:
gcloud compute instance-groups managed \
set-named-ports \
autoscale-managed-instance group \
--named-ports http:80 \
--region asia-northeast1

The above command creates a service endpoint in the instance group that helps the HLB to communicate with the homogeneous instances in the group.
4. Health Check: This is essential so as to assure that HLB routes traffic only to healthy instances. The command to create the health check:
gcloud compute http-health-checks create sample-health-check

5. Backend services: This service routes the traffic to all the backend instances i.e instances in the instance group. It also associates the health check of the instances and make sure it routes traffic only to healthy instances. The command for creating the backend service:
gcloud compute backend-services create \
sample-backend-service \
--http-health-checks sample-health-check

The above command creates a backend service and associates itself to the health check created at the previous step. Now, adding the instance group to the backend service by running the following command:
gcloud compute backend-services add-backend sample-backend-service \
--instance-group \
sample-managed-instance-group \
--balancing-mode RATE \
--max-rate-per-instance 100 \
--instance-group-region asia-northeast1

The above command attaches the instance group to backend-service and also spread the load based on the number of requests using the balancing-mode flag. max-rate-per-instance is used by the autoscaler, if you had set the autoscaler policy based on load balancer utilisation.
6. URL map: Creating a URL map that maps the HTTP request URL to your backend service. The command for creating the URL map:
gcloud compute url-maps create sample-map \
--default-service sample-backend-service

When you choose Content-based load balancer, you need to add many entries in URL maps, so that it routes the request to appropriate backend service.
7. Target HTTP proxy: This step associates the target proxy to the URL map. The command for creating target HTTP proxy:
gcloud compute target-http-proxies \
create sample-target-proxy \
--url-map sample-map

8. Forwarding rules: This is the final step which gives an global external IP address to the HLB.
gcloud compute forwarding-rules \
create sample-forward \
--global \
--ports 80 \
--target-http-proxy sample-target-proxy

Now, accessing the HLB's IP address in the browser gives the web page served by instances in the instance group. This finally sets up an Highly scalable web application which is both autoscaled and load balanced.
This is part 3 of 3-part series about building an autoscaled, load-balanced backend.


The history of promotion and relegation in English football

Question: How exactly did the system of promotion and relegation come about in English football? Specifically, what were the driving forces that made it such an intrinsic part of the game?
As an American soccer fan, I've had difficulty trying to dig up this history. Even though there's no pro-rel in any of the sports in the U.S., it gets talked about a lot in relation to the future of the different soccer leagues.
Comment: There is some interesting info in the answers to [this question](http://sports.stackexchange.com/q/3413/1723), although that question is the opposite of this one: it asks why the US does not use promotion and relegation, and this one asks why England does use it.
Comment: That question is part of what I'm trying to address. How did teams move between the tiers, and why were these methods implemented the way that they are? The links on that page are interesting, but they don't talk about those methods. They talk about promotion, relegation, election and re-election, playoffs and relegation battles and such. But no context is provided for why there was pro-rel or why there was an election (recent history of Glasgow's Rangers is somewhat interesting), or even why leagues assented to these changes in their team lineups at all.
Answer: Here is the relevant information from the Wikipedia article on Promotion and Relegation. Originally the teams who finished bottom of the Football League (the top competition at the time) faced a process of re-election.

The new league was not universally accepted as England's top-calibre competition right away. To help win fans of clubs outside
  the Football League, its circuit was not closed; rather, a system was
  established in which the worst teams at the end of each season would
  need to win re-election against any clubs wishing to join.

The Football Alliance (formed 1889) merged with the Football League in 1892 but not on equal terms. Most of the Alliance teams were entered into the newly formed Football League 2nd Division. The top teams in the 2nd division then replaced the worst teams in the 1st division.

For decades, teams finishing near the bottom of The Football League's
  lowest division(s) faced re-election rather than automatic relegation.
  But the principle of promotion and relegation had been firmly
  established, and it eventually expanded to the football pyramid in
  place today.

So the system of relegation evolved from a series of mergers with other leagues, teams from the newly merged leagues would be entered into lower leagues like the 2nd or 3rd and earn promotion through their league standing rather than election to a higher league. I guess the system came about to ensure their was equality for all the teams and that teams were not gaining promotion based on how teams were voting.


Paginação de resultados com busca em dois campos

Question: Ola, bom dia, estou buscando ajuda pois estou tendo problemas em criar uma paginação de resultados, eu fiz uma pagina que contem dois campos de busca, "o que busca" e "onde busca", ela funciona e faz o filtro correto, porem não estou conseguindo fazer a paginação para limitar os resultados pesquisados, onde estou errando no código a seguir?
    $conexao =mysqli_connect($host,$user,$pass,$bank);
    $pagina = (isset($_GET['pagina'])) ? $_GET['pagina'] : 1 ;

   $consulta1 ="SELECT * FROM registro_clientes";
   $qrTotal  =mysqli_query($conexao,$consulta1) or die(mysqli_error());
   $numTotal =mysqli_num_rows($qrTotal);
   $quantidade = 2;

   $totalPagina=ceil($numTotal/$quantidade);

   $inicio = ($quantidade * $pagina) - $quantidade;

       if(mysqli_connect_errno($conexao)){
           echo "erro conect hen";
           }else{

                 if(isset($_GET['buscar'])&& isset($_GET['onde'])){

                   $nome = $_GET['buscar'];
                   $bairro = $_GET['onde'];
               $consulta = "SELECT * FROM registro_clientes
               WHERE nome_cliente LIKE '%$nome%' AND bairro LIKE '%$bairro%'
               ORDER BY preferencial ASC
               LIMIT $inicio, $quantidade ";
               $executar = mysqli_query($conexao,$consulta);

               $total = mysqli_num_rows($executar);

                    echo  "Encontrado     ".$total. "     resultado(s):";
                        echo "
";
                        echo "
";

               while ($ln=mysqli_fetch_array($executar))

Answer:
É melhor que você use o SELECT COUNT(*) FROM registro_clientes; para descobrir quantos registros existem. A query é muito menor e mais peformatica.
Não entendi direito a conta que você quis usar, mas isso deve funcionar melhor. $inicio = ($pagina - 1) * $numTotal
Comment: obrigado Daniel por me responder, eu fiz seguindo tutoriais, talvez eu não esteja dizendo corretamente o que eu quero dizer. Então eu fiz o que você me falou, ok, ele funcionou, ta ok,
Comment: só que agora eu me deparei com outra questão que não ta nas linhas de código, que é a paginação, voce pode me apontar onde eu to errando nessa questão, segue abaixo o código:                                                                     echo '  primeira pag   - ';

       for($i = 1; $i <= $totalPagina; $i++){

 if($i == $pagina)
 echo $i;
  else
 echo"". $i. "";

      }

    echo" -   ultima pag   ";


Componente p:panelGrid não renderiza, só exibe textos

Question: Tenho um p:panelGrid que recebe dados dinâmicos à medida que são recebidos pelo método onItemchanged mencionado no código. No entanto, conforme a imagem, o componente não renderiza e só exibe os textos.
Já tentei com Glassfish e Jboss e o resultado é o mesmo.
Página (JSF- XHTML):
<?xml version='1.0' encoding='UTF-8' ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

        <h:head>
            <title>PollGF</title>
        </h:head>
        <h:body>
            <h:form>
                <h:commandButton value="Start" actionListener="#{comm.init()}" />

                <h:panelGrid id="grid" columns="7" style="margin-top: 20px">
                    <f:facet name="header">

Soybeans Quotes

Description

Last

Diff

%

Close

Ask

Bid

                    </f:facet>

#{comm.description}

#{comm.last}

#{comm.diff}

#{comm.variation}

#{comm.close}

#{comm.ask}

#{comm.bid}

                </h:panelGrid>

            </h:form>
        </h:body>

Managed Bean:
import br.com.jpoint.periods.SoyNov4;
import com.pretty_tools.dde.DDEException;
import com.pretty_tools.dde.client.DDEClientConversation;
import com.pretty_tools.dde.client.DDEClientEventListener;
import java.util.concurrent.CountDownLatch;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

@ManagedBean(name = "comm")
@SessionScoped
public class Comm {

    private String description;
    private String last;
    private String diff;
    private String variation;
    private String close;
    private String ask;
    private String bid;

    private String code;
    private String value;

    final CountDownLatch eventDisconnect = new CountDownLatch(1);
    final DDEClientConversation conversation = new DDEClientConversation();
    private static final String SERVICE = "TWSVR";
    private static final String TOPIC = "CMA";

    static final String[] items = {
        "0030ZS*1;212", "0030ZS*1;41", "0030ZS*1;1", "0030ZS*1;6", "0030ZS*1;7", "0030ZS*1;25", "0030ZS*1;3", "0030ZS*1;4",
        "0030ZS*2;212", "0030ZS*2;41", "0030ZS*2;1", "0030ZS*2;6", "0030ZS*2;7", "0030ZS*2;25", "0030ZS*2;3", "0030ZS*2;4"
//        "0030ZS*3;212", "0030ZS*3;41", "0030ZS*3;1", "0030ZS*3;6", "0030ZS*3;7", "0030ZS*3;25", "0030ZS*3;3", "0030ZS*3;4",
//        "0030ZS*4;212", "0030ZS*4;41", "0030ZS*4;1", "0030ZS*4;6", "0030ZS*4;7", "0030ZS*4;25", "0030ZS*4;3", "0030ZS*4;4",
//        "0030ZS*5;212", "0030ZS*5;41", "0030ZS*5;1", "0030ZS*5;6", "0030ZS*5;7", "0030ZS*5;25", "0030ZS*5;3", "0030ZS*5;4",
//        "0030ZS*6;212", "0030ZS*6;41", "0030ZS*6;1", "0030ZS*6;6", "0030ZS*6;7", "0030ZS*6;25", "0030ZS*6;3", "0030ZS*6;4",
//        "0030ZS*7;212", "0030ZS*7;41", "0030ZS*7;1", "0030ZS*7;6", "0030ZS*7;7", "0030ZS*7;25", "0030ZS*7;3", "0030ZS*7;4",
//        "0030ZS*8;212", "0030ZS*8;41", "0030ZS*8;1", "0030ZS*8;6", "0030ZS*8;7", "0030ZS*8;25", "0030ZS*8;3", "0030ZS*8;4",
//        "0030ZS*9;212", "0030ZS*9;41", "0030ZS*9;1", "0030ZS*9;6", "0030ZS*9;7", "0030ZS*9;25", "0030ZS*9;3", "0030ZS*9;4",
//        "0030ZS*10;212", "0030ZS*10;41", "0030ZS*10;1", "0030ZS*10;6", "0030ZS*10;7", "0030ZS*10;25", "0030ZS*10;3", "0030ZS*10;4",
//        "0030ZS*11;212", "0030ZS*11;41", "0030ZS*11;1", "0030ZS*11;6", "0030ZS*11;7", "0030ZS*11;25", "0030ZS*11;3", "0030ZS*11;4",
//        "0030ZS*12;212", "0030ZS*12;41", "0030ZS*12;1", "0030ZS*12;6", "0030ZS*12;7", "0030ZS*12;25", "0030ZS*12;3", "0030ZS*12;4",
//        "0030ZS*13;212", "0030ZS*13;41", "0030ZS*13;1", "0030ZS*13;6", "0030ZS*13;7", "0030ZS*13;25", "0030ZS*13;3", "0030ZS*13;4"
    };

    public Comm() {
    }

    public void init() throws DDEException {
//        System.loadLibrary("JavaDDE");
//        System.loadLibrary("JavaDDEx64");
        conversation.connect(SERVICE, TOPIC);
        conversation.setEventListener(new DDEClientEventListener() {
            @Override
            public void onDisconnect() {
                System.out.println("onDisconnect()");
                eventDisconnect.countDown();
            }

            @Override
            public void onItemChanged(String topic, String item, String data) {
                System.out.println("onItemChanged(" + topic + "\t" + item + "\t" + data + ")");
                code = item;
                value = data;

                //******************************************************
                if(item.equalsIgnoreCase(SoyNov4.DESCRIPTION)){
                    description = data;
                } else if (item.equalsIgnoreCase(SoyNov4.LAST)){
                    last = data;
                } else if(item.equalsIgnoreCase(SoyNov4.DIFF)){
                    diff = data;
                } else if(item.equalsIgnoreCase(SoyNov4.VARIATION)){
                    variation = data;
                } else if(item.equalsIgnoreCase(SoyNov4.CLOSE)){
                    close = data;
                } else if(item.equalsIgnoreCase(SoyNov4.ASK)){
                    ask = data;
                } else if(item.equalsIgnoreCase(SoyNov4.BID)){
                    bid = data;
                }
                //******************************************************

                try {
                    if ("stop".equalsIgnoreCase(data)) {
                        conversation.stopAdvice(item);
                    }
                } catch (DDEException e) {
                    System.out.println("Exception: " + e);
                }
            }

        });
        //**********************************************//
        for (String i : items) {
            conversation.startAdvice(i);
        }
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getLast() {
        return last;
    }

    public void setLast(String last) {
        this.last = last;
    }

    public String getDiff() {
        return diff;
    }

    public void setDiff(String diff) {
        this.diff = diff;
    }

    public String getVariation() {
        return variation;
    }

    public void setVariation(String variation) {
        this.variation = variation;
    }

    public String getClose() {
        return close;
    }

    public void setClose(String close) {
        this.close = close;
    }

    public String getAsk() {
        return ask;
    }

    public void setAsk(String ask) {
        this.ask = ask;
    }

    public String getBid() {
        return bid;
    }

    public void setBid(String bid) {
        this.bid = bid;
    }

}

Answer: Observe que ao invés de
 você colocou <h:panelGrid> isso justifica não aparecer as bordas automaticamente.
Mas se você quer usar <h:panelGrid> a borda será exibida somente se você atribuir um valor
para a propriedade border desse componente, como por exemplo:
<h:panelGrid id="grid" collumns="7" border="1" style="margin-top: 20px" >

</h:panelGrid>

Ou então aplicar regras de CSS para esse componente (<h:panelGrid>).
Comment: Valeu pela dica @Luídne, mas, não funcionou mesmo assim. De qq forma, acabei usando uma html  mesmo e funcionou legal. Apenas coloquei dentro as referências ao bean JSF. Ex.: #{bean.attributeName}


Date format - @ symbol has unexpected behaviour

Question: I created a date format , then added that date format to a field within a view. But the @ symbol is automatically appending to the end of the date format (even though i specified it to go into the middle of the date format, and is reflected correctly in the preview). I used PHP:date - Manual as my reference.
My date format: l, F j @ g:ia and it displays as: Wednesday, June 17 @ 4:32pm
Now when I select that date format for my date field within my view, it outputs the said date as: Wednesday, June 17 4:32pm @.
I'm confused because whenever I have put other characters before, it always outputted what I wanted. I've also tried using the html equivalent of @ but it outputs the @ symbol at the end of the format as well.
I'm just wondering if this is a views, php, or date issue? And is there anyway I can output this date as: Wednesday, June 17 @ 4:32pm from a date format?
Comment: Have you tried to use this date format anywhere else? Like content-type field? If so, what was the result? If no, why not?
Comment: @Mołot Yes I have, same behavior.
Comment: So at least it's not views :)
Answer: I was having the same issue and was able to get this working by escaping the @ symbol.
Example: 'M j, Y \@ G:i'


Reflection combined with a glide reflection

Question: Suppose that $A, B, C,$ and $D$ are the vertices $(0, 0), (2, 0), (2, 2),$ and $(0, 2)$ of a square.
The transformation $ρ_{AC} ◦ γ_{DA}$ can be decomposed as the combination of reflections across $4$ mirror lines. Draw
a diagram showing $A, B, C,$ and $D$ and the four mirror lines (marked in order by the numbers $1$ to $4$).
I am having a hard time locating the reflections of the glide reflection. This is what I've done so far:
I said:
$$ρ_{AC} ◦ γ_{DA}=ρ_{AC} ◦ \tau_{DA} \circ \rho_{DA}$$

Now I know that $\tau_{DA}$ must consist of two parallel lines
Let $\rho_{DA}$ be line $1$.
Let $\tau_{DA}$ be line $2$ and $3$ where $2$ and $3$ are parallel. Now I'm confusing do lines $2$ and $3$ have to be parallel to $1$?
and $\rho_{DA}$ is the line $4$
Any insights?
Comment: @MvG, $ρ$=reflections,$γ$=glide reflections,$τ$=translations
Comment: What do $\rho,\gamma,\tau$ stand for? Are these any transformations, or specific kinds of transformations, or objects? Your text seems a bit contradictory in this regard.
Answer: You need to better understand the relation between translation and a pair of reflections. Let's for the moment assume you have two vertical lines of reflection, one at $x=a$ and one at $x=b$. The first maps a point $(x,y)$ to $(a-(x-a),y)=(2a-x,y)$, the latter takes that to $(2b-(2a-x),y)=(x+2(b-a),y)$ so it is a translation by $2(b-a)$ in the $x$ direction. What can you learn from this? On the one hand, the distance of the translation is twice the distance between the lines of reflection, and the direction of the translation is perpendicular to the direction of the lines of reflection. You can also see that the translation is oriented in such a way that it moves from the first reflection towards the second reflection. Now apply this to your situation.
That said, the combination of a glide reflection and a simple reflection is an orientation preserving isometry, and as such is either a translation or a rotation (unless it's the identity), which can be represented using two lines only. So you can pick some points, apply your transformations and use the result to distinguish the cases and find the direction of translation, or the center and angle of rotation.
Or you do this with formulas:
\begin{align*}
\rho_{DA}:(x,y)&\mapsto(-x,y) \\
\tau_{DA}:(x,y)&\mapsto(x,y-2) \\
\rho_{AC}:(x,y)&\mapsto(y,x) \\
\rho_{AC}\circ\tau_{DA}\circ\rho_{DA}:(x,y)&\mapsto(y-2,-x)
\end{align*}
Then you can look for fixed points: a point $(x,y)$ which maps to itself. If you find one, it's the center of rotation. If not, it must be a translation. But does that look like a translation to you?
Comment: I get the point (-1,1), therefore the end result is a rotation centered at (-1,1) with a 180 degree angle of rotation. Thanks a lot!
Comment: @Mark: No, not $180°$
Comment: 90 degrees? How would I find the angle of rotation?
Comment: @Mark: Take one point and transform it. Take the vectors which point from the center of rotation to the preimage resp. to the image point. Compute the angle between those, e.g. following [this post](http://math.stackexchange.com/a/879474/35416).


Help resolving a success probability case!

Question: I am having problems answering this exercise, what is the thinking process that i have to adopt? how do i apply the binomial distribution?
Problem:
It is known from the past experience that the probability that a startup company is successful is 0.2 if its business is hard science based and 0.1 if it is not. It is also known that 1/4 of the startups are hard science based. Determine the probability that a startup is successful.
Comment: Suppose there are $40$ startups. How man do you expect to be successful? What does this say of the probability of a startup to be successful?
Answer: In this case you will need to use weighted probabilities. The answer to your problem is
$$P(successful)=0.25P(successful|science-based)+0.75P(successful|non-science-based)$$
You already stated in the given of the problem that
$$P(successful|science-based)=0.2$$
and
$$P(successful|non-science-based)=0.1$$
So substitute in to get the final answer:
$$P(successful)=0.25(0.2)+0.75(0.1)$$
$$P(successful)=0.05+0.075$$
$$P(successful)=0.125=\frac{1}{8}$$
Which is the final answer.


Mapear classes que herdam o Id de outra classe Entity - EF Core

Question: Preciso mapear as classes Pessoa e Filial com relacionamento um-para-um, onde uma pessoa será apenas uma filial e uma filial estará atrelada a apenas uma pessoa, (Uma PK em Id Pessoa e PK/FK em Id Filial). O Entity Framework Core está se confundindo e colocando PK no Id Filial e FK em Pessoa.
Eu criei uma classe chamada Entity que contém uma propriedade Id para todas herdarem dela. Acho que isso está provocando o problema.

public abstract class Entity
    {
        public Guid Id { get; protected set; }

        public override bool Equals(object obj)
        {
            var compareTo = obj as Entity;

            if (ReferenceEquals(this, compareTo)) return true;
            if (ReferenceEquals(null, compareTo)) return false;

            return Id.Equals(compareTo.Id);
        }

        public static bool operator ==(Entity a, Entity b)
        {
            if (ReferenceEquals(a, null) && ReferenceEquals(b, null))
                return true;

            if (ReferenceEquals(a, null) || ReferenceEquals(b, null))
                return false;

            return a.Equals(b);
        }

        public static bool operator !=(Entity a, Entity b)
        {
            return !(a == b);
        }

        public override int GetHashCode()
        {
            return (GetType().GetHashCode() * 907) + Id.GetHashCode();
        }

        public override string ToString()
        {
            return GetType().Name + " [Id=" + Id + "]";
        }
    }

 public class Pessoa : Entity
    {

        public virtual Filial Filial { get; private set; }

        protected Pessoa() { }

        public Pessoa( Guid id, PessoaNatureza pessoaNatureza)
        {
            Id = id;
            PessoaNatureza = pessoaNatureza;
        }
    }

public class Filial : Entity    {

        public virtual Pessoa Pessoa { get; set; }

        protected Filial() { }

        public Filial(Guid id)
        {
            Id = id;
        }
    }

//Mapeamentos

 public class FilialMap : IEntityTypeConfiguration<Filial>
    {
        public void Configure(EntityTypeBuilder<Filial> builder)
        {
            builder.ToTable("tblFilial");

            builder.HasKey(f => f.Id);

           builder
                .HasOne(u => u.Pessoa)
                .WithOne(p => p.Filial)
                .HasConstraintName("FK_Pessoa_Filial")
                .IsRequired();

            builder.Property(f => f.Id)
                .ValueGeneratedNever()
                .HasColumnName("PessoaId")
                .IsRequired();

        }
    }

public class PessoaMap : IEntityTypeConfiguration<Pessoa>
    {
        public void Configure(EntityTypeBuilder<Pessoa> builder)
        {
            builder.ToTable("tblPessoa");

            builder.HasKey(p => p.Id);

            builder.Property(p => p.Id)
                .HasColumnName("PessoaId")
                .IsRequired()
                .ValueGeneratedNever();

            builder.Property(p => p.PessoaNatureza)
               .HasColumnName("PessoaNaturezaId")
               .IsRequired();

        }
    }
Comment: Funcionou!!! Obrigado Gabriel! :)
Comment: Tente fazer: builder.HasOne(u => u.Filial).WithOne(p => p.Pessoa).HasForeignKey(b => b.FilialId); no mapeamento de Pessoa
Comment: Ah! comenta lá na pergunta para eu poder defini-la como resposta.
Answer: Você precisa fazer o mapeamento na configuração de Pessoas para ele criar corretamente:
...
builder.HasOne(u => u.Filial)
    .WithOne(p => p.Pessoa)
    .HasForeignKey<Filial>(b => b.FilialId);
...


Remove pager from frontpage

Question: On the frontpage of my drupal site I have set up multiple blocks that display content from different views however, in the Content block region my news block is showing a pager that I am unable to remove.
In the news block I have configured the Pager settings to display a specified number of items
and to use a more link that says view all. But the settings will not work in the content block region.
I have also tried to configure the frontpage with similar Pager settings and still no luck.
System Information:

Theme: Bartik 7.12
Comment: Are you sure you're editing the correct display ? Views UI can be misleading at times, especially if you use views with several displays.
Comment: The view I was using is for the index page so I am sure i'm working with the correct view. When i'm in path            **Home » Administration » Structure » Views** I am able to see the changes I have made below the auto preview but the index page itself doesn't display the changes.
Comment: It doesn't prove you're modifying the correct display. Does your view has only one display ? It can be something else, such as a cache issue. Did you try to clear it ?
Answer: I figured out what I was doing wrong. It had to do with the defaults of the page view path.
In the Front Page View I changed the page settings path to /home and went into
Configuration >> Site information and scrolled down to the Front Page settings.
I set the default front page url to home and the pager was removed as per my configuration of the frontpage Page pager settings.

Remove pager from frontpage


How can I display node fields contextually in a block with terms from two separate vocabularies based on node ID?

Question: I've got a content type that has a file field and as part of custom content type that we use to display document links. As part of that content type I have taxonomy 1 "site section" that I'm using to categorize the documents from that field so that they are displayed in specific places on the site. That part is easy.
However, the client just requested an additional level of filtering because they want more fine-grain control over what documents are displayed on what page/node. So far, the best I can figure out is that this level of filtering should be based on a new taxonomy 2 "site sub-section" that I've created that will correspond to specific nodes in the site where the documents need to be displayed.
I'm trying to figure out how I can set my contextual filter so that it will display the resulting file field document results based both on taxonomy 1, and new taxonomy 2, based on the node ID, but I can't figure out the logic to make this happen.
I'm open to other options regarding contextual filters but the node ID is the only one I can think of that would give the specificity necessary to control how and where they're displayed. But, I also cannot figure out to to declare that "when the node ID is [some node id], display nodes with taxonomy terms y and z, and only those nodes."
Is there a way to do this within Views or should I just look to create a custom PHP piece to do this?
Answer: My original goal here was to do this dynamically via contextual filters so I wouldn't need to create a bunch of individual blocks to control various displays. However, I never found a suitable solution for doing this dynamically via the contextual filters, so I ended up resorting to using different blocks with the different filters applied for each one appropriately. It makes a little more of a mess when it comes to managing blocks, but that's not that big a deal.


Alternative method of labeling divs

Question: Can I label my divs in another way to achieve what I'm trying to do here. I have this main div called errors that'll display all error messages. Problem is, my forms input areas and other instruction text need to go in between because the error messages and text need to appear below them. When I do a $('#errors div').empty(); all the instruction text and everthing else gets cleared, because its all under
 Any alternate way of labeling these 3 divs (eUname, ePwd, eMail) so its still under the label "errors"?

     //Input field and other instruction text goes here with its own id

    //Input field and other instruction text goes here with its own id

    //Input field and other instruction text goes here with its own id

Something like:

Answer: You probably want to be using class="error" on all your error divs.

Error here

Error here

This means you can use jQuery like so:
$('.error').empty();

On a related note, you may consider going through some of the tutorials at htmlDog
Comment: you could also use the class on the parent element and just $('.error div').empty()
Comment: wait wait wait @rlemon .error div:empty is perfectly valid as per css3 selectors ,eek i thought the .empty was to select the empty element .. my bad!! >_< , jQuery why u confuse ?
Comment: @rlemon Actually, I think that causes the same problem the OP had originally. His instructional/hinting text is also in divs, which would then be inside the "errors" div.
Comment: ahhh so the magical `>` direct child selector would be used. `$('.error > div')` should do the trick no?
Comment: It depends on where his instructional divs are. They're not shown in the original source example, so we just don't know.
Comment: Something like this ``. Nevermind this does not work.
Comment: My instructional divs are within the errors divs (right now), below the input areas.
Comment: @Norman you can have multiple class names on a single element in HTML, however each element can only contain **one** ID and with that said no other element on the same page (within the same document rather) can contain that same ID. This is why we use classes for styling objects rather that ID's
Comment: Right... Rayan's solution did the job. Thanks to all.

Alternative method of labeling divs


Guitar + Harmonica Sync - Can we sync chords?

Question: Disclaimer: I know nothing about Harmonica. I'm a guitar newbie trying to accompany my friend who is learning to play the Harmonica.
My friend has a "C Major" harmonica (if that's what it's called). He's comfortable playing songs that mostly start with 'C major' chord.
I wish to know if it's possible for harmonica player to play chords 'G', 'D', 'C' and 'A' on this 'C major' harmonica?
Or should he buy harmonica for different scale - for example "G" major harmonica for songs that start with G major?
PS: I don't know if I described my question properly. We are trying to jam together; but we found that I had to switch all the songs to C Major scale to be in sync with him.
Comment: For the chords you're asking about (C, G, D, A), are you asking about D major or minor and A major or minor chords? I'm assuming for G and C you're asking about major chords.
Comment: Yes, all major chords.
Answer: Let's assume it's a Blues harp, with probably 10 holes, rather than a full blown(!) chromatic harmonica. It's marked as a C harp, as all the notes played when blown or drawn will come from the C diatonic scale. Unless they're bent - more later.
To play along with another instrument, it could be played straight, as in both are using key C for the song. Or, it could be used as a cross harp, where the harp is in key C, and the other instrument plays in key F. That way, there are several draw notes which can be 'bent' to produce Blue notes (in key C). It's easier to bend draw than blow notes on a harp.
So, in answer to the actual question, you'll need several harps in different keys. It's what harp players do - they'll use a cross harp for a given key P4 up from the harp they need. The good ones will actually, say, for a song in key A, use two harps - a D harp for the Bluesy bits,(cross harp), and an A harp for the straight parts. Easy way to work out - whatever the main chord is when you draw on the harp, that's the key of the song it'll work best in.
There are also harmonicas available in minor keys, but maybe we don't need to tread that far just yet.
As far as playing chords a C harp will play a good C major triad, a nice G9 triad, and with very careful tongue placement, other 'chords' (dyads) but only those which use notes diatonic to their own key.
Another option is the aforementioned chromatic harmonica - the chromonica - with a button on the r.h. side. But this will, for a marked C chromonica, play in C/G, or C♯/G♯. Probably not favourite alternative keys, though! Having said that, a good player will use a chromonica to solo in all available keys - Toots Thielmans and Larry Adler both spring to mind.
Comment: According to their tuning chart, Hohner diatonic harps in C can play D minor on the draw but not A minor. And you could play F with no 5 on the draw by omitting the D. And a G major triad with no C in it on the low register draw.
Comment: Yes, the harmonica is chromatic - has a button on the side that changes the pitch.
Answer: A standard tuned chromatic harmonica has two major chords, C and C#, and two minor chords, Dm6 and D#m6.
There are als two adjacent notes F and A which could be used as a rudimentary F major.
Standard tuned chromatic harmonicas are notoriously bad at playing chords.
A standard blues harmonica is marginally better: one in C has chords C, G7 and Dm, and the same rudimentary F chord.
If you want to play many chords in a certain key, an alternative approach is to use the so-called spiral tuning.¹ A spiral tuned blues harmonica in C has chords F, C, G, Dm, Am and Em in every octave, though no inverted chords. A spiral tuned harp in the key of D has chords G, D, A, Em, Bm and F#m.
¹) The harmonicas in the link are labelled a bit strangely...


Ruby on Rails app - Adding multiple dynamic input field

Question: I'm a Rails newbie, and I have a RoR app that I'm working on, the app is supposed to allow invited guests to RSVP to a wedding.
I have allowed for fields to be dynamically added, in order to include additional guests (family of an invited guest). But when I add the dynamic field and add the names, only the last name is displayed in the index.
Is there anything specific I need to do to render all other names together in a field within the table?
This is my current controller thus far:

class GuestsController < ApplicationController
skip_before_filter :authenticate_user!, only: [:new, :create]

  def index
    @guests = Guest.all

  end

  def new
    @guest = Guest.new
  end

  def create
    @guest = Guest.all
    @guest = Guest.create(guest_params)
    if @guest.save
      respond_to do |format|
        format.html { redirect_to :back, notice: 'Thank you for replying' }
        format.js
      end
    else
      respond_to do |format|
        format.html { render 'new' }
        format.js
      end
    end
  end

  def destroy
    @guest = Guest.find(params[:id])
    @guest.destroy
    redirect_to guests_path
  end

private

  def guest_params
    params.require(:guest).permit(:status, :name, :message)
  end

end
Comment: I would suggest you to pick up a good book on Rails to start with(like Agile Web Development with Rails) and come back with specific questions when you get stuck with something. Also the paperclip documentation has a good overview on how to start with its integration in a Rails app.
Comment: I agree with @AlokSwain that you need to find a good book. This question is rather broad. But broadly speaking, you need to figure out what kind of data you require first. In Rails, you can add or update tables for your db using the Migration capability (Google search, "Rails migrations"). Once you've defined what your data looks like and what you need to "see", *then* you can start adding models/views/controllers as needed.
Comment: I agree with @AlokSwain as well ... and The Rails 4 Way is another good one to use as is Practicing Rails. Both books greatly help new Railsy folks to get going. In regards to your current issue, I, personally, would want to know what the model structure is like for RSVPing to a wedding. For example, do you have an `Rsvp` model that `has_many` `Guests` (if something like this were the case, there are gems and tools for adding nested objects to the Rsvp form)? The more specific and detailed your question and supporting info is, the better responses you'll get!
Comment: I have a User model that has_many guests, and Guest belongs_to User. I saw that there is a cocoon gem, however it seems that I will have to create nested attributes. the app works well when you enter only one :name, as soon as you add another :name field, then you can only see the last one entered
Answer: Place Guest in place of User
users controler
  def new
   @users = []
   5.times do
   @users << User.new
  end
 end

 if params.has_key?("user")
    User.create(users_params(params["user"]))
  else
    params["users"].each do |user|
     if user["name"] != nil || user["age"] != nil
      User.create(users_params(user))
     end
    end
  end

 def users_params(my_params)
   my_params.permit(:name, :age)
 end

users_form
<%= form_tag users_path do  %>

<% @users.each do |user| %>
<%= fields_for 'users[]', user do |u| %>

<%= u.label :name %>

<%= u.text_field :name %>

<%= u.label :age %>

<%= u.number_field :age %>

<% end %>
<% end %>

<%= submit_tag %>

<% end %>