Add multiple nested underline styles for a same text

Question: Currently, I am working on a project that includes a specific feature to add multiple underline styles to a single text. In this scenario, the text may contain two types of insertions by the user, which may also include misspellings.
I need to style the text with wavy red for misspelling, orange underline for suggestion available and green underline for indicate that is inserted by the user.
I need something like below (please ignore my poor drawing)

I currently have below custom react component:
export type TextType = "inserted" | "misspelled" | "unknown_word" | "Grammer_suggestion"

export interface CustomTextProps extends TypographyProps {
  label: string;
  type?: TextType
}

export const CustomText = ({ label, ...props }: CustomTextProps) => {

  const textStyles: SxProps = {
    textUnderlineOffset: "4px",
    textDecorationLine: "underline",
    textDecorationColor: "red"
    textDecorationThickness: "3px",
    textDecorationStyle: "wavy",
  }

  return (

      <Typography variant="body2" sx={textStyles} {...props}>
        {label}
      </Typography>

  );
};

Comment: https://codepen.io/Paulie-D/pen/VwRBjzZ?editors=1100
Comment: Questions seeking code help must include the shortest code necessary to reproduce it **in the question itself** preferably in a [**Stack Snippet**](https://blog.stackoverflow.com/2014/09/introducing-runnable-javascript-css-and-html-code-snippets/) using the `<>` icon.  See [**How to create a Minimal, Reproducible Example**](http://stackoverflow.com/help/reprex)
Comment: https://stackoverflow.com/questions/40861062/text-with-multiple-underlines
Answer: As i know you cant directly make with different underline styles.But you can make something like this with html, css and linear-gradient image is here

span {
  line-height: 20px;
  background: linear-gradient(0deg, green 1px, white 1px, transparent 1px);
  background-position: 0 100%;
}
.two {
  line-height: 24px;
  padding-bottom: 4px;
}
.three {
  line-height: 28px;
  padding-bottom: 8px;
}
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link rel="stylesheet" href="style.css" />

      Lorem ipsum
        dolor diam lacus.
        sit amet,


How do I create a block only for the user "owning" the profile page?

Question: I made so the logged in user have a recap of their last comments/added node on their profile with a view.
As I am making the profile page public, I need to be able to hide those blocks from others authenticated users.
How can I make the block visible to the user for which the profile page is?
Answer: So I found out :

Either you can directly go in view and add a "FILTER CRITERIA" > "(author) User: Current" and it will hide the content for user that are not the current logged in user
Or you can go in the block settings, select "Pages on which this PHP code returns TRUE (experts only)" and add in the box <?php global $user;
return $user->uid == arg(1); ?> and the block disappear totally if you are not the current user.


Recode a set of columns in a data frame

Question: I have a set of columns in a data frame that I want to recode in the following way (here one example with one variable):
completed_survey$little_control<-car:: recode(completed_survey$little_control,
"1=7;2=6;3=4;4=4;5=3;6=2;7=1")

To be efficient and to not repeat the same code for all different variables, I was thinking to use a function and I was thinking something like this:
recoding <- function(x) {
car :: recode(completed_survey$., "1=7;2=6;3=4;4=4;5=3;6=2;7=1")
}

However, once applied to a variable in the data frame it results in the following error:

Error in `$<-.data.frame`(`*tmp*`, little_control, value = numeric(0)) :
  replacement has 0 rows, data has 139334

I guess it's a problem in the function specification. How can I refer to any generic column-variable in the data frame so then I can apply the recoding function?
Comment: I see some space `car :: `.  Also, the argument `x` is not used inside the function
Answer: There are couple of issues (possibly typo) -1) unnecessary space, 2) function argument is not used inside the function.  Below function have two arguments - one for data, and the next for the column name as a string
recoding <- function(data, colName) {
    car::recode(data[[colName]], "1=7;2=6;3=4;4=4;5=3;6=2;7=1")
  }

recoding(completed_survey, "little_control")

and with a reproducible example
recoding(mtcars, "carb")
#[1] 4 4 7 7 6 7 4 6 6 4 4 4 4 4 4 4 4 7 6 7 7 6 6 4 6 7 6 6 4 2 8 6

Comment: Yes, the typo was in the question only, whereas correct in the code I tried to use. Your solution is perfect, thank you!

Recode a set of columns in a data frame


Android studio- application in emulator stopped

Question: This is the coding to create a shopping list that can de edited or delete when user clicked on the items.
I followed the examples given in web but for some reason, the application just stopped before it can execute anything. I have checked couple of times but cant seems to find any solution. Am I missing something? Thank you
MainActivity.java
public class MainActivity extends AppCompatActivity{

ArrayList<String> shoppingList=null;
ArrayAdapter<String> adapter= null;
ListView lv=null;

@Override
protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar=(Toolbar)findViewById(R.id.toolbar);

    storeArrayVal(shoppingList, getApplicationContext());

    Collections.sort(shoppingList);
    adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1,shoppingList);
    lv = (ListView) findViewById(android.R.id.list);
    lv.setAdapter(adapter);

    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView parent, View view, final int position, long id) {
            String selectedItem = ((TextView) view).getText().toString();
            if (selectedItem.trim().equals(shoppingList.get(position).trim())) {
                removeElement(selectedItem, position);
            } else {
                Toast.makeText(getApplicationContext(), "Error Removing Element", Toast.LENGTH_LONG).show();
            }
        }
    });
}

@Override
public boolean onCreateOptionsMenu(Menu menu){
//inflate menu
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item){
    int id=item.getItemId();

    if(id==R.id.action_add){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Add Item");
        final EditText input = new EditText(this);
        builder.setView(input);
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                shoppingList.add(preferredCase(input.getText().toString()));
                Collections.sort(shoppingList);
                lv.setAdapter(adapter);
            }
        });
        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        builder.show();
        return true;
    }
    return super.onOptionsItemSelected(item);
}
public static String preferredCase(String original)
{
    if (original.isEmpty())
        return original;

    return original.substring(0, 1).toUpperCase() + original.substring(1).toLowerCase();
}

public static void storeArrayVal( ArrayList<String> inArrayList, Context context)
{
    Set<String> WhatToWrite = new HashSet<String>(inArrayList);
    SharedPreferences WordSearchPutPrefs = context.getSharedPreferences("dbArrayValues", Activity.MODE_PRIVATE);
    SharedPreferences.Editor prefEditor = WordSearchPutPrefs.edit();
    prefEditor.putStringSet("myArray", WhatToWrite);
    prefEditor.commit();
}

public static ArrayList getArrayVal( Context dan)
{
    SharedPreferences WordSearchGetPrefs = dan.getSharedPreferences("dbArrayValues",Activity.MODE_PRIVATE);
    Set<String> tempSet = new HashSet<String>();
    tempSet = WordSearchGetPrefs.getStringSet("myArray", tempSet);
    return new ArrayList<String>(tempSet);
}

public void removeElement(String selectedItem, final int position){
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Remove " + selectedItem + "?");
    builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            shoppingList.remove(position);
            Collections.sort(shoppingList);
            storeArrayVal(shoppingList, getApplicationContext());
            lv.setAdapter(adapter);
        }
    });
    builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
        }
    });
    builder.show();
    }
}

AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.shoppinglist">

    <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>
</application>
</manifest>

