Q: Cannot resolve method 'setText(java.lang.String am trying to add a library called smooth check box while I trying to cast it it showed me an error Cannot resolve method 'setText(java.lang.String '
this is my Class
............................................................................
package abtech.waiteriano.com.retrievingcontactsexample;

import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import cn.refactor.library.SmoothCheckBox;

/**
 * Created by Trinity Tuts on 10-01-2015.
 */
public class SelectUserAdapter extends BaseAdapter {

    public List<SelectUser> _data;
    private ArrayList<SelectUser> arraylist;
    Context _c;
    ViewHolder v;

    public SelectUserAdapter(List<SelectUser> selectUsers, Context context) {
        _data = selectUsers;
        _c = context;
        this.arraylist = new ArrayList<SelectUser>();
        this.arraylist.addAll(_data);
    }

    @Override
    public int getCount() {
        return _data.size();
    }

    @Override
    public Object getItem(int i) {
        return _data.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    @Override
    public View getView(int i, View convertView, ViewGroup viewGroup) {
        View view = convertView;
        if (view == null) {
            LayoutInflater li = (LayoutInflater) _c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = li.inflate(R.layout.contact_list_item, null);
            Log.e("Inside", "here--------------------------- In view1");
        } else {
            view = convertView;
            Log.e("Inside", "here--------------------------- In view2");
        }

        v = new ViewHolder();

        v.check = (SmoothCheckBox) view.findViewById(R.id.contactsCB);

        final SelectUser data = (SelectUser) _data.get(i);
        v.check.setText(data.getName());
        v.check.setChecked(data.getCheckedBox());;

        Log.e("Image Thumb", "--------------" + data.getThumb());

        /*// Set check box listener android
        v.check.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CheckBox checkBox = (CheckBox) view;
                if (checkBox.isChecked()) {
                    data.setCheckedBox(true);
                  } else {
                    data.setCheckedBox(false);
                }
            }
        });*/

        view.setTag(data);
        return view;
    }

    // Filter Class
    public void filter(String charText) {
        charText = charText.toLowerCase(Locale.getDefault());
        _data.clear();
        if (charText.length() == 0) {
            _data.addAll(arraylist);
        } else {
            for (SelectUser wp : arraylist) {
                if (wp.getName().toLowerCase(Locale.getDefault())
                        .contains(charText)) {
                    _data.add(wp);
                }
            }
        }
        notifyDataSetChanged();
    }
    static class ViewHolder {
        SmoothCheckBox check;
    }
}

and the error in this line
v.check.setText(data.getName());

android Monitor Error
Information:Gradle tasks [:app:assembleDebug]
E:\AndroidWorkSpace\RetrievingContactsExample\app\src\main\java\abtech\waiteriano\com\retrievingcontactsexample\SelectUserAdapter.java
Error:(69, 16) error: cannot find symbol method setText(String)
Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.
Information:BUILD FAILED
Information:Total time: 1.206 secs
Information:2 errors
Information:0 warnings
Information:See complete output in console

............................................................................
I don't know how to solve this error it's ma pleasure if any could help me
sorry of any thing is not clear I hope this gonna be understandable
............................................................................

A: I assume you mean this SmoothCheckBox on github.
Looking at the source code, one finds no setText(String)-method. If I understand the readme correctly, those check boxes are designed to have a selected and unselected color, but no text.


Q: Does git create new files during merge or overwrite existing ones I have a script test.sh
#!/bin/bash
echo start old file
sleep 20
echo end old file

in the repository which I do execute, and in the mean time I git merge other-branch changes like
#!/bin/bash
echo start new file
sleep 20
echo end new file

into the current branch.
It seems that git on Unix (?) does not directly overwrite the existing file node (?) and does instead rm test.sh and creates the new file.
In that way its guaranteed that the script execution will always read the initial file test.sh and terminate with echo end old file.
Note: On my system (Ubuntu 20.04), while executing the script and directy overtwriting the content in an editor, results in executing the new code, which is bad...
Is that correct and is it also correct on Windows with git-for-windows?

A: I can't answer regarding Windows, but on Ubuntu 18.04 I can confirm that a git checkout or git merge will delete and recreate a changed file, rather than editing it in place.  This can be seen in strace output, for example:
unlink("test.sh")                       = 0

followed later by
openat(AT_FDCWD, "test.sh", O_WRONLY|O_CREAT|O_EXCL, 0666) = 4

It can also be seen if you create a hard link to the file before the git command and then look again afterwards, you will see that you have two different inodes, with different contents.  This is to be expected following deletion and recreation, whereas an in-place edit would have preserved the hard linking.
$ ls -l test.sh
-rw-r--r-- 1 myuser mygroup 59 Jun  5 17:04 test.sh

$ ln test.sh test.sh.bak

$ ls -li test.sh*
262203 -rw-r--r-- 2 myuser mygroup 59 Jun  5 17:04 test.sh
262203 -rw-r--r-- 2 myuser mygroup 59 Jun  5 17:04 test.sh.bak

$ git merge mybranch
Updating 009b964..d57f33a
Fast-forward
 test.sh | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

$ ls -li test.sh*
262219 -rw-r--r-- 1 myuser mygroup 70 Jun  5 17:05 test.sh
262203 -rw-r--r-- 1 myuser mygroup 59 Jun  5 17:04 test.sh.bak

You mentioned in a comment attached to the question that it is related to Overwrite executing bash script files.  Although it would seem not to be the best idea to run a git command affecting a script which is currently still being executed, in fact the delete and recreate behaviour should mean that the existing execution will be unaffected.  Even if the bash interpreter has not yet read the whole file into memory, it will have an open filehandle on the existing inode and can continue to access its contents even though that inode is no longer accessible via the filename that it had.  See for example What happens to an open file handle on Linux if the pointed file gets moved or deleted

A: On Windows with git-for-windows I see the same behavior:
$ mklink /H test.sh.bak
$ fsutil hardlink list test.sh.bak
test.sh.bak
test.sh
$ git merge test
$ fsutil hardlink list test.sh.bak
test.sh.bak

Meaning the hard link did not get preserved, meanin a new file has been created.


Q: footer sum data canot sum all data in serverside datatables i have a model like here
https://pastebin.com/HLNQZgkg
public function data_json_judulbuku() {
    error_reporting(-1);
    if( isset($_GET['id']) ){
        $id = $_GET['id'];
    }else{
        $id = '';
    }

and javascript to access datatable
https://pastebin.com/f2NrFbBr
i canot sum all data in datatables, the sum just page listed
result footer sum
total value must 135 and curent page 15 but on display total 15 and curent page 15


Q: varargs parameter list created at runtime public static void method(Set<?>... sets){}

Depending on program flow, above method is called with two sets, or with three sets, or more. (Not known at compile time).
Is there a way to constructing the argument list "on the fly"?
sets is of type Set< ?>[ ]
Following was not fruitful:
Set<Set<Integer>> varargs = new HashSet<Set<Integer>>();

(method recognizes varargs just as one set -> no solution)
Set<Integer>[] varargs = new HashSet<Integer>[2];

returns
"Cannot create generic array of HashSet<Integer>"

I would like to construct an array of arguments, while array size and content is filled at runtime.

A:  Set<Integer>[] varargs = new HashSet[2];
 varargs[0] = new HashSet<Integer>() ;

A: I believe array of Set should be defined like this:
Set<Integer>[] varargs = new Set[2];
varargs[0] = new HashSet<Integer>();
varargs[1] = new HashSet<Integer>();


Q: cmdline of vim on mac terminal or iTerm2 disappear very slow I type : and then type esc key to exit command mod, the cmdline disappear very slow, about 1s-2s, which actually you are in normal already.

A: vim is waiting a short time to allow for the possibility that the esc key might begin a special key (such as cursor-left or F1).
You can alter this behavior altering these settings: ttimeout, timeoutlen
and ttimeoutlen.
The timeoutlen mode is set by default to 1 second (1000 milliseconds).  If you set that to a shorter time (0.1 seconds is fast), it will help.
Some suggest (as in vim's documentation) reducing the timeout, e.g.,
set ttimeout set ttimeoutlen=100

Related discussion:

*

*Vim Command Line Escape Timeout

*Eliminating delays on ESC in vim and zsh


Q: Getting this error when I use IBM Watson Tone Analyzer API. How can I resolve this? requests.exceptions.ConnectionError:
    HTTPSConnectionPool(host='api.eu-gb.tone-analyzer.watson.cloud.ibm.com', port=443):
    Max retries exceeded with url:
        /instances/76db955a-ebbb-46c9-a9ca-121542253a0c/v3/tone?version=2017-09-21&sentences=true
    (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x05533928>:
    Failed to establish a new connection: [Errno 11001] getaddrinfo failed'))`

The output console shows a part of the output I am getting while printing at runtime and then this max retries exceeded error message pops up. Please revert back as soon as possible.


Q: Firebase authentication phone number for android: SMS template in different languages I am using sms Firebase authentication on the android application. However, the SMS I am receiving is weird: Part of it is sometimes English and part of it is Arabic and the rest of the SMS I can't make out actually.

How to make the SMS's language received only Arabic without the other characters?

A: Check whether your phone language and Firebase console are same. Otherwise this can happen. Firebase rechecks the locale of the phone that's causing the issue.


Q: Create Pivot Table and get Count in Pandas Dataframe I have my dataframe -
import pandas as pd
data = [['2233', 'A', 'FY21'], ['441', 'C', 'FY20'], ['6676', 'A', 'FY19'], ['033', 'C', 'FY16'],
       ['12', 'A', 'FY18'], ['91', 'B', 'FY15'], ['6676', 'C', 'FY10'], ['441', 'C', 'FY17'],
       ['12', 'A', 'FY14'], ['441', 'C', 'FY12']]
df = pd.DataFrame(data, columns = ('emp_id', 'category', 'year'))
df

emp_id   category   year
0   2233    A       FY21
1   441     C       FY20
2   6676    A       FY19
3   033     C       FY16
4   12      A       FY18
5   91      B       FY15
6   6676    C       FY10
7   441     C       FY17
8   12      A       FY14
9   441     C       FY12

So basically I want the categories should be created as individual column i.e A, B, & C and each column should contain the counts of them.
What I want as my output -
emp_id    A   B   C
0   2233  1
1   441           3
2   6676  1
3   033           1
4   12    2
5   91        1
6   6676          1

What I was trying -
df['count'] = df.groupby(['emp_id'])['category'].transform('count')
df.drop_duplicates('emp_id', inplace = True)
df
emp_id  category year   count
0   2233    A    FY21   1
1   441     C    FY20   3
2   6676    A    FY19   2
3   033     C    FY16   1
4   12      A    FY18   2
5   91      B    FY15   1

please help me to get my desired output in python.

A: Use pd.crosstab:
df1 = pd.crosstab(df['emp_id'], df['category']).rename_axis(
    columns=None).reset_index()

OUTPUT:
  emp_id  A  B  C
0    033  0  0  1
1     12  2  0  0
2   2233  1  0  0
3    441  0  0  3
4   6676  1  0  1
5     91  0  1  0

NOTE:
If you don't need 0 in the output you can use:
df = pd.crosstab(df['emp_id'],  df['category']).rename_axis(
    columns=None).reset_index().replace(0, '')

OUTPUT:
  emp_id  A  B  C
0    033        1
1     12  2
2   2233  1
3    441        3
4   6676  1     1
5     91     1

Updated Answer:
df = (
    df.reset_index()
    .pivot_table(
        index=['emp_id', df.groupby('emp_id')['year'].transform(', '.join)],
        columns='category',
        values='index',
        aggfunc='count',
        fill_value=0)
    .rename_axis(columns=None)
    .reset_index()
)

OUTPUT:
  emp_id              year  A  B  C
0    033              FY16  0  0  1
1     12        FY18, FY14  2  0  0
2   2233              FY21  1  0  0
3    441  FY20, FY17, FY12  0  0  3
4   6676        FY19, FY10  1  0  1
5     91              FY15  0  1  0

A: You can also use pivot table:
pv = pd.pivot_table(df, index='emp_id', columns='category', aggfunc='count')
pv.fillna('', inplace=True)

print(pv)

         year
category    A  B  C
emp_id
033               1
12          2
2233        1
441               3
6676        1     1
91             1


Q: I wonder how to create a proportional table for one categorical variable and one numerical variable (numerical data is proportion)? library(ggplot2)
library(tidyverse)
library(dplyr)
aqi <- read.csv("aqi12_21.csv")
aqi <- select(aqi,State.Name,county.Name,Date,AQI,Category,Defining.Parameter)
aqi <- rename(aqi,State=State.Name,County=county.Name)
aqi <- separate(aqi, Date, c("Year", "Month", "Day"))
AQI_HIGH<-filter(aqi,AQI>100)
average_aqi_state <- AQI_HIGH %>% group_by(State) %>% summarise(average_aqi = mean(AQI))

So I have my average data which looks like:

I don't know how to create a proportional graph (average aqi is shown in percentage) while the state remains categorical variable

A: Suppose this simplified form of data represents your actual data:
dat <- structure(list(State = c("Alabama", "Alaska", "Arizona", "Others"
), average_aqi = c(300, 550, 150, 1000)), class = "data.frame", row.names = c(NA,
-4L))

If I understand your purpose correctly, you want to get the proportion of average_aqi in this way:
dat |> mutate(avaqi_perc = average_aqi/sum(average_aqi))

#    State average_aqi avaqi_perc
#1 Alabama         300      0.150
#2  Alaska         550      0.275
#3 Arizona         150      0.075
#4  Others        1000      0.500


Q: Is there a way to change the browser's address bar without refreshing the page? I'm developing a web app. In it I have a section called categories that every time a user clicks one of the categories an update panel loads the appropriate content.
After the user clicked the category I want to change the browser's address bar url from
www.mysite.com/products

to something like
www.mysite.com/products/{selectedCat}

without refreshing the page.
Is there some kind of JavaScript API I can use to achieve this?

A: I believe directly manipulating the address bar to a completely different url without moving to that url isn't allowed for security reasons, if you are happy with it being
www.mysite.com/products/#{selectedCat}
i.e. an anchor style link within the same page then look into the various history/"back button" scripts that are now present in most javascript libraries.
The mention of update panel leads me to guess you are using asp.net, in that case the asp.net ajax history control is a good place to start

A: To add to what the guys have already said edit the window.location.hash property to match the URL you want in your onclick function.
window.location.hash = 'category-name'; // address bar would become http://example.com/#category-name

A: I don't think this is possible (at least changing to a totally different address), as it would be an unintuitive misuse of the address bar, and could promote phishing attacks.

A: With HTML5 you can modify the url without reloading:
If you want to make a new post in the browser's history (i.e. back button will work)
window.history.pushState('Object', 'Title', '/new-url');

If you just want to change the url without being able to go back
window.history.replaceState('Object', 'Title', '/another-new-url');

The object can be used for ajax navigation:
window.history.pushState({ id: 35 }, 'Viewing item #35', '/item/35');

window.onpopstate = function (e) {
  var id = e.state.id;
  load_item(id);
};

Read more here: http://www.w3.org/TR/html5-author/history.html
A fallback sollution: https://github.com/browserstate/history.js

A: This cannot be done the way you're saying it. The method suggested by somej.net is the closest you can get. It's actually very common practice in the AJAX age. Even Gmail uses this.

A:
"window.location.hash"

as suggested by sanchothefat should be the one and only way of doing it. Because all the places that I have seen this feature, it's all the time after the # in URL.


Q: jquery $.post, to django view method, request.method shows GET, and cannot retrieve parameters I'm trying to figure out how I can send some data to a view in django vis POST, and return some data, depending on the data sent in the request, from the view to the client via an HttpResponse.
When the POST request is sent from the client, the web console prints,
POST http://<myurl>
GET  http://<myurl>/

And the message returned is "get".  In the view method, When I try to access the parameters via response.GET.get("key"), None is returned.
I must be misunderstanding something, anyone know what is going on?
views.py
    from django.http import HttpResponse

    def test(request):

        msg = ""

        if request.method == "POST":
            msg = "post"

        elif request.method == "GET":
            msg = "get"

        return HttpResponse(msg)

javascrip/jquery
  function _req(url, params, callback ) {

    function onResponse( data ) {
      console.log( data );
      callback(data);
    };

    $.post(
      url,
      JSON.stringify(params),
      onResponse,
      "text");
   };

A: The two URLs that are printed show exactly what is happening. You are posting to a URL without a final slash, but you have the default APPEND_SLASH setting, so Django is redirecting to the URL with a final slash appended. Redirects are always GETs.
Make sure you post to the URL with the slash.


Q: No trusted certificate found using CAS and JBoss I'm trying to authenticate through CAS+LDAP in a Jboss app. The config is like this:

*

*Server 1: Jboss 6.10. Cas is deployed here.

*Server 1: LDAP using OpenDS.

*Server 2: Jboss whith the app to login into.

I've configured both jboss to use SSL correctly and the CAS succesfyuly reads and authenticates against the LDAP.
When I get to (through https) server1:8443/app/ i'm redirected to server2:8443/cas/ and the login screen is displayed. I login with a valid user on the LDAP but when the flow gets back to the app i'm always getting this:
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: No trusted certificate found

I've read its a certificate problem and, as it is a dev enviroment i'm trying the self-signed certificate. So I did this:

*

*Gen the self signed in Server1 with
keytool -genkey -alias jbosskey -keypass password -keyalg RSA -keystore server.keystore

*Get the certificate of the Server1 with:
keytool -export -alias jbosskey -keypass password -file server.crt -keystore server.keystore

*Copy the server.crt to Server2 and import it to the truststore of Jboss.
keytool -import -alias server1 -file server.crt -keystore C:\dev\jboss-6.1.0.Final\server.truststore

*This gets me the eception. So I also imported to the cacerts of the JVM.
keytool -import -alias server1 -file server.crt -keystore C:\dev\jdk160_18\jre\lib\security\cacerts

*Not working, so I tried to add the certificate to the keystore of the Jboss at Server2.
keytool -import -alias server1 -file server.crt -keystore C:\dev\jboss-6.1.0.Final\keystore.jks
The Server1 Jboss server.xml
  <Connector protocol="HTTP/1.1" SSLEnabled="true"
       port="${jboss.web.https.port}" address="${jboss.bind.address}"
       scheme="https" secure="true" clientAuth="false"
       keystoreFile="${jboss.server.home.dir}/conf/server.keystore"
       keystorePass="password" sslProtocol = "TLS"
/>

The Server2 Jboss server.xml
<Connector protocol="HTTP/1.1" SSLEnabled="true"
            port="8443" address="${jboss.bind.address}"
            scheme="https" secure="true" clientAuth="false"
            keystoreFile="C:\dev\jboss-6.1.0.Final\keystore.jks"
            keystorePass="password"
            truststoreFile="C:\dev\jboss-6.1.0.Final\server.truststore"
            truststorePass="password"
            sslProtocol = "TLS" />

I've been stuck on this for a couple of days and don't know if i'm missing something. Did I missed something important with the keytool?
Thanks in advance.


Q: How to get SetBinding method I need to do something like this:
http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/982e2fcf-780f-4f1c-9730-cedcd4e24320/
I decided to follow the best way as John Smith advised.
I tried to set binding in xaml, it didn't work (target was always null).
I decide to set binding manually in code (for debugging purpose), so I need to execute "SetBinding" method of the DateRange object.
This method doesn't exists in object of type DateRange.
Any ideas?
<TextBox Grid.Row="1"
         Grid.Column="1"
         Name="Xml_Name"
         >
    <TextBox.Text>
        <Binding XPath="@name" UpdateSourceTrigger="PropertyChanged" >
            <Binding.ValidationRules>
                <local:UniqueValidationRule x:Name="uniqueDatasourcesRule001" >
                    <local:UniqueValidationRule.UniqueCollection>
                        <local:UniqueDependencyObject uu="{Binding  ElementName=Xml_Name, Path=Name, UpdateSourceTrigger=PropertyChanged}" />
                    </local:UniqueValidationRule.UniqueCollection>
                </local:UniqueValidationRule>
            </Binding.ValidationRules>
        </Binding>
    </TextBox.Text>
</TextBox>

public class UniqueDependencyObject : DependencyObject
{
    public static readonly DependencyProperty uu11Property =
        DependencyProperty.Register("uu", typeof(string), typeof(UniqueDependencyObject));

    public string uu
    {
        set {
            SetValue(uu11Property, value); }
        get {
            return (string)GetValue(uu11Property); }
    }

}

public class UniqueValidationRule : ValidationRule
{
    public UniqueDependencyObject UniqueCollection
    {
        get;
        set;
    }

    public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
    {
        // I set breakpoint to this line and check UniqueCollection.uu - it is always null
        ////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////
        return new ValidationResult(true, null);
    }
}

//  And binding in code:
                Binding binding = new Binding();
            binding.ElementName = "Xml_Name";
            binding.Path = new System.Windows.PropertyPath("Name");
            binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;

            UniqueValidationRule uVal = new UniqueValidationRule();
            uVal.UniqueCollection = new UniqueDependencyObject();

            BindingOperations.SetBinding(uVal.UniqueCollection, UniqueDependencyObject.uu11Property, binding);

A: I haven't read all the details of the forum post you're referring to, but i'm sure you need to know a few things about data binding before you can start using it.

*

*The target of a data binding is a dependency
property

*A dependency property has to be declared in a class that is derived from DependencyObject (at least when it is not an attached property, but we don't talk about those here)

*The SetBinding method you're looking for is either a static method in BindingOperations, or a method of FrameworkElement.
So when you're going to set up a binding on some property of your DataRange class, it would have to be derived from DependencyObject, and you would set the binding like this:
DataRange dataRange = ...
Binding binding = ...
BindingOperations.SetBinding(dataRange, DataRange.StartProperty, binding);

If DataRange were derived from FrameworkElement, you could write this:
dataRange.SetBinding(DataRange.StartProperty, binding);

Here DataRange.StartProperty is of type DependencyProperty and represents the Start dependency property of class DataRange.
You should at least read the MSDN articles Data Binding Overview, Dependency Properties Overview and Custom Dependency Properties.


Q: How to implement the generalized form of std::same_as (i.e. for more than two type parameters) that is agnostic to parameter order? Background
We know that the concept std::same_as is agnostic to order (in other words, symmetric): std::same_as<T, U> is equivalent to std::same_as<U, T> (related question). In this question, I would like to implement something more general: template <typename ... Types> concept same_are = ... that checks whether types in the pack Types are equal to each other.
My attempt
#include <type_traits>
#include <iostream>
#include <concepts>

template <typename T, typename... Others>
concept same_with_others = (... && std::same_as<T, Others>);

template <typename... Types>
concept are_same = (... && same_with_others<Types, Types...>);

template< class T, class U> requires are_same<T, U>
void foo(T a, U b) {
    std::cout << "Not integral" << std::endl;
}

// Note the order <U, T> is intentional
template< class T, class U> requires (are_same<U, T> && std::integral<T>)
void foo(T a, U b) {
    std::cout << "Integral" << std::endl;
}

int main() {
    foo(1, 2);
    return 0;
}

(My intention here is to enumerate over every possible ordered pair of types in the pack)
Unfortunately, this code would not compile, with the compiler complaining that the call to foo(int, int) is ambiguous. I believe that it considers are_same<U, T> and are_same<T, U> as not equivalent. I would like to know why the code fails how I can fix it (so that the compiler treats them as equivalent)?

A: From cppreference.com Constraint_normalization

The normal form of any other expression E is the atomic constraint whose expression is E and whose parameter mapping is the identity mapping. This includes all fold expressions, even those folding over the && or || operators.

So
template <typename... Types>
concept are_same = (... && same_with_others<Types, Types...>);

is "atomic".
So indeed are_same<U, T> and are_same<T, U> are not equivalent.
I don't see how to implement it :-(

A: The problem is, with this concept:
template <typename T, typename... Others>
concept are_same = (... && std::same_as<T, Others>);

Is that the normalized form of this concept is... exactly that. We can't "unfold" this (there's nothing to do), and the current rules don't normalize through "parts" of a concept.
In other words, what you need for this to work is for your concept to normalize into:
... && (same-as-impl<T, U> && same-as-impl<U, T>)

into:
... && (is_same_v<T, U> && is_same_v<U, T>)

And consider one fold-expression && constraint to subsume another fold-expression constraint && if its underlying constraint subsumes the other's underlying constraint. If we had that rule, that would make your example work.
It may be possible to add this in the future - but the concern around the subsumption rules is that we do not want to require compilers to go all out and implement a full SAT solver to check constraint subsumption. This one doesn't seem like it makes it that much more complicated (we'd really just add the && and || rules through fold-expressions), but I really have no idea.
Note however that even if we had this kind of fold-expression subsumption, are_same<T, U> would still not subsume std::same_as<T, U>. It would only subsume are_same<U, T>. I am not sure if this would even be possible.

A: churill is right .Using std::conjunction_v might be helpful.
   template <typename T,typename... Types>
   concept are_same = std::conjunction_v<std::same_as<T,Types>...>;


Q: How to scalar multiply array Write a method scalarMultiply which takes as input a double[] array, and a double scale, and returns void. The method should modify the input array by multiplying each value in the array by scale.
. Question to consider: When we modify the input array, do we actually modify the value of the
variable
array
?
Here is what i did until now, but i dont know what i did wrong because it still is not working.
public class warm4{

  public static void main(String[] args){
    double[] array1 = {1,2,3,4};
     double scale1 = 3;
    }
 }
   public static void scalarMultiply(double[] array, double scale){
     for( int i=0; i<array.length; i++){
     array[i] = (array[i]) * scale;
     System.out.print(array[i] + " ");
     }
   }
 }

A: You're never calling the scalarMultiply method.

A: You're never calling scalarMultiply and the number of the brackets is incorrect.
public class warm4{

  public static void main(String[] args){
     double[] array1 = {1,2,3,4};
     double scale1 = 3;
     scalarMultiply(array1, scale1);
   }

   public static void scalarMultiply(double[] array, double scale){
       for( int i=0; i<array.length; i++){
       array[i] = (array[i]) * scale;
       System.out.print(array[i] + " ");
     }
   }
 }

A: Your method is OK. But you must call it from your main:
public static void main(String[] args){
    double[] array1 = {1,2,3,4};
    double scale1 = 3;
    scalarMultiply(array1, scale1);
    for (int i = 0; i < array1.length; i++) {
        System.out.println(array1[i]);
    }
}


Q: Animate not queueing correctly I have this working code for moving a heading icon forth and back if you hover over heading
jQuery('h1.heading').hover(
  function(){
    $icon = jQuery('.heading-icon', this);
    if( ! $icon.is(':animated') ){
        $icon.animate({ "margin-left" : "+=7px" }, 200, function(){
          $icon.animate({ "margin-left" : "-=7px" }, 400, function(){
             $icon.css('margin-left','auto');
          } );
        } );
    }
  },
  function(){}
);

However if you hover faster over heading (faster than the animation is completed) it gets buggy and ends up moved away from original location.
I use onComplete functions, I even tried to use ! $('...').is(':animated') as you can see above, did not help, so I thought at least I would reset the position after animation end so then even if it would get buggy it would at least reset to the original position after all animation would end... That worked only partially and still gets buggy and ends up in the wrong position...
So whats wrong?
How come that e.g. shake effect from jQuery UI enques good?
Note: I don't care if the animation runs a few times more, the goal is to make it stay at the right position when (all) the animation(s) end.
Any help ? :)
EDIT
I finally reproduced the problem on JSFiddle - http://jsfiddle.net/yhJst/
 ==> try to hover up and down faster over the headings
EDIT2
It doesn't seem to be happening when there is only one heading ... http://jsfiddle.net/scZcB/3/

A: Here's the problem, in your callback function, you are using animate on the $icon variable. But when you hover an other element, that variable is changed for the new hovered element.
Use $(this) in the callback or the natural queuing :
Natural queuing
jQuery('h1.sc_blogger_title').on('mouseenter', function(){
    $icon = jQuery('.sc_title_bubble_icon', this);
    if( ! $icon.is(':animated') ){
        $icon.animate({ "margin-left" : "+=7px" }, 200).animate({ "margin-left" : "-=7px" }, 400);
    }
});

http://jsfiddle.net/yhJst/1/
$(this)
jQuery('h1.sc_blogger_title').on('mouseenter', function(){
    $icon = jQuery('.sc_title_bubble_icon', this);
    if( ! $icon.is(':animated') ){
        $icon.animate({ "margin-left" : "+=7px" }, 200, function(){
            $(this).animate({ "margin-left" : "-=7px" }, 400);
        });
    }
});

http://jsfiddle.net/yhJst/2/

Or use a local variable.
as you discovered, the current variable is a global one. Just add the keyword var.
jQuery('h1.sc_blogger_title').on('mouseenter', function(){
    var $icon = jQuery('.sc_title_bubble_icon', this);
    if( ! $icon.is(':animated') ){
        $icon.animate({ "margin-left" : "+=7px" }, 200, function(){
            $icon.animate({ "margin-left" : "-=7px" }, 400, function(){
                $icon.css('margin-left','auto');
            } );
        } );
    }
});


Q: Can't append char to a StringBuffer 2-dimensional array Does anybody know why i can't append a char to this StringBuffer array (in my example below) and can somebody please show me how i needs to be done?
public class test {
    public static void main(String args[]){

        StringBuffer[][] templates = new StringBuffer[3][3];

        templates[0][0].append('h');
    }
}

My output to this code is:
output:     Exception in thread "main" java.lang.NullPointerException
            at test.main(test.java:6)

It would help me so much so if you know any solution, please respond to this

A: Below statement will just declare an array but will not initalize its elements :
    StringBuffer[][] templates = new StringBuffer[3][3];

You need to initialize your array elements before trying to append the contents to them. Not doing so will result in NullPointerException
Add this initialization
    templates[0][0] = new StringBuffer();

and then append
    templates[0][0].append('h');

A: You need to initialize the buffers before you append something
templates[0][0] = new StringBuffer();

A: Others correctly pointed out the correct answer, but what happens when you try to do something like templates[1][2].append('h');?
What you really need is something like this:
public class Test {          //<---Classes should be capitalized.

    public static final int ARRAY_SIZE = 3;  //Constants are your friend.

    //Have a method for init of the double array
    public static StringBuffer[][] initArray() {
       StringBuffer[][] array = new StringBuffer[ARRAY_SIZE][ARRAY_SIZE];
       for(int i = 0;i<ARRAY_SIZE;i++) {
            for(int j=0;j<ARRAY_SIZE;j++) array[i][j] = new StringBuffer();
        }
        return array;
    }

    public static void main(String args[]){

       StringBuffer[][] templates = initArray();

        templates[0][0].append('h');
        //You are now free to conquer the world with your StringBuffer Matrix.
    }
}

Using the constants are important, as is is reasonable to expect your matrix size to change.  By using constants, you can change it in only one location rather then scattered throughout your program.


Q: How do i download images from Airtable and upload to Wordpress using Airtable and Wordpress APIs preferably in javascript Im looking to make an automation script that takes images from Airtable and downloads and upload them to Wordpress upload folder. these images should backfill on all the post types with the empty image fields i have created for them. for example say i made a profile for myself James Major and there is an image field, it should take that pic and fill in it. i don't have a clue where to begin as I'm new to coding and i am learning on the fly. thank you for your help
enter code here

var base = new Airtable({ apiKey: 'API KEY HERE' }).base('Base key here');

const table = base('USERS');

const getRecords = async() => {
    const records = await table.select({
        maxRecords: 0,
        view: "Website Export"
    }).firstPage();
    console.log(records);
};
getRecords();
const getRecordById = async(id) => {
    try {
        const record = await table.find(id);
        console.log(record)
    } catch (err) {
        console.error(err);
    }
};

// const createRecord
getRecordById(); ```


Q: Generating sharing message and shortened URL to Twitter I am using a Twitter ghetto sharing on a very simple Python based mobile site
 return "http://mobile.twitter.com/home?status=" + urllib.quote(link)

I'd like to change the sharing so that Twitter messages gets the page title (I have it) and shortened URL.
Does there exist any general libraries/micro-frameworks for this purposes for Python?

A: I'd recommend implementing a URL-shortener API (ie: bit.ly). Even further, there are API wrappers available for most of these popular services (ie: Python API wrapper for bit.ly - http://code.google.com/p/python-bitly/).


Q: Different font size on Different devices in same size class Hi I am new with the size class. As far I know Apple has given one size class (Compact + Regular) for  Portrait iPhone 4s, 5, 6 and 6+. So How can I give different fonts size in these three different devices By storyboard or Any other way to do that.
Thanks
Happy coding

A: Autolayout and SizeClasses wouldn't target specific devices, so you will have to set the font sizes programatically. You can use check the size of your device using UIScreen.mainScreen().bounds.size.height and set the size of your font accordingly. This solution will clarify you more.

A: As you mentioned in your question you need to give separate font sizes for different devices.
First thing is we cant achieve it on storyboard.
You need to assign different font sizes Manually by using If conditions & checking devices.
For ex:
if ([[UIScreen mainScreen] bounds].size.height == 568) {
    // Assign Font size for iPhone 5
}else if ([[UIScreen mainScreen] bounds].size.height == 667){
    // Assign Font size for iPhone 6
}else if ([[UIScreen mainScreen] bounds].size.height == 736){
    // Assign Font size for iPhone 6+
}else if ([[UIScreen mainScreen] bounds].size.height == 480){
    // Assign Font size for iPhone 4s
}

Note:

*

*You can create a separate Font class & if you did it already than just need to put above validations in that class.


Q: RSStail crashes with segmentation fault 11 I'm trying to monitor an RSS feed using rsstail (https://github.com/flok99/rsstail), by piping the url from rsstail into another program. For some reason, rsstail crashes after a few minutes with Segmentation Fault 11. I have no idea why it would be crashing, and there are no reports online that seem to indicate that rsstail has any issues with segfaults on OSX.
How should I be going about figuring out this segfault? I'm considering debugging rsstail using gcb, but this might be overkill for something which by all rights shouldn't be happening.
If any one has an alternative to rsstail that produces command line output, that would also be appreciated.


Q: automatic count the number of 1-n instance in a mysql table I have two mySql tables in a 1-n relationship. In the first table I need to set a field representing the number of instance of the second table, and keep it updated.
What is the best way to accomplish this? I have to update the counter every time I insert/delete a record in the second table or is there an automatic way to do it?

A: To have it as a field in the first table you need to update the counter every time that you insert/delete a record in the second table.
Alternatively, when you need to retrieve the data, you can just query the second table, joining with the first and filtering on the Id from the first table. If you don't need the data every time that you retrieve a record from the first table and if you are inserting/deleting lots from the second table, then this will be the more efficient route.

A: If the run-time query as suggested by @Najzero is not preferred you might think of creating View with this query and getting data from View
Also if you need to update the field every-time on insert/delete, you can consider creating Trigger on INSERT and DELETE operation.


Q: how can i validate year textbox in javascript? I am using a textbox on my page which is used to enter year in yyyy-yyyy format.
Can you tell how can i validate textbox in this format through javascript??
Thanks in advance...

A: You can match it with a regular expression:
var pattern = /\d{4}-\d{4}/;

A: If you are not using any javascript library (like jQuery, etc), Javascript Regular Expressions could be used for validating the input.


Q: Longest prefix+suffix-combination in set of strings I have a set of strings (less than 30) of length 1 to ~30. I need to find the subset of at least two strings that share the longest possible prefix- + suffix-combination.
For example, let the set be
Foobar
Facar
Faobaron
Gweron
Fzobar

The prefix/suffix F/ar has a combined length of 3 and is shared by Foobar, Facar and Fzobar; the prefix/suffix F/obar has a combined length of 5 and is shared by Foobar and Fzobar. The searched-for prefix/suffix is F/obar.
Note that this is not to be confused with the longest common prefix/suffix, since only two or more strings from the set need to share the same prefix+suffix. Also note that the sum of the lengths of both the prefix and the suffix is what is to be maximized, so both need to be taken into account. The prefix or suffix may be the empty string.
Does anyone know of an efficient method to implement this?

A: How about this:
maxLen := -1;
for I := 0 to Len(A) - 1 do
  if Len(A[I]) > maxLen then // (1)
    for J := 0 to Len(A[I]) do
      for K := 0 to Len(A[I]) - J do
        if J+K > maxLen then // (2)
        begin
          prf := LeftStr(A[I], J);
          suf := RightStr(A[I], K);
          found := False;
          for m := 0 to Len(sufList) - 1 do
            if (sufList[m] = suf) and (prfList[m] = prf) then
            begin
              maxLen := J+K;
              Result := prf+'/'+suf;
              found := True;
              // (3)
              n := 0;
              while n < Len(sufList) do
                if Len(sufList[n])+Len(prfList[n]) <= maxLen then
                begin
                  sufList.Delete(n);
                  prfList.Delete(n);
                end
                else
                  Inc(n);
              // (end of 3)
              Break;
            end;
          if not found then
          begin
            sufList.Add(suf);
            prfList.Add(prf);
          end;
        end;

In this example maxLen keeps sum of lengths of longest found prefix/suffix so far. The most important part of it is the line marked with (2). It bypasses lots of unnecessary string comparisons. In section (3) it eliminates any existing prefix/suffix that is shorter than newly found one (winch is duplicated).


Q: Node.js `Stream` and chunk order Are Node.js streams order preserving up to and including the 'data' events? I believe they are, and this question also seems to suggest at least that the pipe methods are sequential.
I want chunk order to be preserved so that I can call a function that operates on each chunk before the stream ends, i.e., while one part of the stream is being read, I want the buffered data chunk to be processed by a function in the 'data' event.
However, when I run the following code, where I've used Math.random and setTimeout to test specifically if the events happen in order:
fs.createReadStream(filePath, { encoding: 'ascii' })
  .pipe(streamToEntry)
  .on('data', (chunk) => {
    setTimeout(() => {
      console.log(chunk);
    }, Math.random() * 1000)
  });

data chunks can be logged in an out-of-order fashion.
Is this because of setTimeout() or because the 'data' event is not necessarily called sequentially? i.e., should ordered processing only happen in the pipe methods, or can I process the data at the end sequentially?

A: Your data events are guaranteed to be emitted in order. See this answer for some additional details and some snippets from node's source code, which shows that indeed you will get your data events in order.
The problem appears when you add asynchronous code in your data callback (setTimeout is an example of async code). In this situation, your data callbacks are not guaranteed to finish processing in the order they were called.
What you need to do is ensure that by the time your data callback returns, you have fully processed your data. In other words your callback code needs to be sync code.
fs.createReadStream(filePath, { encoding: 'ascii' })
  .pipe(streamToEntry)
  .on('data', (chunk) => {
      // only synchronous code here
      console.log(chunk);
  });

To make the question code work, async/await can be used:
fs.createReadStream(filePath, { encoding: 'ascii' })
  .pipe(streamToEntry)
  .on('data', async (chunk) => {
      // only synchronous code here
      await setTimeout(() => console.log(chunk), Math.random() * 1000);
  });


Q: mod_wsgi problem with MAMP I make mod_wsgi is like following

$./configure
  --with-python=/Library/Frameworks/Python.framework/Versions/2.7/bin/python
  --with-apxs=/usr/local/apache2/bin/apxs
checking Apache version... 2.0.63
configure: creating ./config.status
config.status: creating Makefile
$sudo make $sudo make install

and then I copy file from /usr/local/apache2/modules/mod_wsgi.so to /Applications/MAMP/Library/modules/mod_wsgi.so
And then I add

LoadModule wsgi_module
  modules/mod_wsgi.so

in httpd.conf
I run the apache and I got error.

$ sudo
  /Applications/MAMP/Library/bin/apachectl
  start
Syntax error on line 287 of
  /Applications/MAMP/conf/apache/httpd.conf:
  Cannot load
  /Applications/MAMP/Library/modules/mod_wsgi.so
  into server: cannot create object file
  image or add library

A: Step 1: Make sure your version of MAMP is Version 2 because it includes a Universal Binary installer (32-bit & 64-bit)
Step 2: Modify your Make file and eliminate the other compiler versions, similar to:
CPPFLAGS = -I/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -DNDEBUG
CFLAGS = -Wc,"-arch i386" -Wc,"-arch x86_64" -Wc
LDFLAGS = -arch i386 -arch x86_64 -F/Library/Frameworks -framework Python -u _PyMac_Error
LDLIBS = -ldl  -framework CoreFoundation

Step 3: In httpd.conf: LoadModule wsgi_module modules/mod_wsgi.so


Q: Split an Array and get the Index I've an Array like this,
[
  1,
  1,
  1,
  0,
  0,
  0,
  1,
  1,
  0,
  1,
  1
]

In above array I need to get split on 0 and 1  numbers and also their index. I write the code for getting 0 and 1 in separate array but I want their index also in the Main array, below code is:
for (int i = 0; i < [Array count]; i++) {
       NSString* strV = [Array objectAtIndex:i];
        NSLog(@"ArrayCount:%@",strV);
         if ([strV isEqual:[NSNumber numberWithInt:0]]) {
                [getArray addObject:strV];
                   }
    }

    NSLog(@"getArray:%@",getArray.description);
}

Then, how can I get index of 0, can you please help me. Thank you

A: NSMutableArray *arrayContainZero = [NSMutableArray new];
NSMutableArray *arrayWithZeroIndexes = [NSMutableArray new];
for (NSNumber *numberZero in Array)
{
    if(numberZero.integerValue == 0)
    {
            [arrayContainZero addObject:numberZero];
            [arrayWithZeroIndexes      addObject:@([arrayContainZeroindexOfObject:numberZero])];

    }
}

A:  NSArray *mainArr=@[@1,@1,@1,@0,@0,@0,@1,@1,@0,@1,@1];
    NSMutableArray *tempArr=[[NSMutableArray alloc] init];
    for(int i=0;i<[mainArr count];i++){
        if([[mainArr objectAtIndex:i] isEqualToNumber:[NSNumber numberWithInt:0]]){
            NSMutableArray *arr=[[NSMutableArray alloc] initWithArray:tempArr];
            [tempArr removeAllObjects];
            NSDictionary *dic=[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:0],@"value",[NSNumber numberWithInt:i],@"index",nil];
            [tempArr addObject:dic];
            [tempArr addObjectsFromArray:arr];
        }else if ([[mainArr objectAtIndex:i] isEqualToNumber:[NSNumber numberWithInt:1]]){
            NSDictionary *dic=[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:1],@"value",[NSNumber numberWithInt:i],@"index",nil];
            [tempArr addObject:dic];
        }
    }

    NSLog(@"%@",tempArr.description);


Q: Send data to a shiny R program First of all I'm new to shiny.
I'd like to send a matrix of records to a shiny application so I can populate a control and generate a graph.
Is it possible?

A: The trick is not to have your ui code and server code in two seperate files but to write a function which contains your ui and server code.
Try this:
shinyapp <- function(mat) {
    app <- list(
        ui = bootstrapPage(
             here comes your ui.R),
        server = function(input, output) {
             here comes your server.R
             the argument mat can be used now in server
        }
    )
    runApp(app)
}

This worked for me.


Q: Dependency Inversion Principle: High Level and Low Level module example I was going through the following link to understand what high-level and low-level modules mean in the context of Dependency Inversion Principle.
As per the explanation given there, is the following code snippet a good/appropriate example?
public class HighLevel
{
    private IAbstraction _abstraction;

    public HighLevel(IAbstraction abstraction)
    {
        _abstraction = abstraction;
    }

    public void Act()
    {
        _abstraction.DoSomething();
    }

}

public interface IAbstraction
{
    void DoSomething();
}

public class LowLevel: IAbstraction
{
    public void DoSomething()
    {
        //Do something
    }
}

A: To make a long answer short: yes, this is an example of a Dependency Inversion Principle


Q: How to capture a video (AND audio) in python, from a camera (or webcam) i'm looking for a solution, either in linux or in windows, that allows me to

*

*record video (+audio) from my webcam & microphone, simultaneously.

*save it as a file.AVI (or mpg or whatever)

*display the video on the screen while recording it

Compression is NOT an issue in my case, and i actually prefer to capture RAW and compress it later.
So far i've done it with an ActiveX component in VB which took care of everything, and i'd like to progress with python (the VB solution is unstable, unreliable).
so far i've seen code that captures VIDEO only, or individual frames...
I've looked so far at

*

*OpenCV - couldn't find audio capture there

*PyGame - no simultaneous audio capture (AFAIK)

*VideoCapture - provide only single frames.

*SimpleCV - no audio

*VLC - binding to VideoLAN program into wxPthon - hopefully it will do (still investigating this option)

*kivy - just heard about it, didn't manage to get it working under windows SO FAR.

The question - is there a video & audio capture library for python?
or - what are the other options if any?

A: I would recommend ffmpeg. There is a python wrapper.
http://code.google.com/p/pyffmpeg/

A: Answer: No. There is no single library/solution in python to do video/audio recording simultaneously. You have to implement both separately and merge the audio and video signal in a smart way to end up with a video/audio file.
I got a solution for the problem you present. My code addresses your three issues:

*

*Records video + audio from webcam and microphone simultaneously.

*It saves the final video/audio file as .AVI

*Un-commenting lines 76, 77 and 78 will make the video to be displayed to screen while recording.

My solution uses pyaudio for audio recording, opencv for video recording, and ffmpeg for muxing the two signals. To be able to record both simultaneously, I use multithreading. One thread records video, and a second one the audio. I have uploaded my code to github and also have included all the essential parts it here.
https://github.com/JRodrigoF/AVrecordeR
Note: opencv is not able to control the fps at which the webcamera does the recording. It is only able to specify in the encoding of the file the desired final fps, but the webcamera usually behaves differently according to specifications and light conditions (I found). So the fps have to be controlled at the level of the code.
import cv2
import pyaudio
import wave
import threading
import time
import subprocess
import os

class VideoRecorder():

    # Video class based on openCV
    def __init__(self):

        self.open = True
        self.device_index = 0
        self.fps = 6               # fps should be the minimum constant rate at which the camera can
        self.fourcc = "MJPG"       # capture images (with no decrease in speed over time; testing is required)
        self.frameSize = (640,480) # video formats and sizes also depend and vary according to the camera used
        self.video_filename = "temp_video.avi"
        self.video_cap = cv2.VideoCapture(self.device_index)
        self.video_writer = cv2.VideoWriter_fourcc(*self.fourcc)
        self.video_out = cv2.VideoWriter(self.video_filename, self.video_writer, self.fps, self.frameSize)
        self.frame_counts = 1
        self.start_time = time.time()

    # Video starts being recorded
    def record(self):

#       counter = 1
        timer_start = time.time()
        timer_current = 0

        while(self.open==True):
            ret, video_frame = self.video_cap.read()
            if (ret==True):

                    self.video_out.write(video_frame)
#                   print str(counter) + " " + str(self.frame_counts) + " frames written " + str(timer_current)
                    self.frame_counts += 1
#                   counter += 1
#                   timer_current = time.time() - timer_start
                    time.sleep(0.16)
#                   gray = cv2.cvtColor(video_frame, cv2.COLOR_BGR2GRAY)
#                   cv2.imshow('video_frame', gray)
#                   cv2.waitKey(1)
            else:
                break

                # 0.16 delay -> 6 fps
                #

    # Finishes the video recording therefore the thread too
    def stop(self):

        if self.open==True:

            self.open=False
            self.video_out.release()
            self.video_cap.release()
            cv2.destroyAllWindows()

        else:
            pass

    # Launches the video recording function using a thread
    def start(self):
        video_thread = threading.Thread(target=self.record)
        video_thread.start()

class AudioRecorder():

    # Audio class based on pyAudio and Wave
    def __init__(self):

        self.open = True
        self.rate = 44100
        self.frames_per_buffer = 1024
        self.channels = 2
        self.format = pyaudio.paInt16
        self.audio_filename = "temp_audio.wav"
        self.audio = pyaudio.PyAudio()
        self.stream = self.audio.open(format=self.format,
                                      channels=self.channels,
                                      rate=self.rate,
                                      input=True,
                                      frames_per_buffer = self.frames_per_buffer)
        self.audio_frames = []

    # Audio starts being recorded
    def record(self):

        self.stream.start_stream()
        while(self.open == True):
            data = self.stream.read(self.frames_per_buffer)
            self.audio_frames.append(data)
            if self.open==False:
                break

    # Finishes the audio recording therefore the thread too
    def stop(self):

        if self.open==True:
            self.open = False
            self.stream.stop_stream()
            self.stream.close()
            self.audio.terminate()

            waveFile = wave.open(self.audio_filename, 'wb')
            waveFile.setnchannels(self.channels)
            waveFile.setsampwidth(self.audio.get_sample_size(self.format))
            waveFile.setframerate(self.rate)
            waveFile.writeframes(b''.join(self.audio_frames))
            waveFile.close()

        pass

    # Launches the audio recording function using a thread
    def start(self):
        audio_thread = threading.Thread(target=self.record)
        audio_thread.start()

def start_AVrecording(filename):

    global video_thread
    global audio_thread

    video_thread = VideoRecorder()
    audio_thread = AudioRecorder()

    audio_thread.start()
    video_thread.start()

    return filename

def start_video_recording(filename):

    global video_thread

    video_thread = VideoRecorder()
    video_thread.start()

    return filename

def start_audio_recording(filename):

    global audio_thread

    audio_thread = AudioRecorder()
    audio_thread.start()

    return filename

def stop_AVrecording(filename):

    audio_thread.stop()
    frame_counts = video_thread.frame_counts
    elapsed_time = time.time() - video_thread.start_time
    recorded_fps = frame_counts / elapsed_time
    print "total frames " + str(frame_counts)
    print "elapsed time " + str(elapsed_time)
    print "recorded fps " + str(recorded_fps)
    video_thread.stop()

    # Makes sure the threads have finished
    while threading.active_count() > 1:
        time.sleep(1)

#    Merging audio and video signal

    if abs(recorded_fps - 6) >= 0.01:    # If the fps rate was higher/lower than expected, re-encode it to the expected

        print "Re-encoding"
        cmd = "ffmpeg -r " + str(recorded_fps) + " -i temp_video.avi -pix_fmt yuv420p -r 6 temp_video2.avi"
        subprocess.call(cmd, shell=True)

        print "Muxing"
        cmd = "ffmpeg -ac 2 -channel_layout stereo -i temp_audio.wav -i temp_video2.avi -pix_fmt yuv420p " + filename + ".avi"
        subprocess.call(cmd, shell=True)

    else:

        print "Normal recording\nMuxing"
        cmd = "ffmpeg -ac 2 -channel_layout stereo -i temp_audio.wav -i temp_video.avi -pix_fmt yuv420p " + filename + ".avi"
        subprocess.call(cmd, shell=True)

        print ".."

# Required and wanted processing of final files
def file_manager(filename):

    local_path = os.getcwd()

    if os.path.exists(str(local_path) + "/temp_audio.wav"):
        os.remove(str(local_path) + "/temp_audio.wav")

    if os.path.exists(str(local_path) + "/temp_video.avi"):
        os.remove(str(local_path) + "/temp_video.avi")

    if os.path.exists(str(local_path) + "/temp_video2.avi"):
        os.remove(str(local_path) + "/temp_video2.avi")

    if os.path.exists(str(local_path) + "/" + filename + ".avi"):
        os.remove(str(local_path) + "/" + filename + ".avi")

A: I've been looking around for a good answer to this, and I think it is GStreamer...
The documentation for the python bindings is extremely light, and most of it seemed centered around the old 0.10 version of GStreamer instead of the new 1.X versions, but GStreamer is a extremely powerful, cross-platform multimedia framework that can stream, mux, transcode, and display just about anything.

A: I used JRodrigoF's script for a while on a project. However, I noticed that sometimes the threads would hang and it would cause the program to crash. Another issue is that openCV does not capture video frames at a reliable rate and ffmpeg would distort my video when re-encoding.
I came up with a new solution that records much more reliably and with much higher quality for my application. It presently only works for Windows because it uses pywinauto and the built-in Windows Camera app. The last bit of the script does some error-checking to confirm the video successfully recorded by checking the timestamp of the name of the video.
https://gist.github.com/mjdargen/956cc968864f38bfc4e20c9798c7d670
import pywinauto
import time
import subprocess
import os
import datetime

def win_record(duration):
    subprocess.run('start microsoft.windows.camera:', shell=True)  # open camera app

    # focus window by getting handle using title and class name
    # subprocess call opens camera and gets focus, but this provides alternate way
    # t, c = 'Camera', 'ApplicationFrameWindow'
    # handle = pywinauto.findwindows.find_windows(title=t, class_name=c)[0]
    # # get app and window
    # app = pywinauto.application.Application().connect(handle=handle)
    # window = app.window(handle=handle)
    # window.set_focus()  # set focus
    time.sleep(2)  # have to sleep

    # take control of camera window to take video
    desktop = pywinauto.Desktop(backend="uia")
    cam = desktop['Camera']
    # cam.print_control_identifiers()
    # make sure in video mode
    if cam.child_window(title="Switch to Video mode", auto_id="CaptureButton_1", control_type="Button").exists():
        cam.child_window(title="Switch to Video mode", auto_id="CaptureButton_1", control_type="Button").click()
    time.sleep(1)
    # start then stop video
    cam.child_window(title="Take Video", auto_id="CaptureButton_1", control_type="Button").click()
    time.sleep(duration+2)
    cam.child_window(title="Stop taking Video", auto_id="CaptureButton_1", control_type="Button").click()

    # retrieve vids from camera roll and sort
    dir = 'C:/Users/m/Pictures/Camera Roll'
    all_contents = list(os.listdir(dir))
    vids = [f for f in all_contents if "_Pro.mp4" in f]
    vids.sort()
    vid = vids[-1]  # get last vid
    # compute time difference
    vid_time = vid.replace('WIN_', '').replace('_Pro.mp4', '')
    vid_time = datetime.datetime.strptime(vid_time, '%Y%m%d_%H_%M_%S')
    now = datetime.datetime.now()
    diff = now - vid_time
    # time different greater than 2 minutes, assume something wrong & quit
    if diff.seconds > 120:
        quit()

    subprocess.run('Taskkill /IM WindowsCamera.exe /F', shell=True)  # close camera app
    print('Recorded successfully!')

win_record(2)

A: To the questions asked above: Yes the code should also works under Python3. I adjusted it a little bit and now works for python2 and python3 (tested it on windows7 with 2.7 and 3.6, though you need to have ffmpeg installed or the executable ffmpeg.exe at least in the same directory, you can get it here: https://www.ffmpeg.org/download.html ). Of course you also need all the other libraries cv2, numpy, pyaudio, installed like herewith:
pip install opencv-python numpy pyaudio

You can now run the code directly:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# VideoRecorder.py

from __future__ import print_function, division
import numpy as np
import cv2
import pyaudio
import wave
import threading
import time
import subprocess
import os

class VideoRecorder():
    "Video class based on openCV"
    def __init__(self, name="temp_video.avi", fourcc="MJPG", sizex=640, sizey=480, camindex=0, fps=30):
        self.open = True
        self.device_index = camindex
        self.fps = fps                  # fps should be the minimum constant rate at which the camera can
        self.fourcc = fourcc            # capture images (with no decrease in speed over time; testing is required)
        self.frameSize = (sizex, sizey) # video formats and sizes also depend and vary according to the camera used
        self.video_filename = name
        self.video_cap = cv2.VideoCapture(self.device_index)
        self.video_writer = cv2.VideoWriter_fourcc(*self.fourcc)
        self.video_out = cv2.VideoWriter(self.video_filename, self.video_writer, self.fps, self.frameSize)
        self.frame_counts = 1
        self.start_time = time.time()

    def record(self):
        "Video starts being recorded"
        # counter = 1
        timer_start = time.time()
        timer_current = 0
        while self.open:
            ret, video_frame = self.video_cap.read()
            if ret:
                self.video_out.write(video_frame)
                # print(str(counter) + " " + str(self.frame_counts) + " frames written " + str(timer_current))
                self.frame_counts += 1
                # counter += 1
                # timer_current = time.time() - timer_start
                time.sleep(1/self.fps)
                # gray = cv2.cvtColor(video_frame, cv2.COLOR_BGR2GRAY)
                # cv2.imshow('video_frame', gray)
                # cv2.waitKey(1)
            else:
                break

    def stop(self):
        "Finishes the video recording therefore the thread too"
        if self.open:
            self.open=False
            self.video_out.release()
            self.video_cap.release()
            cv2.destroyAllWindows()

    def start(self):
        "Launches the video recording function using a thread"
        video_thread = threading.Thread(target=self.record)
        video_thread.start()

class AudioRecorder():
    "Audio class based on pyAudio and Wave"
    def __init__(self, filename="temp_audio.wav", rate=44100, fpb=1024, channels=2):
        self.open = True
        self.rate = rate
        self.frames_per_buffer = fpb
        self.channels = channels
        self.format = pyaudio.paInt16
        self.audio_filename = filename
        self.audio = pyaudio.PyAudio()
        self.stream = self.audio.open(format=self.format,
                                      channels=self.channels,
                                      rate=self.rate,
                                      input=True,
                                      frames_per_buffer = self.frames_per_buffer)
        self.audio_frames = []

    def record(self):
        "Audio starts being recorded"
        self.stream.start_stream()
        while self.open:
            data = self.stream.read(self.frames_per_buffer)
            self.audio_frames.append(data)
            if not self.open:
                break

    def stop(self):
        "Finishes the audio recording therefore the thread too"
        if self.open:
            self.open = False
            self.stream.stop_stream()
            self.stream.close()
            self.audio.terminate()
            waveFile = wave.open(self.audio_filename, 'wb')
            waveFile.setnchannels(self.channels)
            waveFile.setsampwidth(self.audio.get_sample_size(self.format))
            waveFile.setframerate(self.rate)
            waveFile.writeframes(b''.join(self.audio_frames))
            waveFile.close()

    def start(self):
        "Launches the audio recording function using a thread"
        audio_thread = threading.Thread(target=self.record)
        audio_thread.start()

def start_AVrecording(filename="test"):
    global video_thread
    global audio_thread
    video_thread = VideoRecorder()
    audio_thread = AudioRecorder()
    audio_thread.start()
    video_thread.start()
    return filename

def start_video_recording(filename="test"):
    global video_thread
    video_thread = VideoRecorder()
    video_thread.start()
    return filename

def start_audio_recording(filename="test"):
    global audio_thread
    audio_thread = AudioRecorder()
    audio_thread.start()
    return filename

def stop_AVrecording(filename="test"):
    audio_thread.stop()
    frame_counts = video_thread.frame_counts
    elapsed_time = time.time() - video_thread.start_time
    recorded_fps = frame_counts / elapsed_time
    print("total frames " + str(frame_counts))
    print("elapsed time " + str(elapsed_time))
    print("recorded fps " + str(recorded_fps))
    video_thread.stop()

    # Makes sure the threads have finished
    while threading.active_count() > 1:
        time.sleep(1)

    # Merging audio and video signal
    if abs(recorded_fps - 6) >= 0.01:    # If the fps rate was higher/lower than expected, re-encode it to the expected
        print("Re-encoding")
        cmd = "ffmpeg -r " + str(recorded_fps) + " -i temp_video.avi -pix_fmt yuv420p -r 6 temp_video2.avi"
        subprocess.call(cmd, shell=True)
        print("Muxing")
        cmd = "ffmpeg -y -ac 2 -channel_layout stereo -i temp_audio.wav -i temp_video2.avi -pix_fmt yuv420p " + filename + ".avi"
        subprocess.call(cmd, shell=True)
    else:
        print("Normal recording\nMuxing")
        cmd = "ffmpeg -y -ac 2 -channel_layout stereo -i temp_audio.wav -i temp_video.avi -pix_fmt yuv420p " + filename + ".avi"
        subprocess.call(cmd, shell=True)
        print("..")

def file_manager(filename="test"):
    "Required and wanted processing of final files"
    local_path = os.getcwd()
    if os.path.exists(str(local_path) + "/temp_audio.wav"):
        os.remove(str(local_path) + "/temp_audio.wav")
    if os.path.exists(str(local_path) + "/temp_video.avi"):
        os.remove(str(local_path) + "/temp_video.avi")
    if os.path.exists(str(local_path) + "/temp_video2.avi"):
        os.remove(str(local_path) + "/temp_video2.avi")
    # if os.path.exists(str(local_path) + "/" + filename + ".avi"):
    #     os.remove(str(local_path) + "/" + filename + ".avi")

if __name__ == '__main__':
    start_AVrecording()
    time.sleep(5)
    stop_AVrecording()
    file_manager()

A: If you notice misalignment between video and audio by the code above, please see my solution below
I think the most rated answer above does a great job. However, it did not work perfectly when I was using it,especially when you use a low fps rate (say 10). The main issue is with video recording. In order to properly synchronize video and audio recording with ffmpeg, one has to make sure that cv2.VideoCapture() and cv2.VideoWriter() share exact same FPS, because the recorded video time length is solely determined by fps rate and the number of frames.
Following is my suggested update:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# VideoRecorder.py

from __future__ import print_function, division
import numpy as np
import cv2
import pyaudio
import wave
import threading
import time
import subprocess
import os
import ffmpeg

class VideoRecorder():
    "Video class based on openCV"
    def __init__(self, name="temp_video.avi", fourcc="MJPG", sizex=640, sizey=480, camindex=0, fps=30):
        self.open = True
        self.device_index = camindex
        self.fps = fps                  # fps should be the minimum constant rate at which the camera can
        self.fourcc = fourcc            # capture images (with no decrease in speed over time; testing is required)
        self.frameSize = (sizex, sizey) # video formats and sizes also depend and vary according to the camera used
        self.video_filename = name
        self.video_cap = cv2.VideoCapture(self.device_index)
        self.video_cap.set(cv2.CAP_PROP_FPS, self.fps)
        self.video_writer = cv2.VideoWriter_fourcc(*self.fourcc)
        self.video_out = cv2.VideoWriter(self.video_filename, self.video_writer, self.fps, self.frameSize)
        self.frame_counts = 1
        self.start_time = time.time()

    def record(self):
        "Video starts being recorded"
        # counter = 1
        timer_start = time.time()
        timer_current = 0
        while self.open:
            ret, video_frame = self.video_cap.read()
            if ret:
                self.video_out.write(video_frame)
                # print(str(counter) + " " + str(self.frame_counts) + " frames written " + str(timer_current))
                self.frame_counts += 1
                # print(self.frame_counts)
                # counter += 1
                # timer_current = time.time() - timer_start
                # time.sleep(1/self.fps)
                # gray = cv2.cvtColor(video_frame, cv2.COLOR_BGR2GRAY)
                # cv2.imshow('video_frame', gray)
                # cv2.waitKey(1)
            else:
                break

    def stop(self):
        "Finishes the video recording therefore the thread too"
        if self.open:
            self.open=False
            self.video_out.release()
            self.video_cap.release()
            cv2.destroyAllWindows()

    def start(self):
        "Launches the video recording function using a thread"
        video_thread = threading.Thread(target=self.record)
        video_thread.start()

class AudioRecorder():
    "Audio class based on pyAudio and Wave"
    def __init__(self, filename="temp_audio.wav", rate=44100, fpb=1024, channels=2):
        self.open = True
        self.rate = rate
        self.frames_per_buffer = fpb
        self.channels = channels
        self.format = pyaudio.paInt16
        self.audio_filename = filename
        self.audio = pyaudio.PyAudio()
        self.stream = self.audio.open(format=self.format,
                                      channels=self.channels,
                                      rate=self.rate,
                                      input=True,
                                      frames_per_buffer = self.frames_per_buffer)
        self.audio_frames = []

    def record(self):
        "Audio starts being recorded"
        self.stream.start_stream()
        while self.open:
            data = self.stream.read(self.frames_per_buffer)
            self.audio_frames.append(data)
            if not self.open:
                break

    def stop(self):
        "Finishes the audio recording therefore the thread too"
        if self.open:
            self.open = False
            self.stream.stop_stream()
            self.stream.close()
            self.audio.terminate()
            waveFile = wave.open(self.audio_filename, 'wb')
            waveFile.setnchannels(self.channels)
            waveFile.setsampwidth(self.audio.get_sample_size(self.format))
            waveFile.setframerate(self.rate)
            waveFile.writeframes(b''.join(self.audio_frames))
            waveFile.close()

    def start(self):
        "Launches the audio recording function using a thread"
        audio_thread = threading.Thread(target=self.record)
        audio_thread.start()

def start_AVrecording(filename="test"):
    global video_thread
    global audio_thread
    video_thread = VideoRecorder()
    audio_thread = AudioRecorder()
    audio_thread.start()
    video_thread.start()
    return filename

def start_video_recording(filename="test"):
    global video_thread
    video_thread = VideoRecorder()
    video_thread.start()
    return filename

def start_audio_recording(filename="test"):
    global audio_thread
    audio_thread = AudioRecorder()
    audio_thread.start()
    return filename

def stop_AVrecording(filename="test"):
    audio_thread.stop()
    frame_counts = video_thread.frame_counts
    elapsed_time = time.time() - video_thread.start_time
    recorded_fps = frame_counts / elapsed_time
    print("total frames " + str(frame_counts))
    print("elapsed time " + str(elapsed_time))
    print("recorded fps " + str(recorded_fps))
    video_thread.stop()

    # Makes sure the threads have finished
    while threading.active_count() > 1:
        time.sleep(1)

    video_stream = ffmpeg.input(video_thread.video_filename)
    audio_stream = ffmpeg.input(audio_thread.audio_filename)
    ffmpeg.output(audio_stream, video_stream, 'out.mp4').run(overwrite_output=True)

    # # Merging audio and video signal
    # if abs(recorded_fps - 6) >= 0.01:    # If the fps rate was higher/lower than expected, re-encode it to the expected
    #     print("Re-encoding")
    #     cmd = "ffmpeg -r " + str(recorded_fps) + " -i temp_video.avi -pix_fmt yuv420p -r 6 temp_video2.avi"
    #     subprocess.call(cmd, shell=True)
    #     print("Muxing")
    #     cmd = "ffmpeg -y -ac 2 -channel_layout stereo -i temp_audio.wav -i temp_video2.avi -pix_fmt yuv420p " + filename + ".avi"
    #     subprocess.call(cmd, shell=True)
    # else:
    #     print("Normal recording\nMuxing")
    #     cmd = "ffmpeg -y -ac 2 -channel_layout stereo -i temp_audio.wav -i temp_video.avi -pix_fmt yuv420p " + filename + ".avi"
    #     subprocess.call(cmd, shell=True)
    #     print("..")

def file_manager(filename="test"):
    "Required and wanted processing of final files"
    local_path = os.getcwd()
    if os.path.exists(str(local_path) + "/temp_audio.wav"):
        os.remove(str(local_path) + "/temp_audio.wav")
    if os.path.exists(str(local_path) + "/temp_video.avi"):
        os.remove(str(local_path) + "/temp_video.avi")
    if os.path.exists(str(local_path) + "/temp_video2.avi"):
        os.remove(str(local_path) + "/temp_video2.avi")
    # if os.path.exists(str(local_path) + "/" + filename + ".avi"):
    #     os.remove(str(local_path) + "/" + filename + ".avi")

if __name__ == '__main__':
    start_AVrecording()
    # try:
    #     while True:
    #         pass
    # except KeyboardInterrupt:
    #     stop_AVrecording()
    time.sleep(10)
    stop_AVrecording()
    print("finishing recording")

    file_manager()

A: Using everyone's contributions and following the suggestion of Paul
I was able to come up with the following code:
Recorder.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# VideoRecorder.py

from __future__ import print_function, division
import numpy as np
import sys
import cv2
import pyaudio
import wave
import threading
import time
import subprocess
import os
import ffmpeg

REC_FOLDER = "recordings/"

class Recorder():
    def __init__(self, filename):
        self.filename = filename
        self.video_thread = self.VideoRecorder(self, REC_FOLDER + filename)
        self.audio_thread = self.AudioRecorder(self, REC_FOLDER + filename)

    def startRecording(self):
        self.video_thread.start()
        self.audio_thread.start()

    def stopRecording(self):
        self.video_thread.stop()
        self.audio_thread.stop()

    def saveRecording(self):
        #Save audio / Show video resume
        self.audio_thread.saveAudio()
        self.video_thread.showFramesResume()

        #Merges both streams and writes
        video_stream = ffmpeg.input(self.video_thread.video_filename)
        audio_stream = ffmpeg.input(self.audio_thread.audio_filename)
        while (not os.path.exists(self.audio_thread.audio_filename)):
            print("waiting for audio file to exit...")
        stream = ffmpeg.output(video_stream, audio_stream, REC_FOLDER + self.filename +".mp4")

        try:
            ffmpeg.run(stream, capture_stdout=True, capture_stderr=True, overwrite_output=True)
        except ffmpeg.Error as e:
            print(e.stdout, file=sys.stderr)
            print(e.stderr, file=sys.stderr)

    class VideoRecorder():
        "Video class based on openCV"
        def __init__(self, recorder, name, fourcc="MJPG", frameSize=(640,480), camindex=0, fps=15):
            self.recorder = recorder
            self.open = True
            self.duration = 0
            self.device_index = camindex
            self.fps = fps                          # fps should be the minimum constant rate at which the camera can
            self.fourcc = fourcc                    # capture images (with no decrease in speed over time; testing is required)
            self.video_filename = name + ".avi"     # video formats and sizes also depend and vary according to the camera used
            self.video_cap = cv2.VideoCapture(self.device_index, cv2.CAP_DSHOW)
            self.video_writer = cv2.VideoWriter_fourcc(*fourcc)
            self.video_out = cv2.VideoWriter(self.video_filename, self.video_writer, self.fps, frameSize)
            self.frame_counts = 1
            self.start_time = time.time()

        def record(self):
            "Video starts being recorded"
            counter = 1
            while self.open:
                ret, video_frame = self.video_cap.read()
                if ret:
                    self.video_out.write(video_frame)
                    self.frame_counts += 1
                    counter += 1
                    self.duration += 1/self.fps
                    if (video_frame is None): print("I WAS NONEEEEEEEEEEEEEEEEEEEEEE")
                    gray = cv2.cvtColor(video_frame, cv2.COLOR_BGR2GRAY)
                    cv2.imshow('video_frame', gray)
                    cv2.waitKey(1)

                    while(self.duration - self.recorder.audio_thread.duration >= 0.2 and self.recorder.audio_thread.open):
                        time.sleep(0.2)
                else:
                    break

            #Release Video
            self.video_out.release()
            self.video_cap.release()
            cv2.destroyAllWindows()
            self.video_out = None

        def stop(self):
            "Finishes the video recording therefore the thread too"
            self.open=False

        def start(self):
            "Launches the video recording function using a thread"
            self.thread = threading.Thread(target=self.record)
            self.thread.start()

        def showFramesResume(self):
            #Only stop of video has all frames
            frame_counts = self.frame_counts
            elapsed_time = time.time() - self.start_time
            recorded_fps = self.frame_counts / elapsed_time
            print("total frames " + str(frame_counts))
            print("elapsed time " + str(elapsed_time))
            print("recorded fps " + str(recorded_fps))

    class AudioRecorder():
        "Audio class based on pyAudio and Wave"
        def __init__(self, recorder, filename, rate=44100, fpb=1024, channels=1, audio_index=0):
            self.recorder = recorder
            self.open = True
            self.rate = rate
            self.duration = 0
            self.frames_per_buffer = fpb
            self.channels = channels
            self.format = pyaudio.paInt16
            self.audio_filename = filename + ".wav"
            self.audio = pyaudio.PyAudio()
            self.stream = self.audio.open(format=self.format,
                                        channels=self.channels,
                                        rate=self.rate,
                                        input=True,
                                        input_device_index=audio_index,
                                        frames_per_buffer = self.frames_per_buffer)
            self.audio_frames = []

        def record(self):
            "Audio starts being recorded"
            self.stream.start_stream()
            t_start = time.time_ns()
            while self.open:
                try:
                    self.duration += self.frames_per_buffer / self.rate
                    data = self.stream.read(self.frames_per_buffer)
                    self.audio_frames.append(data)
                except Exception as e:
                    print('\n' + '*'*80)
                    print('PyAudio read exception at %.1fms\n' % ((time.time_ns() - t_start)/10**6))
                    print(e)
                    print('*'*80 + '\n')
                while(self.duration - self.recorder.video_thread.duration >= 0.5):
                    time.sleep(0.5)
            #Closes audio stream
            self.stream.stop_stream()
            self.stream.close()
            self.audio.terminate()

        def stop(self):
            "Finishes the audio recording therefore the thread too"
            self.open = False

        def start(self):
            "Launches the audio recording function using a thread"
            self.thread = threading.Thread(target=self.record)
            self.thread.start()

        def saveAudio(self):
            #Save Audio File
            waveFile = wave.open(self.audio_filename, 'wb')
            waveFile.setnchannels(self.channels)
            waveFile.setsampwidth(self.audio.get_sample_size(self.format))
            waveFile.setframerate(self.rate)
            waveFile.writeframes(b''.join(self.audio_frames))
            waveFile.close()

Main.py
from recorder import Recorder
import time

recorder = Recorder("test1")
recorder.startRecording()
time.sleep(240)
recorder.stopRecording()
recorder.saveRecording()

With this solution, the camera and the audio will wait for each other.
I also tried the FFmpeg Re-encoding and Muxing and even though it was able to synchronize the audio with video, the video had a massive quality drop.

A: You can do offline html,js code to do video with audio recording. Using python lib python webview open that page. It should work fine.

A: I was randomly getting "[Errno -9999] Unanticipated host error" while using JRodrigoF's solution and found that it's due to a race condition where an audio stream can be closed just before being read for the last time inside record() of AudioRecorder class.
I modified slightly so that all the closing procedures are done after the while loop and added a function list_audio_devices() that shows the list of audio devices to select from. I also added an audio device index as a parameter to choose an audio device.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# VideoRecorder.py

from __future__ import print_function, division
import numpy as np
import cv2
import pyaudio
import wave
import threading
import time
import subprocess
import os

class VideoRecorder():
    "Video class based on openCV"
    def __init__(self, name="temp_video.avi", fourcc="MJPG", sizex=640, sizey=480, camindex=0, fps=30):
        self.open = True
        self.device_index = camindex
        self.fps = fps                  # fps should be the minimum constant rate at which the camera can
        self.fourcc = fourcc            # capture images (with no decrease in speed over time; testing is required)
        self.frameSize = (sizex, sizey) # video formats and sizes also depend and vary according to the camera used
        self.video_filename = name
        self.video_cap = cv2.VideoCapture(self.device_index)
        self.video_writer = cv2.VideoWriter_fourcc(*self.fourcc)
        self.video_out = cv2.VideoWriter(self.video_filename, self.video_writer, self.fps, self.frameSize)
        self.frame_counts = 1
        self.start_time = time.time()

    def record(self):
        "Video starts being recorded"
        # counter = 1
        timer_start = time.time()
        timer_current = 0
        while self.open:
            ret, video_frame = self.video_cap.read()
            if ret:
                self.video_out.write(video_frame)
                # print(str(counter) + " " + str(self.frame_counts) + " frames written " + str(timer_current))
                self.frame_counts += 1
                # counter += 1
                # timer_current = time.time() - timer_start
                time.sleep(1/self.fps)
                # gray = cv2.cvtColor(video_frame, cv2.COLOR_BGR2GRAY)
                # cv2.imshow('video_frame', gray)
                # cv2.waitKey(1)
            else:
                break

    def stop(self):
        "Finishes the video recording therefore the thread too"
        if self.open:
            self.open=False
            self.video_out.release()
            self.video_cap.release()
            cv2.destroyAllWindows()

    def start(self):
        "Launches the video recording function using a thread"
        video_thread = threading.Thread(target=self.record)
        video_thread.start()

class AudioRecorder():
    "Audio class based on pyAudio and Wave"
    def __init__(self, filename="temp_audio.wav", rate=44100, fpb=2**12, channels=1, audio_index=0):
        self.open = True
        self.rate = rate
        self.frames_per_buffer = fpb
        self.channels = channels
        self.format = pyaudio.paInt16
        self.audio_filename = filename
        self.audio = pyaudio.PyAudio()
        self.stream = self.audio.open(format=self.format,
                                      channels=self.channels,
                                      rate=self.rate,
                                      input=True,
                                      input_device_index=audio_index,
                                      frames_per_buffer = self.frames_per_buffer)
        self.audio_frames = []

    def record(self):
        "Audio starts being recorded"
        self.stream.start_stream()
        t_start = time.time_ns()
        while self.open:
            try:
                data = self.stream.read(self.frames_per_buffer)
                self.audio_frames.append(data)
            except Exception as e:
                print('\n' + '*'*80)
                print('PyAudio read exception at %.1fms\n' % ((time.time_ns() - t_start)/10**6))
                print(e)
                print('*'*80 + '\n')
            time.sleep(0.01)
        self.stream.stop_stream()
        self.stream.close()
        self.audio.terminate()
        waveFile = wave.open(self.audio_filename, 'wb')
        waveFile.setnchannels(self.channels)
        waveFile.setsampwidth(self.audio.get_sample_size(self.format))
        waveFile.setframerate(self.rate)
        waveFile.writeframes(b''.join(self.audio_frames))
        waveFile.close()

    def stop(self):
        "Finishes the audio recording therefore the thread too"
        if self.open:
            self.open = False

    def start(self):
        "Launches the audio recording function using a thread"
        audio_thread = threading.Thread(target=self.record)
        audio_thread.start()

def start_AVrecording(filename="test", audio_index=0, sample_rate=44100):
    global video_thread
    global audio_thread
    video_thread = VideoRecorder()
    audio_thread = AudioRecorder(audio_index=audio_index, rate=sample_rate)
    audio_thread.start()
    video_thread.start()
    return filename

def start_video_recording(filename="test"):
    global video_thread
    video_thread = VideoRecorder()
    video_thread.start()
    return filename

def start_audio_recording(filename="test", audio_index=0, sample_rate=44100):
    global audio_thread
    audio_thread = AudioRecorder(audio_index=audio_index, rate=sample_rate)
    audio_thread.start()
    return filename

def stop_AVrecording(filename="test"):
    audio_thread.stop()
    frame_counts = video_thread.frame_counts
    elapsed_time = time.time() - video_thread.start_time
    recorded_fps = frame_counts / elapsed_time
    print("total frames " + str(frame_counts))
    print("elapsed time " + str(elapsed_time))
    print("recorded fps " + str(recorded_fps))
    video_thread.stop()

    # Makes sure the threads have finished
    while threading.active_count() > 1:
        time.sleep(1)

    # Merging audio and video signal
    if abs(recorded_fps - 6) >= 0.01:    # If the fps rate was higher/lower than expected, re-encode it to the expected
        print("Re-encoding")
        cmd = "ffmpeg -r " + str(recorded_fps) + " -i temp_video.avi -pix_fmt yuv420p -r 6 temp_video2.avi"
        subprocess.call(cmd, shell=True)
        print("Muxing")
        cmd = "ffmpeg -y -ac 2 -channel_layout stereo -i temp_audio.wav -i temp_video2.avi -pix_fmt yuv420p " + filename + ".avi"
        subprocess.call(cmd, shell=True)
    else:
        print("Normal recording\nMuxing")
        cmd = "ffmpeg -y -ac 2 -channel_layout stereo -i temp_audio.wav -i temp_video.avi -pix_fmt yuv420p " + filename + ".avi"
        subprocess.call(cmd, shell=True)
        print("..")

def file_manager(filename="test"):
    "Required and wanted processing of final files"
    local_path = os.getcwd()
    if os.path.exists(str(local_path) + "/temp_audio.wav"):
        os.remove(str(local_path) + "/temp_audio.wav")
    if os.path.exists(str(local_path) + "/temp_video.avi"):
        os.remove(str(local_path) + "/temp_video.avi")
    if os.path.exists(str(local_path) + "/temp_video2.avi"):
        os.remove(str(local_path) + "/temp_video2.avi")
    # if os.path.exists(str(local_path) + "/" + filename + ".avi"):
    #     os.remove(str(local_path) + "/" + filename + ".avi")

def list_audio_devices(name_filter=None):
    pa = pyaudio.PyAudio()
    device_index = None
    sample_rate = None
    for x in range(pa.get_device_count()):
        info = pa.get_device_info_by_index(x)
        print(pa.get_device_info_by_index(x))
        if name_filter is not None and name_filter in info['name']:
            device_index = info['index']
            sample_rate = int(info['defaultSampleRate'])
            break
    return device_index, sample_rate

if __name__ == '__main__':
    start_AVrecording()
    time.sleep(5)
    stop_AVrecording()
    file_manager()


Q: Heroku, Rails: WildCard SSL cause env['warden'] to return nil In my rails app. I'm using devise. Users will enter the top page from several subdomains like "ja.myapp.com", "www.myapp.com" etc..
I use several subdomains only inside promotion pages, so when they enter the "sign in" page, All of them will redirect to the "www" subdomain page.
When user sign in, if the user's profile_type was "Student", user will redirect to "Students' home"., if it was "Teacher", "Teachers' home".
Everything works fine when I test with "POW", but when I uploaded it to the production server.
After user signed in, all of them will redirect to the TOP page.
I rollback the app and, try signing in again, but same thing happend
This happened after I uploaded the heroku certs from "single domain SSL" to "wildcard subdomains SSL".
After I change the SSL to single domain one, this won't happens anymore inside the rollbacked site.
I suppose that this happened because of the "wildcard subdomain SSL" & devise session controller, but not so sure about that.
Does anyone have any idea to fix this problem?
Below are the code.
routes.rb
root :to => 'students#index', :constraints => lambda { |request| request.env['warden'].user.try(:profile_type) == 'Student' }
root :to => 'teachers#index', :constraints => lambda { |request| request.env['warden'].user.try(:profile_type) == 'Teacher' }
root :to => 'pages#home'
devise_for :users, :controllers => {:sessions => "sessions", :registrations => "registrations", :confirmations => "confirmations"}

config/initializers/session_store.rb
MyAPP::Application.config.session_store :cookie_store, key: '_my_app_secure_session', domain: :all

# coding: utf-8
class SessionsController < Devise::SessionsController
  after_filter :clear_sign_signout_flash
  def after_sign_in_path_for(resource)
    url = root_path
  end

  def new
    @title = I18n.t "sessions.new.title"
    super
  end

  def create
    super
  end

  def destroy
    super
  end

  protected
  def clear_sign_signout_flash
    if flash.keys.include?(:notice)
      flash.delete(:notice)
    end
  end

end

application_controller
class ApplicationController < ActionController::Base
  protect_from_forgery
  before_filter :set_locale, :www_redirect

  private
  def www_redirect
    #if Rails.env.production
      parsed_subdomain = request.subdomains.first
      locale = Locale.find_by_subdomain(parsed_subdomain)
      if (use_www? && parsed_subdomain != "www") || locale.nil?
        redirect_to request.url.sub(parsed_subdomain, "www")
      end
    #end
  end

  def use_www?
    true
  end

  def set_locale
    if user_signed_in?
      if current_user.profile_type == "Teacher"
        I18n.locale = I18n.default_locale
      else
        I18n.locale = current_user.locale.i18n_form.to_sym
      end
    else
      if request.subdomains.first == "www" && cookies[:locale]
        I18n.locale = cookies[:locale].to_sym
      else
        I18n.locale = extract_locale_from_subdomain || I18n.default_locale
        cookies[:locale] = {
          value: I18n.locale.to_s,
          expires: 1.year.from_now,
          domain: :all
        }
      end
    end
  end

  def extract_locale_from_subdomain
    parsed_subdomain = request.subdomains.first
    locale = Locale.find_by_subdomain(parsed_subdomain)
    if locale
      I18n.available_locales.include?(locale.i18n_form.to_sym) ? locale.i18n_form.to_sym : nil
    else
      nil
    end
  end
end

locale_settings_controller.rb
class LocaleSettingsController < ApplicationController

  def switch_language
    locale = params[:locale]
    locale = "www" if locale == "en"
    path = params[:uri]
    cookies[:locale] = {
      value: locale,
      expires: 1.year.from_now,
      domain: :all
    }
    if Rails.env.production?
      base_url = "http://" + "#{locale}" + ".myapp.com"
    else
      base_url = "http://" + "#{locale}" + ".myapp.dev"
    end
    url = path == "/" ?  base_url : base_url + "#{path}"
    redirect_to url
  end
end

production.rb
config.force_ssl = true

config/initializers/rack_rewrite.rb
require 'rack/rewrite'

LingualBox::Application.config.middleware.insert_before(Rack::Lock, Rack::Rewrite) do
  r301 %r{.*}, 'http://www.myapp.com$&', :if => Proc.new {|rack_env|
    rack_env['SERVER_NAME'] == 'myapp.com'
  }
end if Rails.env == 'production'


Q: Trying to use Javascript Function in AmCharts4 Barchart to convert number of days to years and months I am adding some charts to a cakephp4 app using amcharts 4.
I have an amCharts4 bar chart that shows the number of days that I need to convert to
<years> years, <months> months, <days> days

in my source data I have an "amount" column that contains the number of days, for example 500. I need that to show up as '1 year, 4 months, 15 days. I am using a JS function getFormatedStringFromDays(numberOfDays) which works great.
I'm trying to set a var to be used in the function - I've tried Number(), parseInt(), etc. trying to get the var mypreconvertednumber to be seen as a number. Every attempt I
make produces NaN  - I can assign mypreconvertednumber a number (like var mypreconvertednumber = 500;) and of course it works fine.
My source data looks like this (amount is the number I'm trying to convert in the label):
barchart1.data = [{
        "type": "Last Check In",
        "amount": 500
},

var mypreconvertednumber = "{values.valueX.workingValue.formatNumber('#')}";

var valueLabel = series.bullets.push(new am4charts.LabelBullet());
valueLabel.label.text = getFormatedStringFromDays(mypreconvertednumber);
valueLabel.label.horizontalCenter = "left";
valueLabel.label.fontSize = 10;
valueLabel.label.truncate = false;
valueLabel.label.hideOversized = false;
valueLabel.label.dx = 5;

I'm hoping someone can point me to an amcharts built-in function to process the value label text like in amcharts 3.
"labelFunction": function(data) {
    return getFormatedStringFromDays(data);
},

I have been scouring the docs - and probably looked right past the option I need.
Thank you for any help any of you can give me to help solve this.
The function works when I place a number like:
getFormatedStringFromDays('500') // will return 1 year, 4 months, 15 days.

But when I try to use the var mypreconvertednumber = "{values.valueX.workingValue.formatNumber('#')}"; the function returns NaN - ive tried using Number(), parseInt() to attempt to make sure its a number but always get NaN.
getFormatedStringFromDays(mypreconvertednumber) // produces NaN  - even though the source data amount is: 500
barchart1.data = [{ "type": "Last Check In", "amount": 500 },...]