error message
12-23 23:36:43.038 1259-1259/? D/dalvikvm: Late-enabling CheckJNI
12-23 23:36:43.594 1259-1259/com.example.shyan.shoppinglist W/dalvikvm: VFY: unable to find class referenced in signature (Landroid/view/SearchEvent;)
12-23 23:36:43.626 1259-1259/com.example.shyan.shoppinglist I/dalvikvm: Could not find method android.view.Window$Callback.onSearchRequested, referenced from method android.support.v7.internal.view.WindowCallbackWrapper.onSearchRequested
12-23 23:36:43.626 1259-1259/com.example.shyan.shoppinglist W/dalvikvm: VFY: unable to resolve interface method 17907: Landroid/view/Window$Callback;.onSearchRequested (Landroid/view/SearchEvent;)Z
12-23 23:36:43.630 1259-1259/com.example.shyan.shoppinglist D/dalvikvm: VFY: replacing opcode 0x72 at 0x0002
12-23 23:36:43.646 1259-1259/com.example.shyan.shoppinglist I/dalvikvm: Could not find method android.view.Window$Callback.onWindowStartingActionMode, referenced from method android.support.v7.internal.view.WindowCallbackWrapper.onWindowStartingActionMode
12-23 23:36:43.650 1259-1259/com.example.shyan.shoppinglist W/dalvikvm: VFY: unable to resolve interface method 17911: Landroid/view/Window$Callback;.onWindowStartingActionMode (Landroid/view/ActionMode$Callback;I)Landroid/view/ActionMode;
12-23 23:36:43.654 1259-1259/com.example.shyan.shoppinglist D/dalvikvm: VFY: replacing opcode 0x72 at 0x0002
12-23 23:36:43.786 1259-1259/com.example.shyan.shoppinglist I/dalvikvm: Could not find method android.content.res.TypedArray.getChangingConfigurations, referenced from method android.support.v7.internal.widget.TintTypedArray.getChangingConfigurations
12-23 23:36:43.790 1259-1259/com.example.shyan.shoppinglist W/dalvikvm: VFY: unable to resolve virtual method 432: Landroid/content/res/TypedArray;.getChangingConfigurations ()I
12-23 23:36:43.794 1259-1259/com.example.shyan.shoppinglist D/dalvikvm: VFY: replacing opcode 0x6e at 0x0002
12-23 23:36:43.794 1259-1259/com.example.shyan.shoppinglist I/dalvikvm: Could not find method android.content.res.TypedArray.getType, referenced from method android.support.v7.internal.widget.TintTypedArray.getType
12-23 23:36:43.798 1259-1259/com.example.shyan.shoppinglist W/dalvikvm: VFY: unable to resolve virtual method 454: Landroid/content/res/TypedArray;.getType (I)I
12-23 23:36:43.798 1259-1259/com.example.shyan.shoppinglist D/dalvikvm: VFY: replacing opcode 0x6e at 0x0002
12-23 23:36:43.826 1259-1259/com.example.shyan.shoppinglist I/dalvikvm: Could not find method android.widget.LinearLayout$LayoutParams.<init>, referenced from method android.support.design.widget.AppBarLayout$LayoutParams.<init>
12-23 23:36:43.830 1259-1259/com.example.shyan.shoppinglist W/dalvikvm: VFY: unable to resolve direct method 18422: Landroid/widget/LinearLayout$LayoutParams;.<init> (Landroid/widget/LinearLayout$LayoutParams;)V
12-23 23:36:43.830 1259-1259/com.example.shyan.shoppinglist D/dalvikvm: VFY: replacing opcode 0x70 at 0x0000
12-23 23:36:43.834 1259-1259/com.example.shyan.shoppinglist I/dalvikvm: Could not find method android.widget.LinearLayout$LayoutParams.<init>, referenced from method android.support.design.widget.AppBarLayout$LayoutParams.<init>
12-23 23:36:43.834 1259-1259/com.example.shyan.shoppinglist W/dalvikvm: VFY: unable to resolve direct method 18422: Landroid/widget/LinearLayout$LayoutParams;.<init> (Landroid/widget/LinearLayout$LayoutParams;)V
12-23 23:36:43.838 1259-1259/com.example.shyan.shoppinglist D/dalvikvm: VFY: replacing opcode 0x70 at 0x0000
12-23 23:36:43.966 1259-1259/com.example.shyan.shoppinglist D/AndroidRuntime: Shutting down VM
12-23 23:36:43.966 1259-1259/com.example.shyan.shoppinglist W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0xa4ba9648)
12-23 23:36:43.966 1259-1259/com.example.shyan.shoppinglist E/AndroidRuntime: FATAL EXCEPTION: main
12-23 23:36:43.966 1259-1259/com.example.shyan.shoppinglist E/AndroidRuntime: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.shyan.shoppinglist/com.example.shyan.shoppinglist.MainActivity}: java.lang.NullPointerException
12-23 23:36:43.966 1259-1259/com.example.shyan.shoppinglist E/AndroidRuntime:     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
12-23 23:36:43.966 1259-1259/com.example.shyan.shoppinglist E/AndroidRuntime:     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
12-23 23:36:43.966 1259-1259/com.example.shyan.shoppinglist E/AndroidRuntime:     at android.app.ActivityThread.access$600(ActivityThread.java:141)
12-23 23:36:43.966 1259-1259/com.example.shyan.shoppinglist E/AndroidRuntime:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
12-23 23:36:43.966 1259-1259/com.example.shyan.shoppinglist E/AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:99)
12-23 23:36:43.966 1259-1259/com.example.shyan.shoppinglist E/AndroidRuntime:     at android.os.Looper.loop(Looper.java:137)
12-23 23:36:43.966 1259-1259/com.example.shyan.shoppinglist E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:5103)
12-23 23:36:43.966 1259-1259/com.example.shyan.shoppinglist E/AndroidRuntime:     at java.lang.reflect.Method.invokeNative(Native Method)
12-23 23:36:43.966 1259-1259/com.example.shyan.shoppinglist E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Method.java:525)
12-23 23:36:43.966 1259-1259/com.example.shyan.shoppinglist E/AndroidRuntime:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
12-23 23:36:43.966 1259-1259/com.example.shyan.shoppinglist E/AndroidRuntime:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
12-23 23:36:43.966 1259-1259/com.example.shyan.shoppinglist E/AndroidRuntime:     at dalvik.system.NativeStart.main(Native Method)
12-23 23:36:43.966 1259-1259/com.example.shyan.shoppinglist E/AndroidRuntime:  Caused by: java.lang.NullPointerException
12-23 23:36:43.966 1259-1259/com.example.shyan.shoppinglist E/AndroidRuntime:     at com.example.shyan.shoppinglist.MainActivity.onCreate(MainActivity.java:46)
12-23 23:36:43.966 1259-1259/com.example.shyan.shoppinglist E/AndroidRuntime:     at android.app.Activity.performCreate(Activity.java:5133)
12-23 23:36:43.966 1259-1259/com.example.shyan.shoppinglist E/AndroidRuntime:     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
12-23 23:36:43.966 1259-1259/com.example.shyan.shoppinglist E/AndroidRuntime:     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
12-23 23:36:43.966 1259-1259/com.example.shyan.shoppinglist E/AndroidRuntime:     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
12-23 23:36:43.966 1259-1259/com.example.shyan.shoppinglist E/AndroidRuntime:     at android.app.ActivityThread.access$600(ActivityThread.java:141)
12-23 23:36:43.966 1259-1259/com.example.shyan.shoppinglist E/AndroidRuntime:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
12-23 23:36:43.966 1259-1259/com.example.shyan.shoppinglist E/AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:99)
12-23 23:36:43.966 1259-1259/com.example.shyan.shoppinglist E/AndroidRuntime:     at android.os.Looper.loop(Looper.java:137)
12-23 23:36:43.966 1259-1259/com.example.shyan.shoppinglist E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:5103)
12-23 23:36:43.966 1259-1259/com.example.shyan.shoppinglist E/AndroidRuntime:     at java.lang.reflect.Method.invokeNative(Native Method)
12-23 23:36:43.966 1259-1259/com.example.shyan.shoppinglist E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Method.java:525)
12-23 23:36:43.966 1259-1259/com.example.shyan.shoppinglist E/AndroidRuntime:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
12-23 23:36:43.966 1259-1259/com.example.shyan.shoppinglist E/AndroidRuntime:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
12-23 23:36:43.966 1259-1259/com.example.shyan.shoppinglist E/AndroidRuntime:     at dalvik.system.NativeStart.main(Native Method)

Comment: when you say stopped, does it give you any error or exception..if it does then attach that too.
Comment: You are passing `shoppingList` as `null` to `storeArrayVal(shoppingList, getApplicationContext());`, thats why its crashing.
Comment: may i ask what should i add?
Answer: Issue is in this line,
 storeArrayVal(shoppingList, getApplicationContext());

You should initialise your array before you pass.
ArrayList<String> shoppingList=null;

should be
    ArrayList shoppingList=new ArrayList();
OR
Replace your line,
storeArrayVal(shoppingList, getApplicationContext());

with,
shoppingList=new ArrayList();
storeArrayVal(shoppingList, getApplicationContext());

Comment: the application still stop. i edited my post with the logcat
Comment: post your logcat. So we can help you.
Comment: Are u using any lib files? And which IDE? Android studio or eclipse?
Comment: I'm using android studio. android sdk. genymotion. wat does lib files mean?
Comment: If you have used any .jar file in your app of lib folder and it's not added to your build path then it may cause this kind of error. What is `Landroid/view/SearchEvent` ? in you code


How to create a new Array from Original Array in which the sum of all differences is maximum?

Question:
Candy Love

There are N children coming to the party and you have decided to distribute candies as return gift to those children. Children are numbered from 1 to N. You are given an array A which defines the maximum number of candies which can be given to any child. There are restrictions on number of candies which can be given to any child :

Each child should be given at least one candy.
The maximum candies which can be given to ith child is A[i].

The collective success of party is given by a function S which is calculated as follows :
function S():
Array C denotes the number of candies given to each child
   sum = o
   for i = 2 to N:
       sum = sum a abs(c[i]-[i-1])
   return sum

Now as the host of party you want to maximize the success of party. So distribute the candies in such a way which maximizes the success of party. Output the maximum value of success which can be obtained.
>##Sample Input##
You will be given N denoting the number of children in party and next line will consist of N space separated integers denoting the maximum candies which can be given to any child.

>##Sample Output##
Print the maximum success value of party which can be obtained.

>##Constraints##
2 <= N <= 10^5
1 <= A[i] <= 10^9

>##Sample Input 1##
3
1 2 4

>##Sample Output 1##
3

>##Sample Input 2##
6
3 10 15 10 3 10

>##Sample Output 2##
45

>##Explanation 1##
One of the ways to get success value as 3 is giving {1,2,4} candies to children respectively.

>##Explanation 2##
One of the ways to get success value as 45 is giving {1,10,1,10,1,10} candies to children respectively.

Answer: -to maximize the sum of differences each value X of the array should be changed to either 1 or X
import java.io.*;

class Test
{
    static int maximumDifferenceSum(int arr[], int N)
    {
        int dp[][] = new int [N][2];

        for (int i = 0; i < N; i++)
            dp[i][0] = dp[i][1] = 0;

        for (int i = 0; i< (N - 1); i++)
        {
            //dp[i][0] stores the maximum value of sum using first i elements if ith array value is modified to 1
            dp[i + 1][0] = Math.max(dp[i][0],
                           dp[i][1] + Math.abs(1 - arr[i]));

            //dp[i][1] stores the maximum value of sum using first i elements if ith array value is kept as a[i]
            dp[i + 1][1] = Math.max(dp[i][0] +
                           Math.abs(arr[i + 1] - 1),
                           dp[i][1] + Math.abs(arr[i + 1]
                           - arr[i]));
        }

        return Math.max(dp[N - 1][0], dp[N - 1][1]);
    }

    public static void main (String[] args)
    {
        int arr[] = {3,10,15,10,3,10};
        int N = arr.length;

        // output will be 45
        System.out.println( maximumDifferenceSum(arr, N));

    }
}


Is python package virtualenv necessary when I use python 3.3?

Question: I was looking in Cristoph Gohlke's python packages and I noticed that there is a package Virtualenv for Python 3.3.
Since there is a package venv in the standard python library v3.3, I was wondering if there is an advantage to install this package separately.
Edit: From the documentation of both packages, virtualenv 1.8.2 and venv I can say that the venv standard library package lacks the functionality of:

--no-site-packages option
choice between setuptools or distribute
inability to install pip, since it is not available in the default python installation
no customization of prompt prefix inside the virtual environment --prompt=PROMPT

If there are any other differences that I was unable to spot, please write them here.
Answer: Generally, the virtualenv package is not required when using python3.3 or later, since it was incorporated into the standard library via PEP 405. As you note in the question, there are some relatively small differences between the latest versions of virtualenv and the venv package in the standard library. In part (e.g. --no-site-packages) this stems from the different implementations. Since venv is in the standard library, it doesn't have to jump through some of the contorted hoops that virtualenv does in order to create a self-contained python installation, such as copying much of python's site module.
The best resource is really to read the PEP thoroughly.
Comment: See minute 14 of Brett Cannon's talk at PyCon13 http://pyvideo.org/video/1730/python-33-trust-me-its-better-than-27. He says, "Because it's now directly integrated into python, many of the edge cases you might be used to hitting are now gone, because it's a directly supported thing".
Comment: *Since venv is in the standard library, it doesn't have to jump through some of the contorted hoops(...)* Venv is purely Python package and does not have any special access to any part of Python compared to any 3rd party purely Python package like virtualenv.
Answer: for the question
Is python package virtualenv necessary with venv in the stdlib?
(or what are the differences?)

--no-site-packages is the default in both. The --system-site-packages option exists, but it's broken
distribute is deprecated... nothing to see here
Since Python3.4, ensurepip will provide pip inside the virtualenv. To get it working on Ubuntu/Debian, be sure to install the python3-venv package
No changes here

When venv was first announced, I'd hoped that it get into maintenance mode, to provide bug fixes on the "virtualenv for old pythons", and all developments would shift focus on the stdlib venv. I'm not sure about the project goals/roadmap for virtualenv, but I'm afraid that what I hoped is not happening. So, at least for the time being, I'd keep using the original virtualenv.
Answer: pyvenv was the recommended tool for creating virtual environments for Python 3.3 and 3.4
From python 3.5 onwards use:
python3 -m venv
venv is an inbuilt module with access to python's internals
pyvenv is deprecated in 3.6
Source: https://docs.python.org/3/library/venv.html


Using two routers

Question: I've set up a camera system with all the cameras hardwired to a router. When I plug the router into the clients regular network, the dhcp from the two routers cross over and create problems. The client network is 192.168.1xxx. The camera network is 192.168.0.xxx. What am I doing incorrectly?
Comment: Impossible say from the information you've provided. It depends on your DHCP servers and their configuration, and the router configuration.
Comment: So many questions, the first of which is, why are you plugging the cameras into a separate router?
Comment: To keep the bandwidth off the main network.
Comment: Return the router, buy a switch, or better yet return both routers, build a pfsense and vlan off the cameras, they don't need internet access.
Comment: At a minimum, turn off DHCP on one of the "routers" and use it as a switch.
Comment: Each network has a dhcp server. one is 0.xxx the other is 1.xxx. I assigned mac addresses to the cameras and reserved them on the 0.xxx router but they still get address from the other router sometimes and devices on the other network get address from the camera network.
Comment: they do need internet access
Comment: there are several switches on my network. The NVR doesn't do DHCP so a router needs to provide addresses.
Comment: If I turn off dhcp will the address to mac reservations still work? They are TL-R600VPN routers
Comment: You've plugged the camera router into the main network, so you haven't isolated the traffic.
Comment: It's working at 5 locations but the two larger locations are where the issues are.
Comment: DHCP traffic doesn't cross routers unless the routers are configured to do so. So either the routers are configured to forward DHCP traffic or you've connected the camera router incorrectly to the main network.
Comment: That's what I thought and their IT guy agrees. I went from the wan link on the router to a port on the internet router.
Comment: Is the camera router configured to forward DHCP traffic? Is the main network router configured to forward DHCP traffic? Is it possible that the camera router is configure as a bridge in bridge mode? Is it possible that the main network router interface you plugged into is configured as a bridge in bridge mode? By default, DHCP traffic shouldn't be crossing the routers.
Answer: You have two separate networks. You likely have two DHCP servers (one per router) and it's not being attached to the network correctly.
If you're goal is to segregate the cameras from the regular network, use a switch which is cable of doing VLAN's and separate them that way. This allows the cameras network connectivity, and then you can use the firewall to block traffic as needed to the new VLAN. This also helps to avoid duplicating DHCP configurations.
Currently, you need to make sure that the WAN port on the second router is plugged into a LAN port on the primary router. This should block the DHCP values from being broadcast to the primary network, while still offering DHCP addresses to the cameras. You can then use the second router to provide static IP's to the cameras. You won't be able to access systems behind the second router (when connected to the primary network) without also configuring appropriate NAT/Firewall rules.
Comment: I'd bet that he plugged the one of the "switch" ports on the router (instead of the WAN port) into the office LAN which is why DHCP is being answered by both devices and causing issues.
Comment: I agree. It definitely sounds like a mis-wire which is causing DHCP to broadcast between the two networks. It's also possible there's some kind of loop in the connection as well.

Using two routers


How to hide a discord token on github? discord.py

Question: Discord detect when i have the token in a file on github and reset this. I have tried putting it in an .env file and also the default .gitignore for python but it doesn't work. I don't understand much of this, any solution?
Comment: You shouldn't commit your token with your code to Github
Comment: make the repo private…?
Comment: It's not for a functional bot, i just test stuff
Comment: If you had already committed a .env file before adding it to the list in .gitignore, then it will still be in the repo and you would need to git rm it
Answer: Personally using. env and I put that in my .gitignore and it works fine for me.
Are you sure you opened the project in the same directory as your .git file?
Besides that you should be able to see what GitHub pushes to GitHub by downloading GitHub Desktop. Which you can download here.
Answer: Create an .env file and type in the .env file:
DISCORD_BOT_SECRET=TOKEN


Show that $f(z):=\frac{e^z}{1-z}$ is a holomorphic function on $\mathbb C\setminus${$1$}

Question: If we have $f:\mathbb C\setminus${$1$}$\to\mathbb C$ given by
$f(z):=\frac{e^z}{1-z}$,
how can we show that $f$ is a holomorphic function on $\mathbb C\setminus${$1$}?
--
I understand that for a function to be holomorphic on a domain, it means that it is complex differentiable in this domain, but how do I write this mathematically?
Also, how do I incorporate the $\mathbb C\setminus${$1$} aspect into the answer, as logically it is clearly seen that $z$ cannot take the value of $1$, or else the denominator of $f$ would be zero, but how would I formally add this to my proof? Thanks!
Comment: $e^z$ is holomorphic on $\mathbb{C} \setminus \{1\}$, and $\displaystyle\frac{1}{1-z}$ is also holomorphic on $\mathbb{C} \setminus \{1\}$. The product of two holomorphic functions is also holomorphic.
Comment: Assuming you have proved $e^z$ and $1-z$ are holomorphic in $\mathbb{C}$, use the quotient rule of derivation show that it is differentiable at every $z\ne 0$.
Answer: I suggest you prove (or look up the proof of) a more general fact:
$``$If $g:U \to \mathbb{C}$ and $h:U \to \mathbb{C}$ are holomorphic, then $z\mapsto g(z)/h(z)$ is holomorphic on the set
$$U\setminus\{w \in U \, : \, h(w)=0\}."$$
In your case, we have $g(z)=e^z$ and $h(z)=1-z.$
It is well-known that $g$ is holomorphic everywhere on $\mathbb{C}.$
It is easily seen that $h$ is also holomorphic everywhere on $\mathbb{C}.$
The only point $w \in \mathbb{C}$ with $h(w)=0$ is $w=1.$
Therefore, by the above result, $z\mapsto e^z/(1-z)$ is holomorphic everywhere on $\mathbb{C}\setminus\{1\}.$
Answer: First of all, you only have to consider $z\in\mathbb{C}-\{1\}$. There are several ways to argue here depending on the knowledge that is presumed. What do you know about holomorphic functions?
The most elementary way is to check whether or not the Cauchy - Riemann equations hold and if the derivatives are continuous. (Which they are)


If $80\%$ order coffee, $25\%$ order biscotti and coffee, what is the probability someone does not order biscotti given they do not order coffee?

Question: Really have no idea how to answer this question. Any help would be appreciated!
In an Italian breakfast cafe, a waitress has observed that $80\%$ of her customers order coffee and $25\%$ order both biscotti and coffee.
What is the probability that a randomly selected customer would not order a biscotti, given that he or she does not order coffee?
You need to know the percentage of her customers that order biscotti to answer the above question - let's assume that it is $40\%$.
Comment: classic problem on Baye's
Answer: $Pr(B^c|C^c) = \frac{Pr(B^c\cap C^c)}{Pr(C^c)}=\frac{1-Pr(B\cup C)}{1-Pr(C)}=\frac{1-(Pr(B)+Pr(C)-Pr(B\cap C))}{1-Pr(C)}$
Answer: Let $A$ be the event "does not order biscotti" and $B$ the event "does not order coffee." We want $\Pr(A|B)$, which is $\frac{\Pr(A\cap B)}{\Pr(B)}$.
We need to find the two probabilities on the right. Calculation of $\Pr(B)$ is easy. It remains to calculate $\Pr(A\cap B)$, the probability of ordering neither biscotti nor coffee.
To find $\Pr(A\cap B)$, note that the probability of ordering coffee or biscotti, or both, is $0.8+0.4-0.25$. This can be done by "formula," or by drawing  a Venn diagram.
Answer: $P(\text{no coffee}) = 100 - 80 = 20\%$
$P(\text{biscotti and coffee}) = 25\%$
So, $P(\text{no biscotti and coffee}) = 80 - 25 = 55\%$
$P(\text{biscotti and no coffee}) = 40 - 25 = 15\%$
$$P(\text{ biscotti given no coffee } ) = \frac{P(\text{ biscotti and no coffee) }}{P(\text{  no coffee)}} = \frac{15}{20} $$


Linux CentOS 6.0 - auto_eth0 not connecting

Question: I just recently installed CentOS 6.0 i386 from the Live CD. However, now when I try to run updates, I do not have an internet connection.
I was told to run "system-config-services" and disable "NetworkManager" and enable "Network"
but it still doesn't work.
I configured everything to be setup as manual not automatic. 192.168.1.107 as ip 255.255.255.0 as net mask and 192.168.1.1 as gateway and dns.
What do you recommend?
Comment: From Paweł Brodacki:
 1. How do you connect to the Internet? Do you have a permanent IP address, or is it given by a DHCP server? What is your default gateway? What are DNS servers' addresses?

2. How many NICs do you have in the server? Are you sure you are configuring the correct one?

3. Did this connection ever work (e.g. during the install, or for a different machine)?

4. Does your ISP limit the number of machines you can connect? Do they monitor Ethernet cards MAC addresses?

You really didn't give us much data to work with.
Answer: I recommend configuring eth0 with ifconfig if you really need it connected now.
Do you have multiple nics in that box?  Make sure the mac address for the nic you're using is the mac address listed in /etc/sysconfig/network-scripts/ifcfg-eth0.


MacOS OSX How to change the text to speech voice in terminal or with a keyboard shortcut?

Question: I'm looking for a way to change the voice with a shortcut:
going in to settings->accessibility->Speech and setting the voice "Alex"
take's to long.
Does anyone know a terminal command? Or a way to change it with a keyboard shortcut?
I use speech in English and in Dutch so i have to manually change the voice a couple of times a day. thx
Answer: Have a look at https://github.com/mklement0/voices. Voices is a command line tool for changing the default text-to-speech voice. But the author of the tool warns that:

As of macOS 10.12 (Sierra), there is no documented programmatic way to
  change the default voice. Thus, this utility makes use of undocumented
  system internals, which, unfortunately, means that future
  compatibility of this feature is uncertain.

But at the moment, it seems to work with the latest Sierra version.
In addition, the author also provides links to alternatives, like:

If you have Alfred with its Power Pack, consider workflow speak.awf as a superior alternative.
Comment: Got it working!

Created two executables (terminal command's), That i can call with a keyboard shortcut.

This really save's me so much time! Many thanks!
Comment: `voices` still works in High Sierra, but sometimes fails to restart the Speech Synthesis Server. I did not look in to why, but removed lines 512-517 of `voices` and now use [this](https://bitbucket.org/nJGL/public/src/master/shellscripts/speak.sh) shell script to switch between languages from command line using `voices`by @mklement0 . Even without actively restarting the Speech Synthesis Server, the modified `voices` works for my purposes.
Answer: Thanks @cello for the tip: https://github.com/mklement0/voices
I created a small appleScript to change the voice
on run {}
    set changeVoiceToo to ""
    set currentVoice to do shell script "export PATH=/usr/local/bin:$PATH;" & "voices -b"

    if currentVoice is "Alex" then
        set changeVoiceToo to "Xander"
    else
        set changeVoiceToo to "Alex"
    end if

    do shell script "export PATH=/usr/local/bin:$PATH; voices -d " & changeVoiceToo

    do shell script "export PATH=/usr/local/bin:$PATH; say " & changeVoiceToo
    # display notification currentVoice sound name "Tink"
    display notification "Voice Change!" with title changeVoiceToo # sound name "Tink"
end run

I hope this is useful to somebody
Answer: MAC OS 13 VENTURA:
This script lets you change language on Ventura, so that you can get the Siri voice on multiple languages.
Open automator -> Add run apple script -> Past the script and create an app.
Set your desired language on line 22. Make one copy of the script pr language
The script works by activating Voice over to navigate, so you have to deactivate the VoiceOver welcome screen for it to work correctly. On the first run you will be told that the app lacks permission to keystroke.
What you have to do is go to system settings, Privacy & Security -> Accessibility -> and turn on the app you created. Use the pluss sign and add it if it did not appear automatically.
on run {input, parameters}
    set volume with output muted #Turns off the volume
    tell application "System Settings" to activate
    delay 1
    tell application "System Events"
        key code 96 using command down #CMD F5 activate voiceover
        delay 4 #waiting to load, increase if buggy
        key code 125 #DOWN ARROW Moves from apperance to Accessibility
        delay 1
        key code 48 #TAB Scroll Area 1
        delay 1
        key code 48 #TAB Scroll Area 2
        delay 1
        key code 48 #TAB Scroll Area 3
        delay 1
        key code 48 #TAB Scroll Area 4
        delay 1
        key code 49 #SPACE Entering Spoken Content Menu
        delay 1
        key code 49 #SPACE Entering System speech language MENU
        delay 1
        keystroke "English" #Choose your language. First letter is enoufgh like N for Norwegian.
        delay 1
        key code 36 #ENTER Selects the language
        delay 1
        key code 96 using command down #de-activate voiceover
        delay 1
        tell application "System Settings" to quit
        delay 3
        set volume without output muted #Turn the volume back on
    end tell
    return input
end run


Can we extend NP-HARD proof of one problem to another?

Question: I have tried to put my question in following diagram

I have two domains A and B. I can formulate two optimizations problems 1 and 2. In domain A, efficient algorithms exist for solving these two optimization problems. Moreover they both share a mathematical framework "tool", which is well defined in Domain A.
In domain B, It has been proved that optimization problem 1 is NP-hard. Moreover, I also know that "tool" does not exists in domain B. What can I say about optimization problem 2 in domain B. Can we say that it is NP-HARD as well?
I am not a mathematician, so I am not very familiar with the mathematical rigor that we need here.
I will appreciate any help in this regard.
Also, can someone can suggest a better title for this question?
Answer: Technically, you can't say anything about what would happen in domain B. Depending on the domains, and the optimization problems, the optimization problem 2 could be defined in such a way that it is easy in domain A but NP-hard in domain B, or easy in both domains even though your "tool" as you say doesn't work in domain B.
As far as determining what's going on, you can either try to come up with a new polynomial time algorithm for optimization problem 2 in domain B, or, if your optimization problems 1 and 2 are related, then within domain B, you can try to reduce solving an arbitrary optimization problem 1 instance in domain B into an optimization problem 2 instance in domain B (polynomial time reduction), and this would show problem 2 is NP-hard in domain B.
Comment: @NAASI Basically, take any possible input for your optimization problem 1 from domain B, and show that you can solve it quickly IF you can solve some kind of related input for optimization problem 2 (in domain B). The length of the new input for problem 2 needs to be polynomial in the length of the input for problem 1.
Comment: can you please elaborate the term "instance" here?


Bloquear eventos com jquery

Question: Estou há algum tempo vasculhando a documentação do jquery em busca de uma função com o seguinte comportamento
Suponhamos que temos dois botoes na tela cada um com um evento de click diferente:
<button>Effetc1</button>
<button>Effetc2</button>

 Click in first button to change

O primeiro dispara uma animação, já o segundo lança alerta. Eu quero que o evento do segundo botão aguarde até a conclusão do primeiro.
Porém são dois eventos separados, então não dá para sobrepor callbacks, eu quero que durante a execução do primeiro evento, nenhum outro evento seja executado a até a conclusão do primeiro. Exemplo abaixo
http://jsfiddle.net/xwky0wc1/3/
Answer: As vezes um simples fleg pode resolver o seu problema.
Exemplo:

$(document).ready(function() {
  var fleg = false;
  $('button:eq(0)').click(function() {
    $('div').html('click in second button during animation');
    $('div').animate({
      width: 300
    }, 5000, function() {
      $('div').animate({
        lineHeight: 100
      }, 5000, function() {
        fleg = true;
      });
    });
    return false;
  });
  $('button:eq(1)').click(function() {
    if (fleg) {
      alert('Shit, stoped animation... Wait to finish idiot jquery');
    }
  });
});
div {
  background: red;
  color: white;
  text-align: center;

<button>Effetc1</button>
<button>Effetc2</button>

Click in first button to change

Uma função que faça isso em jquery eu nunca vi, mas você pode aguardar o termino do animate colocando uma function(){} e colocar o fleg verdadeiro para poder acionar o botão.

Bloquear eventos com jquery


Interpreting $\begin{bmatrix} 1 & 2 & 3 \end{bmatrix} \cdot h $ as a scalar or matrix multiplication

Question: As part of another problem I am working on, I have the following product to work out.
$\begin{bmatrix} 1 & 2 & 3 \end{bmatrix} \cdot h $
where $h$ is a scalar. My question is, if I commute the row vector and the scalar then I can just multiply it through. If I think of the $h$ as a $1 \times 1$ matrix however, it seems that this isn't allowed.
I know it sounds simple, but I want to understand the subtlety involved.
Comment: Why do you think it is not allowed? http://en.wikipedia.org/wiki/Matrix_multiplication#Scalar_multiplication
Comment: Looking at all of the answers now...it seems like we all said the same thing but in a different way: matrix multiplication is **not** commutative.
Answer: If $h$ is a scalar:
$$h\cdot \begin{bmatrix} 1 & 2 & 3 \end{bmatrix} = \begin{bmatrix} 1 & 2 & 3 \end{bmatrix} \cdot h = \begin{bmatrix} h & 2h & 3h \end{bmatrix} $$
If $h$ is a $1\times 1$ matrix,
$$\begin{bmatrix} h \end{bmatrix} \begin{bmatrix} 1 & 2 & 3 \end{bmatrix} = \begin{bmatrix} h & 2h & 3h \end{bmatrix}$$
and the multiplication yields the $1\times 3$ matrix we would expect. However, the following multiplication is not defined because the number of columns of the first matrix does not equal the number of rows of the second matrix:
$$\begin{bmatrix} 1 & 2 & 3 \end{bmatrix} \begin{bmatrix} h \end{bmatrix}$$
Thus the matrix multiplication is identical to scalar multiplication when defined. It's just that scalar multiplication is more universal and more defined.
Answer: As a reminder, if we have $A$ and $B$ be $n\times m$ and $m \times p$ matrices (respectively) then $AB$ is a $n \times p$ matrix. Matrix multiplication will work if the number of columns of the first matrix matches the number of rows of the second matrix. This is also the reason why matrix multiplication is not commutative. If we let $[h]$ be a $1\times 1$ matrix and we have the $1 \times 3$ matrix $\begin{bmatrix} 1 & 2 & 3 \end{bmatrix},$ then we can certainly multiply the two. The product will be a $1 \times 3$ matrix equal to $\begin{bmatrix} h & 2h & 3h \end{bmatrix}$.
So that all works out fine if we treat $h$ as a $1\times 1$ matrix and we multiply from the left. It is clear we cannot multiply a $1\times 1$ matrix on the right of $\begin{bmatrix} 1 & 2 & 3 \end{bmatrix}$ and we couldn't multiply at all if you had a matrix with more than one row. We can get around this if we scrap the idea that $h$ has to be a $1 \times 1$ matrix. Consider the $n \times n$ identity matrix $I_n$, except with a diagonal of $h$'s instead of $1$'s. Simply make $n$ is the number that allows you to multiply with the matrix you are after. For example, if we want to multiply on the right of  $\begin{bmatrix} 1 & 2 & 3 \end{bmatrix}$ we need $n = 3$, and you should find that $$\begin{bmatrix} 1 & 2 & 3 \end{bmatrix}\begin{bmatrix} h & 0 & 0 \\ 0 & h & 0  \\ 0 & 0 & h \end{bmatrix} = \begin{bmatrix} h & 2h & 3h \end{bmatrix}$$
The reasoning has gotten a bit circular now as $\begin{bmatrix} h & 0 & 0 \\ 0 & h & 0  \\ 0 & 0 & h \end{bmatrix}  = hI_3$. So in conclusion, scalars are not matrices, and matrices are not scalars. Even if sometimes they can be coaxed in a way to make it look like they act the same. There are very nice, scalar-exclusive properties that you can take advantage of as you work through linear algebra, just as there are very nice matrix-exclusive properties.
Answer: There's not really a "subtlety" so to speak. Matrix products are not commutative. So $h\cdot A$ for a matrix $A$ is different than $A\cdot h$ for the same matrix $A$. In your example, $h$ is a scalar and may be thought of as a $1\times 1$ matrix but your matrix $A$ is $1\times 3$. So the product $h\cdot A$ is defined whereas $A\cdot h$ is undefined.
The real problem for you it seems is in understanding when a matrix product is defined. Does my explanation above make sense?


How to test for mediation when working with binary data?

Question: I want to assess if a single variable is mediating the effects of a set of IVs on a single DV. All variables in the model (IV, DV and the mediator variable) are dichotomous (0, 1) and observed. What is the appropriate statistical procedure to test this model?
I have run separate binary logistic regressions, and have found that:

IVs are associated with the mediator variable, and
the mediator is associated with the DV. However,
IVs are not associated with DV when removing the mediator variable from the model.
Comment: Informally, if you observe those three things, then there appears to be mediation (although, as always, you can't, statistically, rule out the possibility of some sort of confounding creating this pathway spuriously). But, it appears this question is asking for a formal statistical testing framework - is that the case?
Comment: Your third finding makes this sound more like a case of suppression than mediation. You may want to check out [this article](http://www.ncbi.nlm.nih.gov/pmc/articles/PMC2819361/) on the topic.
Answer: You can easily model this in structural modeling software such as Mplus. You need a model of
X --> Z --> Y
where Z is the mediator and inspect fit and/or residual correlations. If the model fit is poor, then Z may be an imperfect mediator, and residual correlations between the three variables should be inspected to see where residual effects persist, e.g. between X and Y if you have imperfect mediation.
I am suggesting to use Mplus because it can very easily deal with categorical variables in its general linear modeling framework.
Answer: Nathaniel Herr discussed the problem (and solution) of using Logit regression with dichotomous mediator, predictor and outcome in his blog
http://www.nrhpsych.com/mediation/logmed.html


How to change the structure of output.xml from Robot Framework output

Question: We are passing three text files to pybot and the output generated is in the hierarchical format. For Example, in Test Statistics section of the report.html file, under Statistics by Suite, Test 1 & Test 2 & Test 3.Test 1 is observed. It was changed to display just Test 1 by editing the report.html template file under /usr/local/lib/python2.7/dist-packages/robot/htmldata/rebot .
The log.html template file was also changed to get the desired output like above in log.html file. But I am not finding, where to change to get the desired in output.xml file. The output.xml file still has the format like Test 1 & Test 2 & Test 3.Test 1 . Could someone help to resolve this ?
Comment: First let me say that changing files in installed RF packages is very bad practice. Believe me that, you don't want to go that way. Second, from your question I understood that you are trying to change only the "heading" or "name" of test suite? You can change that only with `--name ` option. See the [docs](http://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#setting-the-name)
Answer: There is no way to modify the format of the output.xml file that was generated by robot. You have a couple of choices.
First, you can post-process output.xml with xslt or any other tool to transform it into whatever format you want. It's a very simple structure that is easy to parse.
Your second option is to ignore the output.xml and write your own using the listener interface. Through the listener interface you can get a callback for every suite, testcase and keyword where you can write your own output in whatever format you like.
Answer: C:\Users\tijne\AppData\Local\Programs\Python\Python38\Lib\site-packages\robot\htmldata\rebot


Application of Newton-Raphson method

Question: Is Newton-Raphson method applicable to solve rational equations? or any equation except polynomial equations.
Answer: Newton's Method is applicable for real-valued functions. However, it does not work all the time. There are many possible reasons for Newton's Method to fail such as  if the derivative doesn't exist at the root.

Application of Newton-Raphson method


When I save a user account as an admin, I get logged in as that user

Question: I'm experiencing a strange issue that I'm having a really hard time debugging.
When I save a user account (of an authenticated user) as an admin, the account is saved, but when the page reloads I get an access denied and I am suddenly logged in as the user I saved, not the admin.  This happens whether I save the account in the UI (via the People page) or save the account using a rules action.
Recently, I added a custom function and modified a few of my rules, so these changes are likely to be the cause of the problem.  The site is version-controlled using git, so I can roll back to a working version, but I would like to attempt to determine what I did wrong.
I have Netbeans working with Xdebug.  I just don't know where to set breakpoints or how otherwise to start looking for the source of this problem.
Answer: Can you re-produce the problem from CLI?
Using drush scr, bootstrap, login as user 1, save a new user, check if your ID changed.
If you can do this from CLI, git bisect can be very helpful in finding the commit that caused it.
Comment: Wow, I didn't know about `drush scr`.  I will try to do this but first I will need to track down some examples.
Comment: It turns out you can't call `user_load()` from within `hook_user_presave()`.


linear restriction on a particular covariance matrix

Question: Suppose I have this covariance matrix of regression coefficient for $\hat{\beta_1}$ and $\hat{\beta_2}$
\begin{pmatrix}
&5 &-3\\
&-3& 0.5\\
\end{pmatrix}
And I'm going to test
$\begin{cases}
H_0:\beta_1+\beta_2=1\\
H_1:\beta_1+\beta_2\neq 1
\end{cases}$
If I am going to test with t-ratio I need to compute $se(\hat{\beta_1}-\hat{\beta_2}-1)$ so the square root of the variance:
$VAR(\hat{\beta_1}-\hat{\beta_2}-1)=VAR(\hat{\beta_1})+VAR(\hat{\beta_2})+2cov(VAR(\hat{\beta_1}),VAR(\hat{\beta_1}))=5+0.5-2*3<0$
This is an error depending on the covariance matrix which is not positive definite (in fact real part of the eigenvalues are not all positive).
AM I right?
Comment: On an exercise, but I think that there is obviously an error on the covariance matrix.
Comment: How did you get this covariance matrix?
Answer: covariance matrix is always non-negative definite if your design matrix is full rank.
Just compute your t-ratio as:
t-value=(β1+β2-1)/sqrt([1 1] * covb * [1 1]')
Comment: 1) Every covariance matrix is positive semi-definite. 2) sqrt([1 1] * covb * [1 1]' is Negative!


Controlling the number of parallel tasks running simultaneously

Question: I have a Windows service application that has a number of different jobs that need to be done in parallel and are spawned on three different schedules. However I want to make sure that at no point of time more than N tasks are running.
This is not a duplicate of this question, because that is about limiting the number of tasks that are started per second, not the number that are running concurrently.  Also not a duplicate of this because my tasks are on separate schedules so cannot be queued simultaneously.
Here is some code to provide context:
namespace WindowsService1
{
    public partial class Service1 : ServiceBase
    {
        List<Task> ServiceTasks;
        private List<Timer> ServiceTimers;
        private static int N = 10;

        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            List<double> Times = new List<double>(){1000d,2000d,5000d};
            for(int i = 0; i<3 ; i++)
            {
                 var t = new Timer(Times[i]);
                 t.AutoReset = true;
                 ServiceTimers.Add(t);
            }
            ServiceTimers[0].Elapsed += Timer1Elapsed_DoSomething;
            ServiceTimers[0].Start();
            ServiceTimers[1].Elapsed += Timer2Elapsed_DoSomething;
            ServiceTimers[1].Start();
            ServiceTimers[2].Elapsed += Timer3Elapsed_DoSomething;
            ServiceTimers[2].Start();
        }

         private void Timer1Elapsed_DoSomething(object sender, ElapsedEventArgs e)
         {
            ServiceTasks.Add(Task.Factory.StartNew(() => ServiceWork.DoTask1()));
         }

         private void Timer2Elapsed_DoSomething(object sender, ElapsedEventArgs e)
         {
            ServiceTasks.Add(Task.Factory.StartNew(() => ServiceWork.DoTask2()));
         }

         private void Timer3Elapsed_DoSomething(object sender, ElapsedEventArgs e)
         {
            ServiceTasks.Add(Task.Factory.StartNew(() => ServiceWork.DoTask3()));
         }
    }
}

How can I modify this code to ensure that only N tasks will be running at any given time?
Comment: OK, I think that's a legitimate difference, so probably not a duplicate.  [One of the answers to that question](http://stackoverflow.com/a/4088240/886887) does cover this situation, but there isn't very much detail, it should probably be expanded on.  It isn't entirely clear to me how the linked code works.
Comment: possible duplicate of [Limit the number of Tasks in Task.Factory.Start by second](http://stackoverflow.com/questions/18771524/limit-the-number-of-tasks-in-task-factory-start-by-second)
Comment: How is this different from [System.Threading.Tasks - Limit the number of concurrent Tasks](http://stackoverflow.com/questions/2898609/system-threading-tasks-limit-the-number-of-concurrent-tasks) ?  (If you're concerned that the fact that the application is a service might make a difference, it doesn't.)
Comment: @HarryJohnston, thank you. But, in the question you pointed out, all 100 tasks are spawned simultaneously. In my case, the tasks are starting at different times in different functions, I am not sure how to process incoming tasks as new tasks come in. I would be much obliged if you can explain how to do that, or explain how the answer is the same as in the question you pointed out, if that is the case.
Answer: SemaphoreSlim is a class that allows you to do just that. It's a lock for N simultaneous "threads".
Like that:
SemaphoreSlim s = ...;
async Task F() {
 await s.WaitAsync();
 DoWork();
 s.Release();
}

You can use the synchronous API as well if you don't mind 1MB of stack usage per thread waiting.

This:
 Task.Factory.StartNew(() => ServiceWork.DoTask3())

becomes:
Task.Run(async () => {
 await s.WaitAsync();
 try {
  ServiceWork.DoTask3();
 } finally {
  s.Release();
 }
});

And you can start an unlimited number of these and they will self-throttle.
The list of tasks is still required so that you can shut down the service cleanly by waiting for all tasks to complete and handling their errors.
Comment: @T2Tom: you specify N in the constructor for SemaphoreSlim.
Comment: WaitAsync does not block and thanks to await the entire operation does not block either.
Comment: Thank you for this clue. Could you kindly expand on it in the context of my problem? Do I not need List anymore?
Comment: Can .NET efficiently allow tasks to block like that?  Or will there be one thread per waiting task?  (Not a problem unless there are a lot of them, of course, so may not matter to the OP.)
Comment: Could you clarify where/how you are specifying the value of N here?


Custom view created with Interface Builder does not render when called in other views

Question: I have an xib for the main window, and I created a custom view in the following steps:

Create a new class which inherits from NSView.

MyView.h:
    #import <Cocoa/Cocoa.h>
    IB_DESIGNABLE
    @interface MyView : NSTableCellView
    @end

MyView.m:
    #import "MyView.h"

    @implementation MyView

    - (void)awakeFromNib {
        NSLog(@"Post view awaking from nib.");
    }

    @end

Create a new xib, and set the root view's class to the class created above. And design in that xib.
Set outlets from the xib to the class.

And I tried to use this custom view in the main window in the following steps:

Drag a custom view to the main window's xib.
Set the class of that custom view to the class created above.

But nothing renders. From the log, I can see that code in awakeFromNib from the custom view class is executed. When I set the class to be IB_DESIGNABLE, the view gets empty in the main window's xib, different from what I designed.
I tried to set the file owner of the custom view's xib to the custom class, but nothing changed.
I guess the problem is that, the custom view's xib file is not actually loaded. When I googled it, there seem to be few references on this exact topic. So, how should I actually achieve this goal? I.e., design a view in IB, implement its methods in a class, associate these two, and expose it just like a system view for use in other xibs?
UPDATE:
I found a tutorial and realized what I lack (for correctly rendering the view when built). I have to add an outlet from the view in the xib to the view class:
@property (nonatomic, strong) IBOutlet NSView *view;

, and then load it in the (id)initWithCoder:(NSCoder *)coder method.
[[NSBundle mainBundle] loadNibNamed:@"MyView" owner:self topLevelObjects:nil];
[self addSubview:self.view];

But the view still won't render in the interface builder.
Comment: Just a small comment:  your IBOutlets (unless in special circumstances) should always be weak.  Reason is the reference is owned by the nib loader.
Comment: Also, you're not "Creating a new class which inherits from NSView" really, its actually inheriting from NSTableCellView.  There is no telling what NSTableCellView is doing, so maybe you can simplify your code for now to just NSView?
Comment: Another thing to look at, in iOS loadNibNamed: actually returns an array of views, not the actual view.  So check the return.

NSArray* views = [[NSBundle mainBundle] loadNibNamed:@"MyView" owner:self topLevelObjects:nil];

MyView* myView = views[0];
Answer: Your guess is correct: the xib is not being loaded. The nib loader doesn't know about your custom view's nib. The nib framework doesn't provide a facility for defining that connection, so you need to write code to load the xib.
Here's what I'd do. Add a contentView property to your custom view:
@interface MyView ()

@property (nonatomic, strong, readwrite) IBOutlet NSView *contentView;

@end

In your custom view's nib, set the custom class of the root view back to NSView and disconnect all the (no-longer-valid) outlet connections from it. Set the custom class of File's Owner to your custom class name (e.g. MyView). Connect the root view to File's Owner's contentView outlet, and connect all the other outlets from File's Owner to the appropriate objects in the nib.
Then implement awakeFromNib in your custom view subclass to load the nib and add the content view as a subview:
@implementation MyView {
    BOOL hasLoadedOwnNib: 1;
}

- (void)awakeFromNib {
    [super awakeFromNib];
    [self loadOwnNibIfNeeded];
}

- (void)loadOwnNibIfNeeded {
    if (hasLoadedOwnNib) {
        return;
    }

    hasLoadedOwnNib = YES;

    [[NSBundle bundleForClass:self.class] loadNibNamed:NSStringFromClass(self.class) owner:self topLevelObjects:nil];
    self.contentView.frame = self.bounds;
    self.contentView.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable;
    [self addSubview:self.contentView];
}

@end

Note that you have to be careful not to allow infinite recursion. When your app loads the main window's nib, it will create an instance of MyView and (eventually) send it awakeFromNib. Then, in awakeFromNib, MyView loads its own nib, where it is the File's Owner. The nib loader sends awakeFromNib to File's Owner, and this will happen while you're already in -[MyView awakeFromNib]. If you don't check for this, you get a stack overflow due to unbounded recursion.
Answer: You aren't providing any code, but here are some sanity checks:

Are you specifying the nib name correctly?  In iOS its caps sensitive, but I don't think it is for you.
Check the package, is the nib actually there?  Make sure it is part of the target you are building.
Could also be a frame issue.  Make sure your auto-resizing parameters are set up correctly and that everything is in frame.
Another check you can do is set your IBOutlets to the actual frame of a UIView (or other) that you are interested in.  Then in awakeFromNib, you can make sure their frame exists, or that they exist at all.


Google Speech Recognition API on windows phone

Question: i am trying to use the Google APIS in developing a Windows Phone application, i am specifically interested in the speech recognition API from Google but i want to know if it is available for windows phone developers, if it is, i need more details please
Comment: I searched your tags on google, and the first two responses http://forums.create.msdn.com/forums/p/96999/578944.aspx and http://news.ycombinator.com/item?id=2875352
Answer: The Speech API, i guess you mean the Speech API which is used by google in Android phones is not written in C#. Therefore, the answer to your question is no - currently it's not available.
Have a look at this stackoverflow post, there was already a discussion about good Speech APIs in .NET:
good Speech recognition API
greetings


Testing Hypothesis with different alternatives

Question: I want to test whether $\mu=\mu_0$ where $\mu_0$ is some fixed number.
Consider the following two different testings.
Hypothesis Testing 1: $H_0:\mu=\mu_0,H_1:\mu<\mu_0$
Hypothesis Testing 2: $H_0:\mu=\mu_0,H_1:\mu>\mu_0$
It is possible that testing 1 fails to reject $H_0$ and testing 2 rejects $H_0$. In this situation, I can't compare two testings as they are pear and apple.
Let's suppose you are not allowed to use $H_1:\mu\neq\mu_0$ here.
If I am in this situation, what should I do? Should I declare I can't reject $H_0$? Should I declare $H_0$ false by some probability? Which test should I trust?
Answer: Imagine testing $\mu=0$. You do your calculations and find that $\bar{x}=99$ and your z-statistic (or t-stat) is 123.
I would have serious doubts about hypothesis 1 and very much believe hypothesis 2.
Comment: That's a lot of bad luck if you get that result by chance. But everything always could have just happened by chance. The point of a p-value is to measure how surprising of a result you have if the null hypothesis is true. A very surprising result is evidence against the null hypothesis.
Comment: Sure. However, this could happen by chance. Say you can run experiment once.
Comment: Of course, one tries to do intelligent planning from the start. No guarantee against bad luck, but leads to _surprisingly less_ 'bad luck'.  Anyhow, if $T=123$ really occurred, then I'd 'very much believe' hypothesis 2 (+1).
Answer: Doing it right the first time is best.
First, in practice, this should be an unlikely situation.

Maybe you have re-engineered a pharmaceutical process hoping
that the new process has a higher yield than the current one
with $\mu_0 = 100,$ so you'd take data from runs of the new process,
average them and test $H_0: \mu= 100$ vs. $H_a: \mu > 100.$
Maybe your town has changed the widths of lanes and the
sequencing of traffic lights on its main road hoping that the
average late afternoon travel average travel time on the main
stretch is reduced from the former $\mu_0 = 20$ min. Then
you'd get travel times under the new configuration to test
$H_0: \mu = 20$ vs $H_a: \mu < 20.$
Maybe your old supplier whose product had 200mg of active
ingredient per bottle has gone out of business and you are
checking to see the amount of active ingredient in a former competitive
supplier is the same as for the old supplier. Then you'd
test $H_0: \mu = 200$ vs $H_a: \mu \ne 200,$ based on the average
of $n$ randomly selected bottles from the prospective new supplier.

So ordinarily you would test one of the three kinds of tests
and act according to the results of the test. One hopes you would have done
a 'power and sample size' computation beforehand so you'd take
a large enough sample $n$ in order to have a good chance (say 90%)
of rejecting if there is a meaningful difference from $\mu_0.$
Then you would likely take the result of the one test as sufficiently
good evidence to act upon.
But best-laid plans don't always work out. However, as a direct answer to your question, let's suppose you
have taken data to test $H_0: \mu = 100$ vs. $H_1: \mu < 100$
at the 5% level, and cannot reject.  Here are data simulated in R
that would give such a result.
set.seed(806)
x = rnorm(10, 98, 15)
t.test(x, mu=100, alt="less")

        One Sample t-test

data:  x
t = -0.69053, df = 9, p-value = 0.2536
alternative hypothesis: true mean is less than 100
95 percent confidence interval:
     -Inf 104.6308
sample estimates:
mean of x
 97.20135

The mean of my $n=10$ observations is $\bar X = 97.2,$ which is
below the hypothetical mean $\mu = 100,$ but not enough smaller
to be considered statistically significant. Maybe we put the wrong
assumptions into our power computation so we didn't use a large
enough $n.$  In this case, there's no use testing $H_0: \mu = 100$ vs. $H_1: \mu > 100$ because $\bar X < 100$ could never lead to rejection.
But what do we do if we guessed completely wrong and got data such as those
in the simulation below?
set.seed(806)
x = rnorm(10, 110, 15)
t.test(x, mu=100, alt="less")\

    One Sample t-test

data:  x
t = 2.2703, df = 9, p-value = 0.9753
alternative hypothesis: true mean is less than 100
95 percent confidence interval:
     -Inf 116.6308
sample estimates:
mean of x
 109.2014

Of course, we can't reject in favor of $H_a: \mu < 100$ based
on a sample mean $\bar X = 109.2.$ Then we might be tempted to
try testing $H_0: \mu = 100$ vs. $H_1: \mu > 100.$ [In R, the notation
p.val gives just the P-value of the test, not the full printout.]
t.test(x, mu=100, alt="gr")$p.val
[1] 0.02466914

So we could have rejected a test of $H_0: \mu = 100$ vs. $H_1: \mu > 100$
at the 5% level because the P-value $0.025 < 0.05 = 5\%.$ Doing multiple
tests on the same data is always dangerous. If we try enough different
things, we might accidentally get a rejection on one of our tries--just by chance. (The result would be a 'false discovery'.)
Rejecting at the 2% level isn't a really strong result, but if is really important to resolve the true value of $\mu,$ then we might consider getting fresh data and doing the right test
the second time. Or maybe making a two-sided 95% confidence interval
to get a good guess at the actual value of $\mu$ in order to plan our
course of action.
Answer: The research question is king. The job of the hypothesis test is to answer the research question. The job of the data (and statistics) is to help you perform the hypothesis test.
I think you are somewhat confused about how to set up your hypotheses. Your hypotheses should be formed from your research question and before you even look at your data! In particular, let's consider your statement
"Let's suppose you are not allowed to use $H_1: \mu \neq \mu_0$ here."
There is no such circumstance! You are always allowed to specify any valid alternative hypothesis you like, and this $H_1$ is a valid alternative hypothesis except in the pathological case where $\mu$ can only possibly take the single value $\mu_0$.
If you are struggling to work out which alternative hypothesis to use, it is easiest to write out what you are trying to test in words and then try to put it into algebra. Dave gives some examples of this in his answer, but the question will fall into one of three categories:
(A) You want to see if the mean is above some threshold or not. If the mean is $\leq$ the threshold you don't really care whether it is equal or lower. (Maybe you are seeing if a new, expensive drug is more effective than an existing cheap drug. If it isn't more effective then you don't care whether it is equally or less effective, you won't pursue it further because it is expensive.)
(B) You want to see if the mean is below some threshold or not. If the mean is $\geq$ the threshold you don't really care whether it is equal or higher. This is just the reverse of (A).
(C) You want to see if the mean is different from some value or not. (was Don Bradman a "100-runs-per-innings" batsman?)
All of these are legitimate research questions. A and B translate to one-sided hypothesis tests, C translates to a two sided test. However, we could have formulated research questions which were asking whether the two drugs had the same efficacy as each other (this is important for regulatory reasons in some cases), or whether Don Bradman's batting skill was over 100 runs per over. Those would have led to different alternative hypothesis.
Answer: Yes, it is possible that test 1 fails to reject $H_0$ and testing 2 rejects $H_0$. (Consider for example a t-test with level 1% on $n = 9$ datapoints where $s^2 = 1$, $\overline{X} = \mu_0 + 3$ ).
In such a case, you have to... wonder what is the relevant alternative, and this depends on what you want to test.
Keep in mind that one only rejects the null hypothesis in favor of the alternative. And one can only have a positive conclusion in case of a reject of $H_0$. Not rejecting $H_0$ does not allow you to accpet it.
So in the case you described, you cannot conclude that $\mu < \mu_0$ (since testing 1 didn't reject $H_0$) but you can conclude that $\mu > \mu_0$ (since testing 2 did reject $H_0$). If you just want to know if $\mu = \mu_0$ then use the alternative $\mu \neq \mu_0$.


ZFC vs second-order arithmetic: Help me understand the distinction explicitly!

Question: (From Wikipedia: Second-order arithmetic can also be seen as a weak version of set theory in which every element is either a natural number or a set of natural numbers. Although it is much weaker than Zermelo–Fraenkel set theory, second-order arithmetic can prove essentially all of the results of classical mathematics expressible in its language.)
I know that ZFC proves second-order arithmetic but I would like to understand in exactly what regard second-order arithmetic is "weaker". Is there any forumalted theorem up to this date that only makes sense in ZFC and cannot be forumalted in the language of second-order arithmetic by just associating sets with sets of natural numbers? Or is the distinction only interesting in a proof-theoretic context? (i.e. in principle ZFC allows sets that are not just sets of natural numbers, but all reasonably formulated propositions can always be reformulated in second-order arithmetic) If the latter is true, then what would be an explicit example of a construction that goes further than second-order arithmetic?
Thank you!
(This consideration was inspired by the question whether there is a function of natural numbers in ZFC that has a faster growth rate than all fuctions that can be formulated in the language of second-order arithmetic. I hope that is not a stupid question to ask.)
Comment: Some examples in Stephen Simpson, Subsystems of Second Order Arithmetic (Cambridge UP, 2nd ed 2009) [see page 23].
Comment: Borel determinacy can be proved in ZFC and expressed in second-order arithmetic (at least when restricted to the Baire space). It is not provable in second order arithmetic.
Comment: Note that "second-order arithmetic" is also used to refer to the second-order version of Peano arithmetic, $\mathsf{PA}_2$. This is a theory in second-order logic, in contrast to $\mathsf{Z}_2$ which (despite the name) uses first-order logic. $\mathsf{PA_2}$ is complete and indeed fully categorical, and so e.g. entails ("proves" isn't a great word to use here) lots of things about natural numbers which $\mathsf{ZFC}$ doesn't such as $\mathsf{Con(ZFC)}$.
Comment: @MauroALLEGRANZA Thank you, that is exactly what I was looking for! I see that I grossly overestimated the power of $Z_2$ and, in general, of arithmetic expressions. Please correct me if I am wrong, but by following the trail of references, I think I understand now that for every natural number $n$ and every finite-order arithmetic $Z_n$, we can find statements in $ZFC$ that are neither expressable nor provable in $Z_n$.
Comment: In 1st order PA, we cannot discuss subsets of $\mathbb N$, but only formulas that cut out the desired subsets. In 2nd order arithmetic, we are allowed to directly discuss subsets of $\mathbb N$, but not subsets whose elements are subsets, or to mix, like a set whose elements can be either subsets or natural numbers.  ZFC has no problem  to form any kind of sets.
Answer: Z₂ is all about countable mathematics. For example, In Z₂ we can't even express:
"Every vector space has a basis"
But we can express and prove this:
"Every countable vector space has a basis"
And there are a lot of similar examples.
So, ZFC is stronger than Z₂, because in ZFC, we can talk about arbitrary sets, but in Z₂, we can't.
Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Making menu item active onclick in angularjs

Question: I have side menu bar, where i used ng-repeat to display items in the list.

          Inbox

          {{record.customer_name}}

I want to highlight the item on click.I am beginner could someone guide me on how to achive this effect.thanks in advance.
Answer: Add ngClass like,
ng-class="{selected: $index === selectedIndex}"

Your HTML
{{record.customer_name}}

and your viewDates function should be like
$scope.selectedIndex = null;
$scope.viewDates = function ($index) {
   $scope.selectedIndex = $index;
   //.... your remaining code here
};

Comment: use `active` class instead of `selected` as per OP
Comment: I don't think so, he didn't mention class name (he just said **I want to highlight the item on click**) and you are free to choose class name. So why only `active`?
Answer: you can use ng-class to add styles dynamically according to the conditions.

angular.module("app",[])
.controller("ctrl",function($scope){

$scope.inboxlist = {};
$scope.inboxlist.Result = [{"customer_name":"ss"},{"customer_name":"aa"},{"customer_name":"cc"}]

})
.change-color{
  color : red;
}

          Inbox

                {{record.customer_name}}


Foreign key matching in PostgreSQL

Question: Just curious, if I have this table:
CREATE TABLE "post" (
    "id" SERIAL,
    "revision" INTEGER NOT NULL DEFAULT 0,
    "summary" CHARACTER VARYING NOT NULL,
    "description" TEXT NOT NULL,
    "user_id" INTEGER NOT NULL
        REFERENCES "user" ("id") MATCH FULL
            ON UPDATE CASCADE
            ON DELETE RESTRICT,
    "post_type_id" INTEGER NOT NULL
        REFERENCES "post_type" ("id") MATCH FULL
            ON UPDATE CASCADE
            ON DELETE RESTRICT,
    "ctime" TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    PRIMARY KEY("id", "revision")
);

to store posts, and this table:
CREATE TABLE "post_state" (
    "post_id" INTEGER NOT NULL,
    "assembly_seat_id" INTEGER NOT NULL
        REFERENCES "assembly_seat" ("id") MATCH FULL
            ON UPDATE CASCADE
            ON DELETE RESTRICT,
    PRIMARY KEY("post_id")
);

and I want my post_id field to point to post(id), how do I do it? I have tried with the following phrase:
    "post_id" INTEGER NOT NULL UNIQUE,
        REFERENCES "post" ("id") MATCH SIMPLE
            ON UPDATE RESTRICT
            ON DELETE RESTRICT,

but I am getting this error:

ERROR:  there is no unique constraint matching given keys for referenced table "post"

The values of post_state(asembly_seat_id) do not change in this case.
Comment: You can only create a foreign key that references a single row in the other table. Since `post_id` is not unique (only the post_id/revision combination is unique), you can't reference it.
Comment: @ErwinBrandstetter I didn't say anything about single columns in the foreign key, just that it needs to reference a _single row_ (which is exactly what you changed it to do :) ). There are (as far as I know) basically two ways of making it reference a unique row, either make it reference the composite primary key or add a unique index to the column (post.id) he was trying to reference. Adding unique breaks the primary key in post and the foreign key change breaks what I was reading that he was attempting to do, hang a post_state on a post, not a specific revision of a post.
Comment: OH, thanks for the reply, silly me *facepalm*
Comment: @JoachimIsaksson: You may be interested in my answer that contradicts your comment in parts.
Comment: @ErwinBrandstetter yea, re-modeled the tables already :) still thanks for the answer tho
Comment: @JoachimIsaksson: Oh, you are absolutely right. I misread your "single row" as "single column". Will fix my incorrect quote immediately. My apologies.
Comment: @ErwinBrandstetter np, I realized you misread, just wanted to set things straight :)
Answer: A foreign key constraint can span multiple columns. You could just add the column revision to the table post_state.
CREATE TEMP TABLE post (
  post_id serial NOT NULL
 ,revision integer NOT NULL DEFAULT 0
 ,summary text NOT NULL
 ,description text NOT NULL
 ,user_id integer NOT NULL
    REFERENCES user (id) MATCH FULL ON UPDATE CASCADE ON DELETE RESTRICT
 ,post_type_id integer NOT NULL
    REFERENCES post_type (id) MATCH FULL ON UPDATE CASCADE ON DELETE RESTRICT
 ,ctime timestamptz DEFAULT NOW()
 ,PRIMARY KEY(post_id, revision)
);

CREATE TEMP TABLE post_state (
  post_id integer NOT NULL
 ,revision integer NOT NULL
 ,assembly_seat_id integer NOT NULL
    REFERENCES assembly_seat (id) MATCH FULL ON UPDATE CASCADE ON DELETE RESTRICT
 ,PRIMARY KEY(post_id, revision)
 ,FOREIGN KEY (post_id, revision) REFERENCES post (post_id, revision)
);
Read the manual about foreign key constraints.
I am using the name post_id for the primary key column of table post. Don't use id as column name. If you join a bunch of tables you end up with a bunch of columns all names id. Regrettably, some half-wit ORMs are in the habit of doing that.
Alternatively, it might be better design to have unique post_id in table post and add a table post_revision with a n:1 relation to post.
Comment: Excellent answer. SQL is easy: *once you master the syntax, everything reduces to a data modelling problem*
Comment: @Erwin yea, I actually re-designed the model and have another post_revision table as you mentioned :P

Foreign key matching in PostgreSQL


Blogs view for users

Question: I have a drupal page with the blog module. Every user has his own Blog, reachable by site.name/en/blogs/user.name but on the blog entry i have added an new field where i can list all Authors. I need now a view which reads this information out of this and show all blog entries of this Author in his blog. Because now, there is the entry only on the blog of his owner. thanks (drupal 7)
Answer: I have a solution. Install the Module Entity Reference, then create an multiple field wich is linked to the user Profile, at least you have to add a view to blogs/% and there you have to add an context filter wich filters to the field which refers to the Username.

Blogs view for users


FOO.tab.cpp file in folder FOO part of a larger project. Is there special significance of *.tab.cpp?

Question: This might be difficult to answer. I am trying to understand some codebase and in one of the project folders named FOO there is a main.cpp file plus other .hpp and .cpp files. These filenames are made descriptive using underscores such as Hi_there_file.cpp etc.
There are two files Foo.tab.hpp and Foo.tab.cpp
Is *.tab.cpp an indication of something or just a poor try at making the file name descriptive?
Comment: No significance really, any name(symbol) starting with `foo` is hardly descriptive. This seems to be outcome of overwork or drinking at work.
Answer: Turns out, that file is generated by a perl script so they put a tab.cpp at the end. maybe even delete this question. Very very specific to what i'm working with


dmarc getting fail in Authentication result

Question: I am having Postfix server configured for domain. From last few days my mails are marking as spam in gmail. I have already configured DKIM,SPF and DMARC for this domain. I have checked mail source and getting
"Authentication-Results: mydomain; dmarc=fail header.from=mydomain"
I have checked all the support docs but didn`t find anything.
Comment: DMARC failure should not affect your spam score. The mail might be classified as SPAM due to other reasons.
Answer: Could you provide full sample headers or run a classification test with a third party?
Often, the TXT records aren't correctly created with the proper name style or have a syntax error causing the mail server parser to fail. Since DMARC fails the issue can be in either SPF or DKIM. In relaxed mode, the [SPF]-authenticated domain and RFC5322.From domain must have the same Organizational Domain. In strict mode, only an exact DNS domain match is considered to produce Identifier Alignment.
Generally speaking, its really hard to help without proper details. Kindly always provide DNS and configuration samples.


Rails object saving to database despite validation error

Question: I have an item model and a user_item model.  I have a form for users to create an item.  This form requires a picture but the picture should be used to create a user_item in the user_item database.  The item is saving to the database even though there are errors with the form.
I have it set up so that item has_many user_items and user_item belongs_to item.
items_controller.rb
  def create
    Item.transaction do

      @item = Item.create(name: item_params[:name],
                                        description: item_params[:description],
                                        tag_list: item_params[:tag_list],
                                        created_by: current_user.id,
                                        status: Item::STATUS[:pending])

      if item_params[:item] == nil
        @item.errors.add(:picture, "is required")
      end

      if @item.errors.empty?
        @user_item = @item.user_items.build(user_id: current_user.id, picture: item_params[:item][:picture])

        if @user_item.save
          flash[:notice] = "Thank you for submitting your item."
          redirect_to items_path
        else
          render :new
          raise ActiveRecord::Rollback, "UserItem create failed"
        end

      else
        render :new
      end
    end
  end

  private
    def item_params
      params.require(:item).permit(:name, :description, :tag_list,
                                                                item: :picture)
    end

new.html.erb
<%= simple_form_for @item, url: items_path, method: :post, html: { class: "create-item-form" } do |item_builder| %>

  <%= item_builder.input :name, required: false, error: false, label: "Item name", input_html: {class: 'form-control'} %>
  <%= item_builder.input :description, as: :text, required: false, error: false, label: "Description of item", input_html: {class: 'form-control'} %>
  <%= item_builder.input :tag_list, required: false, label: "Tags (these will help users find your item)", input_html: {class: 'form-control'} %>
  <%= item_builder.simple_fields_for @item, @item.user_items.build do |user_item_builder| %>
    <%= user_item_builder.input :picture, as: :file, required: false, label: "Picture of you with this item", input_html: {class: 'form-control'} %>
  <% end %>

    <%= item_builder.submit 'Submit new item', class: "btn btn-primary pull-right inherit-width" %>

<% end %>

I try submitting the form without a picture and the form renders correctly with an error message but when I check the db, the item is there.  In user_item.rb I have validates_presence_of :picture.
I tried to omit code that I didn't think important to my question. If I left something out please let me know.
Comment: Make sure that if item_params[:item] == nil couldn't also be coming through as "" instead of nil
Answer: The raise ActiveRecord::Rollback is not invoked when picture is missing.  Change the code to...
 if @item.errors.empty?
   @user_item = @item.user_items.build(user_id: current_user.id, picture: item_params[:item][:picture])

   if @user_item.save
     flash[:notice] = "Thank you for submitting your item."
     redirect_to items_path
    else
      render :new
      raise ActiveRecord::Rollback, "UserItem create failed"
    end

  else
    render :new
    raise ActiveRecord::Rollback, "No picture provided"
  end

Comment: because your form explicity states `url: items_path, method: :post,` it doesn't care that @item is nil.  Rails doesn't insist on an action being defined as long as the view exists.
Comment: Yes, that would work.  If the form is shared between `new` and `edit` methods then you'd have to do it that way. As it currently is, the form is only suitable for `new` (post) actions.  If your requiement is only for `new` then what you have is serviceable although a bit unexpected.
Comment: Thanks it worked!  I am able to do all this without having a `new` action with `@item = Item.new` in this controller.  I thought you needed to when creating a form.  Any idea why I don't need the `new` action?
Comment: Would the alternative be to just have `simple_form_for @item` and leave the rest, then I'd have to define the action?


How to quantify improvements in business process?

Question: I'm not sure how to ask this question, so please forgive if I'm vague. I'm new to DS and don't speak the language yet. :)
Business process A (bpA) assigns accounts to handlers based on existing logic.
Business process B (bpB) uses ML to assign accounts based on better logic, but I'm not sure how much better.
I have a pool of data stretching back a few years, which I take as my baseline. This is entirely based on bpA, the "old" way. I train and run my model to get bpB recommendations. I look at the list of recommendations and ask, "where did bpA do what bpB recommended?" That's my first bucket. Everything else, where we did NOT do what bpB recommended, get tossed into the second bucket. Then I look at the average success rate -- bucket 1 might have an average success rate of 75%, while bucket 2 might have an average success rate of 65%.
The easy answer is to say, "10% improvement". I suspect that this is not the correct answer, though.
Where should I be looking? What should I be reading? Thanks!
Comment: Could you be more specific about what you have done? Have you the capacity to assign the same account to different handlers (i.e. Do you have paired data for bpA and bpB)? How do you measure performance after assignment?
Comment: Yes, the account can be assigned to different handlers. The role of the ML "engine" is to determine which handler is likely to have greatest success with a given account. Imagine this is a large ticketing system -- which employee is likely to resolve the customer's needs most quickly / efficiently / profitably? We measure performance based on "what percent of request was met?". It's easy to evaluate performance for each account in our business, I just don't know how to quantify the optimization accurately.
Comment: @Duncan Please consider [accepting an answer](https://stackoverflow.com/help/someone-answers). If you find [no answer satisfactory](https://stackoverflow.com/help/no-one-answers), please consider editing your question(s) to provide more information. If you want to motivate answerers, please consider [starting a bounty](https://meta.stackexchange.com/questions/16065/). Accepting an answer shows your appreciation, rewards the author, provides incentive to others and informs everyone that your issue is resolved. You can always change your mind and accept a different answer later on.
Answer:
I then compare performance rates between "bpA did what bpB recommended" and the inverse. I see a difference in performance between the two sets, but I am not sure that the number I see is the number I should be reporting.

If you see a difference in performance you need to establish if it is statistically significant.

Have you measured the accuracy of your model?
Can you explain how you measure performance?

It would be helpful if you provided some Minimal, Complete, and Verifiable example.
Comment: How we measure performance: we use a percentage. Given the properties of an account, one handler might eventually score 78% and another might eventually score 85%, so we want to send the account to the handler expected to score highest.
Comment: @Duncan I was not asking for the format of your results (percentages) but for your definition of performance (e.g. ROI?) and methodology. Your results are represented in percentages of what exactly?


ShapeRenderer doesn't render when using Skins

Question: My shapes drawn by shape renderer does not show when I use skins. The shape is drawn inside the actor using an instance of ShapeRenderer. I think this is caused by the skin because I tried adding an empty table and the shapes show, but if I add an instance of a skin the shapes does not show.
This code is from the libgdx tests in github:
Skin skin = new Skin(Gdx.files.internal("data/uiskin.json"));

Label nameLabel = new Label("Name:", skin);

Table t1 = new Table();
t1.setFillParent(true);
t1.add(nameLabel);
stage.addActor(t1);

Answer: you need to .end() the SpriteBatch befor using the ShapeRender.begin() after the ShapeRender.end() you need to call SpriteBatch.begin() in your actor. Else you do have 2 concurenting batches.
actor.draw(SpriteBatch batch, float delta){
   batch.end();
   ShapeRender.begin(Some Typee);//start it with your shapetype
   //drawing stuff with the shaperender
   ShapeRender.end();//dont forget to end it
   batch.begin(); //need to be started again for the next actors to be dawn
}

An empty table shouldnt be a problem.


Is there any difference between these two note values?

Question: I have never understood if these two note values are supposed to be played in the same way:

Mathematically, I can understand that they are the same, since both of them have 6 notes that are being played in 1 beat, but they are symbolized different.
Usually, the way I have seen the sixteenth triplets is like this:

(a line connecting the two groups).
Answer: The difference between a sextuplet and two triplets is that the two triplets are clearly substructured into two units.  The sextuplet in contrast may either be substructured into three groups of two notes, or it may not be substructured at all.
If you have one ascending run (for example) written as sextuplets, chances are that the composer intends you to not make the fourth note stand out in any manner.
Comment: I think when there is a difference, you have nailed precisely what it is... but there are different conventions that different composers/publishers use and it is quite possible that the composer does NOT intend any difference between the two figures.  Matters of phrasing such as this can be notated as much as possible with similar grouping techniques but technically speaking, the barring of notes is in no way required to influence their phrasing patterns.
Comment: So, the difference is that in the triplets that the 1st and the 4th note stands out, whereas on the sextuplet only the first one does?
Comment: That's pretty much right. Although it might also suggest phrasing of notes, as well as actual accents. And, if accents are supposed to be obvious, it would also make sense to use accent markings.
Comment: Exactly. As @DarrenRinger says, different beamings may *suggest* different accents or phrasing, but to explicitly show these, you should use accent marks and phrasing slurs.
Comment: Except that there are times when accent marks (which imply dynamic accents) and slurs (which tend to imply that the last note under the slur is detached from the notes that follow it) aren't entirely appropriate. Indeed, there are instruments for which dynamic accents aren't really possible, e.g., harpsichord and organ. On instruments such as these, tuplets are usually picked out by agogic accents, i.e., slightly dwelling on the first note of the group. In such cases, beaming _is_ the proper way of going about the notation.
Answer: You are right. They have exactly the same rhythmic values. It would make more sense to use the sextuplets unless:

the music obviously accents two groups of three notes per beat.
the music often intersperses quavers (8th) notes with groups of triplet semiquavers (16th).

In either case where you use triplet semiquavers, I would group pairs of them with a single beam, as shown in your last example. Unless, of course, you are in a time signature which has a longer beat, such as compound time or 2/2, in which case you could group 3 and 4 groups of triplet semiquavers with single beams, respectively.
Answer: It's like the difference between 6/8 and 3/4, the first being subdivided into two units, the second in 3. However, in many cases there is only one accent on the first note of a sextuplet. Anyway, when written as two triplets the accents are clearly on the first and (possibly a bit weaker) on the fourth note. This little article describes the different rhythmic interpretations of the sextuplet.
Answer: The sextuplet can also be six in the time of three, six in the time of four and Six in the time of five. It all depends on the specifics of the piece and how the rhythms work. So yes very much different than the regular three in the time of two.


How does the following piece of music give off that ominous feeling

Question:

I'm curious as to how this piece of music gives this feeling of dread. It is very ominous and heavy. This is odd because it played without any distortion. I'm curious as to how the effect of heavy guitars can be gotten without down tuning significantly or adding distortion
Comment: At core there's a good, analytical question here regarding how this music achieves its effect. But as currently written, it runs into the problems already outlined in the comments, plus requiring transcription. I am voting to close, but would also vote to reopen after a solid revision. Please consider reworking the question to better fit site guidelines.
Comment: I'm sorry but the conveying of emotions or feelings is basically what music is all about. Asking how a certain emotion is evoked in a piece of music should be exactly what a site on music should allow questions on
Comment: I'm voting to close this question because it asks to identify effects or techniques, and talks in very subjective ways about a "feeling." (Even on musicfans, some more concrete description might be needed to get a useful answer.)
Comment: @NeilMeyer Whether a certain piece of music evokes a particular emotion is a matter of opinion.
Comment: Perfectly fine question closed?!? IMO the first example has a feel that could be called dread, but not the second. The first achieves this through the combination of: minor key, accented dissonance, slow tempo, and I feel most importantly the sustained bass notes which create a sense of _anticipation_. Perhaps you could say minor key dissonance evoking 'fear' with slow and unchanging evoking 'suspense' provides: fear + suspense = dread.
Comment: You have a lot more experience and reputation here than I, so I'd certainly defer to your input on meta. But I am suggesting that any attempt to give a musical explanation for a certain sound might need a much clearer explanation of what's being heard.
Comment: I suspect that you're looking for a music-theory analysis (it has a bit to do with "open," no-3rd, chords, but also with the drop D and other expressive choices like tempo and of course a background wind sound effect). But as it stands, the question, talking about "heavy guitars," doesn't make that clear, and sounds like it's looking for an answer about effects or recording techniques, which would be totally off-topic. And no, I don't get "ominous" or "dread," I get "badass."
Comment: I'm not prepared (and probably not qualified) to answer with a thorough theoretical analysis, but that minor 9th (or is it an augmented octave?) in the third bar helps.  (cf. Ron Grainer's "Doctor Who" theme).
Answer: What this does is

Play at a low register
Switch between perfect 5th and augmented fifths of the chord (there is not 3rd)
It uses leaps
It goes upward
It rhythmically anticipates the 1st beat

At least if you just cared about the intro
From here, it gets more subjective, but low registers + dissonance is a pretty easy way to make something sound spooky. The rest adds interest to a degree, but also puts the listener into an uneasy state using leaps and rhythmic anticipation.
Comment: Augmented fifths? Nah, those are pretty clearly just minor sixths that have been notated wrong in the video.
Comment: It could be minor sixths, but it doesn't really imply the VI or iv chord imho (assuming minor tonality)