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: Determining the number of servers per farm needed I'm studying for the 668 and don't understand why I need 4 SP servers for these farms based on the requirements.

A: Here what i understand:
Farm1 will host the Service Applications( only cross farm services i.e UPA, MMS). so 2 servers are ok for this farm.
Farm2: according the deployment requirement....No services Applications on the servers host WebPages for user & also farm should be up and running if one server fails.
we need two WFE for failover...We need 1 App server for the Central admin and other server for the search.
Farm 3: again 2 servers for WFE( as fail over), One App Server( Central Admin) and One Server for the OWA as requirement is open word document in Browser and edit it.
SO user content will be accessible even one wfe is down.


Q: Can someone explain how expectations are used and evaluated in reinforcement learning? Going through some tutorials on reinforcement learning, I cannot help but to notice that people selectively put expectation operators around their equations (value, Q, loss, etc.), and when expectation is used, it is never evaluated.
Note: By "evaluated", I mean, if I were asked in a probability exam to find the expectation of $X$, where $X \sim \mathcal{N}(\mu, \sigma^2)$ is the Gaussian distribution, I would write $E(f_X(x)) = \mu$. If it were the uniform random variable, I would write $E(f_X(x)) = \dfrac{1}{n}$. It would be unthinkable for me to leave it as $E(f_X(x))$, but this is exactly what people in reinforcement learning does.
The usage of the expectation is also irregular:
For example, in these papers, expectation is not used in the definition of state-action value/function.
https://hmjianggatech.github.io/files/HCK.pdf
https://yilundu.github.io/2016/12/24/Deep-Q-Learning-on-Space-Invaders.html
In these papers, expectations are used
https://arxiv.org/pdf/1511.06581.pdf
http://paulorauber.com/notes/reinforcement_learning.pdf
https://www.nature.com/articles/nature14236.pdf
Finally, it is not clear to me how people can actually implement these expressions as actual algorithms, because the distributions, i.e., the policy, the environment, the reward, are never specified, they are just assumed to exist. More to the point, say that I am given the following definition,
$Q_\pi(s, a) = E_\pi[R_t|s_t = s, a_t = a]$
(as appears http://paulorauber.com/notes/reinforcement_learning.pdf)
However, we do not know what $\pi$ is at the beginning, we only know that it is some probability distribution. Furthermore, it is not clear how the inner expressions i.e. $R_t$.... depends on $\pi$. How do we evaluate this expression as something that is actually implementable in code?

A: In general, the derivations in RL work with expectations, because it is possible to show important relations analytically, such as Bellman optimality.
In Dynamic Programming, where you have a model, it is possible to expand from an expectation, using known probabilities from the model. Your reference text does this on page 4 for $Q^{\pi}(s,a)$. If you know the policy and environment model, the precise values of Q can be calculated. This is how Policy Iteration and Value Iteration work.
When you have a formula involving an expectation of some value from a system, and access to the system but not its operating parameters (the state transition probabilities in an MDP), it is possible to sample the value, and use that sample in stochastic approximations, because over many samples the eventual average will be the same as the expectation.
Essentially, Q Learning, SARSA, Monte Carlo Control are all algorithms that approximate Value Iteration from Dynamic Programming, by taking samples to resolve expectations in the long term, instead of calculating them over a known probability distribution.
As an aside, often $\pi(a|s)$ is known or under control of the learning agent, so it can be used to partially resolve expectations even when sampling. This knowledge is used in extensions to basic algorithms such as importance sampling and Expected SARSA.


Q: Can someone check my proof that an infinite subset of a countable set is countable? Thanks in advance.
Definitions: A set is $S$ countable iff there exists a bijection between $\mathbb{N}$ and S.
Some notable allowed assumptions: Non-empty finite sets of real numbers contain a maximum and a minimum. Non-empty sets of integers that are bounded above contain a maximum, similarly non-empty sets of integers that are bounded below contain a minimum. The natural numbers are not bounded above (Archimedian principle). Induction, strong induction.
This is problem 1.5.1 in "Understanding Analysis" by Abbott.
Problem: Assume $B$ is a countable set. Thus, there exists a function $f \colon \mathbb{N} \to B$ which is a bijection. Let $A \subseteq B$ be an infinite subset of $B$. Show that $A$ is countable.
My proof:


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: Reference Request - Jakob Weisblat's "The Search for the Odd Perfect Number" Hi All!
I am currently trying to locate an online copy of Jakob Weisblat's paper titled "The Search for the Odd Perfect Number".  I could only get hold of the abstract:
"A perfect number is a number whose proper divisors add up to the number itself. All known perfect numbers are of the form $(2^{p}-1)(2^{p-1})$ where p is prime and $2^{p}-1$ is prime. This talk will consider the possibility of an odd perfect number. After considering criteria for the prime factorization of an odd perfect number, many categories of odds will be eliminated. The remaining categories will then be more thoroughly considered.
The first part of the talk will be my personal research and investigations without having looked at anyone's previous work. Next, interesting previous studies on this matter will be discussed. Finally, my personal work will be compared to the previous analyses, and my research will be extended using this new information."
If anybody out there has a copy or has a web-link to an online copy, would you please be willing to share it?  Thanks!
Edit:  After taking to Ivars Peterson of MAA, it appears that the author was not required to make a paper submission for his talk.  Likewise, the author does not have a publicly available e-mail address.  Hence, reflecting quid's suggestion, is a write-up of the author's notes for this talk available somewhere?  The author is currently unreachable through Facebook messaging.


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: People Picker Port Tester Failed to DNS Test I have a Problem with People Picker in Sharepoint 2013,
I have One Domain Server with windows server 2008 and one Server for MSSQL 2012 and Sharepoint 2013. "we have a small network with 14 users at max".
Also we Have Kerio in network for Control internet sharing.
My Problem is i can't find any user with People Picker but i can select "Everyone" | "Domain Admin" and etc.
I test my Ports and DNS With People Picker Port Tester:
https://peoplepicker.codeplex.com/
And unfortunately the DNS Test section returns "no dns found" but all my ports can get connected. "I Allowed Ports in Firewall in both Servers"
I also find this error log when i trying to find users in AD with PP:
12/17/2014 00:37:20.23  w3wp.exe (0x1728)   0x1A88  SharePoint Foundation   General 72e7        Medium  Error in searching user 'Some-User' :     System.DirectoryServices.DirectoryServicesCOMException (0x80072020): An operations error occurred.       at System.DirectoryServices.SearchResultCollection.ResultsEnumerator.MoveNext()     at Microsoft.SharePoint.WebControls.PeopleEditor.SearchFromGC(SPActiveDirectoryDomain domain, String strFilter, String[] rgstrProp, Int32 nTimeout, Int32 nSizeLimit, SPUserCollection spUsers, ArrayList& rgResults)     at Microsoft.SharePoint.Utilities.SPUserUtility.SearchAgainstAD(String input, Boolean useUpnInResolve, SPActiveDirectoryDomain domainController, SPPrincipalType scopes, SPUserCollection usersContainer, Int32 maxCount, String customQuery, String customFilter, TimeSpan searchTimeout, Boolean& reachMaxCount)     at Microsoft.SharePoint.Utilities.SPActiveDirectoryPrincipalResolver.SearchPrincipals(String input, SPPrincipalType scopes, SPPrincipalSource sources, SPUserCollection usersContainer, Int32 maxCount, Boolean& reachMaxCount)     at Microsoft.SharePoint.Utilities.SPUtility.SearchPrincipalFromResolvers(List`1 resolvers, String input, SPPrincipalType scopes, SPPrincipalSource sources, SPUserCollection usersContainer, Int32 maxCount, Boolean& reachMaxCount, Dictionary`2 usersDict).   1c99d69c-fd6c-d086-2e71-662fc7a6ad20

Thanks for Help.


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 },...]


Q: XSLT 2.0 creating incremental footnote numbers in HTML output through multi-stage transformation This question builds on the responses to my original question, where it was suggested that I post a followup. This concerns attempting to integrate the XSL code from the previous post.
In the previous question I presented a simplified version of the TEI:XML document I am transforming into HTML using XSLT 2.0 (the full tei file and current xslt can be found here https://xsltfiddle.liberty-development.net/bdxtqT/6). This is a fuller view of the hierarchy, but not all details:
<tei>
 <teiHeader/>
 <text>
   <front/>

       <seg type="typefoo" corresp="#foo601" xml:id="foo361">
         <date type="deposition_date" when="1245">Idus
         marcii</date>In non hendrerit metus. Sed in posuere
         eros, sit amet pharetra lacus.</seg>
       <seg type="typefoo" xml:id="foo362">Nullam semper varius
         justo, vitae mollis turpis dapibus sit amet.
         Donec<note type="public_note">note content</note>
         rhoncus tempor urna sit amet imperdiet.</seg>
       <seg type="typefoo" xml:id="foo363">Integer
         id ante nunc. Curabitur at ligula sed arcu consequat
         gravida et id orci. Morbi quis porta dolor.</seg>
       <seg type="typefoo" corresp="#fooid2">Sed dictum<note
         type="public_note">note content 2</note> sem nec urna sodales
         cursus. Donec sit amet nibh tempor, congue ligula semper,
         rhoncus odio.</seg>

   <back>

       <seg>
       <seg>

       <seg>
       <seg>

   </back>
 </text>
<tei>

The desired HTML output is as follows. Incremental footnote numbers are created in  based on one of three conditions:

*

*date[@type="deposition_date"] (add footnote no.),

*seg[@type="typefoo"] (add footnote no.)

*note[@type="public_note"] (replace with footnote no.).
Desired output

Idus marcii1In non hendrerit metus. Sed in
       posuere eros, sit amet pharetra lacus.
2

Nullam semper varius justo, vitae mollis turpis
       dapibus sit amet. Donec3 rhoncus tempor
       urna sit amet imperdiet.

Integer id ante nunc. Curabitur at ligula sed
       arcu consequat gravida et id orci. Morbi quis porta
       dolor.

Sed dictum sem4 nec urna sodales cursus.
      Donec sit amet nibh tempor, congue ligula semper,
      rhoncus odio.
5

  [...]

1 1245

2 foo601

3 note here

4 note here

5 fooid2

The full XSLT transformation document is found at https://xsltfiddle.liberty-development.net/bdxtqT/6, where one can see the following problems:

*

*date[@type='deposition_date'] is being entirely replaced, instead receiving an added footnote marker

*seg[@type='dep_event' and @corresp] is not receiving an added footnote marker, but it appears in the
 at the bottom of the page.

The XSL file is too long and doesn't seem to paste here correctly. Interact with files here https://xsltfiddle.liberty-development.net/bdxtqT/6.
NB: I am restricted to XSLT 2.0 as this transformation is fired off inside eXist-DB with Xquery 3.1.
Thanks very much!

A: I think, unless you want to prefix all your paths in that template matching / with the variable I suggested to store the result of the marker insertion, one way to merge the existing code with my suggestion is to change the match from / to /* e.g. use
<xsl:template match="/*">

Latin

            <xsl:apply-templates select="//tei:body//tei:p"/>

English

            <xsl:apply-templates select="//tei:back//tei:p[@xml:lang='EN']"/>

            <xsl:if test="//tei:back//tei:p[@xml:lang='FR']">

French

                <xsl:apply-templates select="//tei:back//tei:p[@xml:lang='FR']"/>
            </xsl:if>

               <xsl:if test="$footnote-sources">

                     <xsl:apply-templates select="$footnote-sources" mode="build_footnotes"/>

               </xsl:if>

</xsl:template>

that would then mean that my suggestion to use
<xsl:template match="/">
    <xsl:apply-templates select="$fn-markers-added/node()"/>
</xsl:template>

can be kept and the XSLT processor would apply it.
There is however the use of that variable $footnote-sources at the end of the template, as far as I can see from the snippet its use on nodes from the original input document would not be affected by the introduction of a temporary result adding markers but somehow to me it would feel wrong to at that place keep processing the original input while the rest works on the temporary result so I would be inclined to change the variable declaration to
<xsl:variable name="footnote-sources" select="$fn-markers-added/tei:text//tei:seg//date[@type='deposition_date'] |
    $fn-markers-added/tei:text//tei:seg//note[@type='public_note'] | $fn-markers-added/tei:text//tei:seg[@corresp]"/>

With those two changes I think my suggestion in the previous answer should then be applied. Although now looking again at the posted source with a tei root element I wonder how a global variable having paths starting with tei:text would select anything but perhaps that is an omission in the sample.


Q: Nginx gives an Internal Server Error 500 after I have configured basic auth I am trying to do basic auth on Nginx. I have version 1.9.3 up and running on Ubuntu 14.04 and it works fine with a simple html file.
Here is the html file:
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title></title>
</head>
<body>
  "Some shoddy text"
</body>
</html>

And here is my nginx.conf file:
user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    include /etc/nginx/conf.d/*.conf;
    server {
        listen 80;
        server_name 192.168.1.30;
        location / {
            root /www;
            index index.html;
            auth_basic "Restricted";
            auth_basic_user_file /etc/users;
        }
    }
}

I used htpasswd to create two users in the "users" file under /etc (username "calvin" password "Calvin", and username "hobbes" password "Hobbes"). It's encrypted by looks like this:
calvin:$apr1$Q8LGMfGw$RbO.cG4R1riIfERU/175q0
hobbes:$apr1$M9KoUUhh$ayGd8bqqlN989ghWdTP4r/

All files belong to root:root. The server IP address is 192.168.1.30 and I am referencing that directly in the conf file.
It all works fine if I comment out the two auth lines and restart nginx, but if I uncomment them, then I do indeed get the username and password prompts when I try to load the site, but immediately thereafter get an Error 500 Internal Server error which seems to persist and I have to restart nginx.
Anybody can see what I'm doing wrong here? I had the same behaviour on the standard Ubuntu 14.04 apt-get version of Nginx (1.4.something) so I don't think it's the nginx version.

A: Not really an answer to your question as you are using MD5. However as this thread pops up when searching for the error, I am attaching this to it.
Similar errors happen when bcrypt is used to generate passwords for auth_basic:
htpasswd -B <file> <user> <pass>

Since bcrypt is not supported within auth_basic ATM, mysterious 500 errors can be found in nginx error.log, (usually found at /var/log/nginx/error.log), they look something like this:
*1 crypt_r() failed (22: Invalid argument), ...
At present the solution is to generate a new password using md5, which is the default anyway.
Edited to address md5 issues as brought up by @EricWolf in the comments:
md5 has its problems for sure, some context can be found in the following threads

*

*Is md5 considered insecure?

*Is md5 still considered secure for single use authentications?
Of the two, speed issue can be mitigated by using fail2ban, by banning on failed basic auth you'll make online brute forcing impractical (guide). You can also use long passwords to try and fortify a bit as suggested here.
Other than that it seems this is as good as it gets with nginx...

A: I was running Nginx in a Docker environment and I had the same issue. The reason was that some of the passwords were generated using bcrypt. I resolved it by using nginx:alpine.

A: Do you want a MORE secure password hash with nginx basic_auth? Do this:
echo "username:"$(mkpasswd -m sha-512) >> .htpasswd

SHA-512 is not considered nearly as good as bcrypt, but it's the best nginx supports at the moment.

A: I will just stick the htpassword file under "/etc/nginx" myself.
Assuming it is named htcontrol, then ...
sudo htpasswd -c /etc/nginx/htcontrol calvin
Follow the prompt for the password and the file will be in the correct place.
location / {
    ...

    auth_basic "Restricted";
    auth_basic_user_file htcontrol;
}

or auth_basic_user_file /etc/nginx/htcontrol; but the first variant works for me

A: I had goofed up when initially creating a user.  As a result, the htpasswd file looked like:
user:
user:$apr1$passwdhashpasswdhashpasswdhash...

After deleting the blank user, everything worked fine.

A: I just had the same problem - after checking log as suggested by @Drazen Urch I've discovered that the file had root:root permissions - after changing to forge:forge (I'm using Forge with Digital Ocean) - the problem went away.

A: Well, just use correct RFC 2307 syntax:
passwordvalue          = schemeprefix encryptedpassword
schemeprefix           = "{" scheme "}"
scheme                 = "crypt" / "md5" / "sha" / altscheme
altscheme              = "x-" keystring
encryptedpassword      = encrypted password

For example: sha1 for helloworld for admin will be

*

*admin:{SHA}at+xg6SiyUovktq1redipHiJpaE=
I had same error cause i wrote {SHA1} what against RFC syntax. When i fixed it - all worked like a charm. {sha} will not work too. Only correct {SHA}.

A: First, check out your nginx error logs:
tail -f /var/log/nginx/error.log

In my case, I found the error:
[crit] 18901#18901: *6847 open() "/root/temp/.htpasswd" failed (13: Permission denied),

The /root/temp directory is one of my test directories, and cannot be read by nginx. After change it to /etc/apache2/ (follow the official guide https://docs.nginx.com/nginx/admin-guide/security-controls/configuring-http-basic-authentication/) everything works fine.
===
After executing the ps command we can see the nginx worker process maintained by the user www-data, I had tried to chown www-data:www-data /root/temp to make sure www-data can access this file, but it still not working. To be honest, I don't have a very deep understanding on Linux File Permissions, so I change it to /etc/apache2/ to fix this in the end. And after a test, you can put the .htpasswd file in other directories which in /etc (like /etc/nginx).

A: I too was facing the same problem while setting up authentication for kibana. Here is the error in my /var/log/nginx/error.log file

2020/04/13 13:43:08 [crit] 49662#49662: *152 crypt_r() failed (22:
  Invalid argument), client: 157.42.72.240, server: 168.61.168.150,
  request: “GET / HTTP/1.1”, host: “168.61.168.150”

I resolved this issue by adding authentication using this.
sudo sh -c "echo -n 'kibanaadmin:' >> /etc/nginx/htpasswd.users"
sudo sh -c "openssl passwd -apr1 >> /etc/nginx/htpasswd.users"

You can refer this post if you are trying to setup kibana and got this issue.
https://medium.com/@shubham.singh98/log-monitoring-with-elk-stack-c5de72f0a822?postPublishedType=repub

A: In my case, I was using plain text password by -p flag, and coincidentally my password start with $ character.
So I updated my password and thus the error was gone.
NB: Other people answer helped me a lot to figure out my problem. I am posting my solution here if anyone stuck in a rare case like me.

A: In my case, I had my auth_basic setup protecting an nginx location that was served by a proxy_pass configuration.
The configured proxy_pass location wasn't returning a successful HTTP200 response, which caused nginx to respond with an Internal Server Error after I had entered the correct username and password.
If you have a similar setup, ensure that the proxy_pass location protected by auth_basic is returning an HTTP200 response after you rule out username/password issues.


Q: How can I get one neighbourhood name using address and/or postal code? this is my first time here.
I just need to get a neighbourhood/locality name, to get it I have the address and postal code (all over Argentina). -no polygons needed-
This is to change a background image acording to its neighbourhood/locality, this does not need to be a 100% accurate about neighbourhood/locality limits

A: You might try the International Address Verification API from SmartyStreets.com. Having never been to Argentina I'm not very familiar with their neighborhood system but here is some output from the API which some locality information, and a corresponding Google map:
Input:

El Tupe No 4950
Partido de la Matanza
Provincia de Buenos Aires, Argentina

International API Output:
[
   {
      "address1":"El Tupe 4950",
      "address2":"Ciudad Evita – Partido De 1778 Ciudad Evita",
      "address3":"B1778 La Matanza",
      "components":{
         "administrative_area":"Buenos Aires",
         "building":"Ciudad Evita – Partido De",
         "dependent_locality":"Ciudad Evita",
         "country_iso_3":"ARG",
         "locality":"La Matanza",
         "postal_code":"B1778",
         "postal_code_short":"B1778",
         "premise":"4950",
         "premise_number":"4950",
         "thoroughfare":"El Tupe",
         "sub_building_number":"1778"
      },
      "metadata":{
         "max_geocode_precision":"Premise"
      },
      "analysis":{
         "verification_status":"Verified",
         "address_precision":"Thoroughfare",
         "max_address_precision":"DeliveryPoint"
      }
   }
]

Map

*

*Google Map zoomed to show the address and the surrounding neighborhoods
What this input/output and corresponding map show is that Cuidad Evita (the dependant_locality value) is more fine-grained neighborhood information provided by the API (which seems to be what you are asking for). The only question is whether that information is fine-grained enough for your use case.

*

*Documentation for the International API from SmartyStreets

Full disclosure: I'm a developer at SmartyStreets, an address verification API provider.


Q: Why does this LinkedList addLast implementation work? I am working on adding an item to the end of a linked list (this isn't homework...just an exercise for myself).
Here is the program:
public class CustomLinkedList {

    private static Node head = null;
    private int size = 0;

    public static void main(String[] args) {
        CustomLinkedList myList = new CustomLinkedList();
        myList.add(5);
        myList.add(9);
        myList.add(3);

        System.out.println("List Size: " + myList.size);
        myList.print();
    }

    private int size() {
        return this.size;
    }

    private void print() {
            Node temp = head;
           for (int i=0; i<=size-1;i++){
                System.out.print(temp.value + " ");
                temp = temp.next;
            }
        System.out.println();
    }

    private void add(int value) {
        if (head == null) {
            head = new Node();
            head.value = value;
            head.next = null;
            size++;
        } else {
            Node temp = head;
            while (temp.next != null) {
                temp = temp.next;
            }
            temp.next = new Node();
            (temp.next).value = value;
            size++;
        }
    }
}

Here is my Node class:
public class Node {
    public int value;
    public Node next;

    public int getValue(){
        return this.value;
    }
}

Here is what I think is happening:
1. I have an original/ongoing list starting with "head."
2. I want to add to that list.
3. To add to it, I need to find the end of it. I do that by creating a new node called temp (which is just a copy of the original list).
4. I traverse the copy (temp) until I reached the end.
5. Once I reach the end, I create a new node.
To me, this is where my code stops. Now, in my mind, I need to add code that says, "Alright, you have your new node, you know where it needs to go, so lets go through the real list and add it."
But I don't have that. According to my debugger (image below), the right thing is happening, but I don't see the magic that is adding the new node to the original list. How is this working?

Edit:
I did look at other implementations (like the one here); it looked very similar. However, I still couldn't find why it works without assigning temp to head (or to head.next). I get Linked Lists in theory I believe. I just don't understand why this bit works.

A: Your confusion is that temp is different to head. It's not.
They are both variables holding references to the same Node object. Changes made via either variable are reflected in the (same) object they reference. When you add a Node to temp, you add it to the real list.


Q: Can I do anything with this LCD? I doubt it Right, so I have ripped the 1.7" (ish) TFT module out of an HP PhotoSmart C4780.  Despite HP's best efforts I can plainly see that it is made by AUO.  No model number on it though.
Now, I have never had anything to do with TFT screens before now, but I want to have a play.
The screen has a single mylar strip connector, and I can see which of the connections break off to the back-light, so that's not a problem.
From what I can see the rest of it doesn't need anything 'special' - the board it normally plugs into is powered by a PIC16F727, so it must be possible for me to interface it to some other PIC instead (I have a selection to hand).
But how do I get started?  I don't even know what connections to expect there to be on the mylar strip, and how to work out what should be where.
I have found some AUO data sheets, but none for a 1.7", only 1.5" and 2" and upwards, though I have identified one possible 1.7" model - A017CN01, but I can't find a data sheet for it anywhere.
Any pointers would be most appreciated.

****Update:****
I think I may have just found a data sheet for this device - I'm still none the wiser though...
I see it has a serial data (SPI-like) interface to it - ideal for PIC usage.  Nothing in the data sheet about how to use it.  Would this interface be likely to be common to all AUO devices?

A: You may (or not) may have found a datasheet. Unless you can find back the ID numbers on the actual device there's no way to tell with absolute certainty. Checking dimensional properties is the first job. If dimensions differ, it may be at best a variant, but also there: no certainty.
If you're confident enough that you have the right datasheet, scrutinize it. This may not be a pleasant task, especially when a datasheet has several hundreds of pages, but here the most interesting parts are easy to spot: the timing diagrams on pages 14 and 15 reveal a lot. Like the VSYNC and HSYNC. They tell you that this isn't a device with its own intelligence and memory, but rather that you have to drive it like a video signal, doing the refreshing yourself.
OTOH, like you said there are also the SDA and SCL connections, which hint at I2C, though the (again) timing diagram page 29 shows that it's more SPI-like (It lacks the I2C starting sequence). The pages following show that the serial interface isn't used for image data, but to program configuration registers.

A: Video data is fed into the screen by drawing with a cursor based on HSYNC and VSYNC signals. These indicate the next row and next column. A 8-bit databus indicates the color data. Because this is 8-bits and colours are usually 16-bit or 24-bit, it means you need to have 2 or 3 periods of DCLK (data color clock) to draw 1 pixel. The datasheet even talks abuot having a dummy value to clear the pixel.
A PIC16F is incapable of doing this. The DCLK needs to be between 16 and 27MHz. At DCLK @ 23040kHz (23.04MHz) you can get a refresh rate of 50Hz, which is kinda a minimum for display quality. HSYNC and VSYNC are dependant on how the screen is drawn; top-bottom or left-right. It may be that HSYNC is 23.04MHz/4=5.76MHz and VSYNC is 23.04MHz/4/480=12kHz.
In other words, the PIC16F probably connects to some kind of internal bus (may be a UART or something else) so a main controller can easily speak to it. The PIC16F is probably used to configure contrast, backlight values etc.


Q: Setting fs.default.name in core-site.xml Sets HDFS to Safemode I installed the Cloudera CDH4 distribution on a single machine in pseudo-distributed mode and successfully tested that it was working correctly (e.g. can run MapReduce programs, insert data on the Hive server, etc.) However, if I chance the core-site.xml file to have fs.default.name set to machine name rather than localhost and restart the NameNode service, the HDFS enters safe-mode.
Before the change of fs.default.name, I ran the following to check the state of the HDFS:
$ hadoop dfsadmin -report
...
Configured Capacity: 18503614464 (17.23 GB)
Present Capacity: 13794557952 (12.85 GB)
DFS Remaining: 13790785536 (12.84 GB)
DFS Used: 3772416 (3.60 MB)
DFS Used%: 0.03%
Under replicated blocks: 2
Blocks with corrupt replicas: 0
Missing blocks: 0

Then I made the modification to core-site.xml (with the machine name being hadoop):
<property>
  <name>fs.default.name</name>
  <value>hdfs://hadoop:8020</value>
</property>

I restarted the service and reran the report.
$ sudo service hadoop-hdfs-namenode restart
$ hadoop dfsadmin -report
...
Safe mode is ON
Configured Capacity: 0 (0 B)
Present Capacity: 0 (0 B)
DFS Remaining: 0 (0 B)
DFS Used: 0 (0 B)
DFS Used%: NaN%
Under replicated blocks: 0
Blocks with corrupt replicas: 0
Missing blocks: 0

An interesting note is that I can still perform some HDFS commands. For example, I can run
$ hadoop fs -ls /tmp

However, if I try to read a file using hadoop fs -cat or try to place a file in the HDFS, I am told the NameNode is in safemode.
$ hadoop fs -put somefile .
put: Cannot create file/user/hadinstall/somefile._COPYING_. Name node is in safe mode.

The reason I need the fs.default.name to be set to the machine name is because I need to communicate with this machine on port 8020 (the default NameNode port). If fs.default.name is left to localhost, then the NameNode service will not listen to external connection requests.
I am at a loss as to why this is happening and would appreciate any help.

A: The issue stemmed from domain name resolution. The /etc/hosts file needed to be modified to point the IP address of the machine of the hadoop machine for both localhost and the fully qualified domain name.
192.168.0.201 hadoop.fully.qualified.domain.com localhost

A: Safemode is an HDFS state in which the file system is mounted read-only; no replication is performed, nor can files be created or deleted. Filesystem operations that access the filesystem metadata like 'ls' in you case will work.
The Namenode can be manually forced to leave safemode with this command( $ hadoop dfsadmin -safemode leave).Verify status of safemode with ( $ hadoop dfsadmin -safemode get)and then run dfsadmin report to see if it shows data.If after getting out of safe mode the report  still dose not show any data then i'm suspecting communication between namenode and datanode is not hapenning. Check namenode and datanode logs after this step.
The next steps could be to try restarting datanode process and last resort will be to format namenode which will result in loss of data.


Q: Returning a value based on date of return Please I need help.
I have a column called "Date_Of_Return". I want to create a calculated field to return "SMP" if the arrival date is greater than "01-11-2021" and return "JI" if otherwise.
I came up with this but it's not working effectively.
Any help will do please.
SMP = IF('NEW EUTF UPDATED PORTAL II'[Date_Of_Return] >= DATEVALUE("01-11-2021"),"SMP","JI"())

A: Try using below formula for your calculated column:
=IF([Date_Of_Return] > DATE(2021,11,1), "SMP", "JI")

Where DATE(2021,11,1) is in format: DATE(yyyy,mm,dd)
Note:

*

*Sometimes comma(,) does not work in formula (I am not sure but it is based on something language or regional settings on your site). So in that case use semicolon(;) instead of comma(,).

Official Documentations:

*

*Calculated Field Formulas.

*IF function.


Q: Checkbox styling Is there a way to style a checkbox and a label with border, so the user can see only the label (the checkbox is hidden), and when the user clicks on the label, the label will change the color of the background and the text? This click should also work as clicking on the checkbox.
If there is a way, how should I do this?
or
How to hide the checkbox and leave only the label do the work with changing colors?

A: Put them side to side (in html structure) and use the adjacent sibling selector +
Something like this
html
<input type="checkbox" id="box1" />
<label for="box1">checkbox #1</label>

css
input[type="checkbox"]{
    position:absolute;
    visibility:hidden;
    z-index:-1;
}
input[type="checkbox"]:checked + label{
    color:red;
}

you could style the label (2nd rule) as you want of course..
demo at http://jsfiddle.net/kb67J/1/


Q: Multiple Nuxt3 custom modules disable each other I developed 2 custom modules, let's say module1 and module2.
module1 uses addImports (to auto-import composable and utils) and module2 uses addComponent (to, obviously, auto-import some components) along a components list in directory ./runtime/components.
// module1
addImports([
  {
    from: resolve(runtimeDir, 'composables/useFoo'),
    name: 'useFoo',
    as: 'useFoo'
  }
]);

// module2
const components = fs.readdirSync(resolve('./runtime/components')).map((component: string) => {
  return component.split('.').slice(0,-1).join('.');
});
// components = [ 'Component1', 'Component2' ]
components.map((component: string) => {
  addComponent({
    name: component,
    filePath: resolve(`./runtime/components/${component}.vue`),
    global: true
  });
});

After publishing both and testing by installing them in a test Nuxt3 project, it appears that they work fine individualy, but as soon as I add both in nuxt.config.ts file's modules array, the first one in the array break the second one:
// In test project
// addCOmponents of module2 does not work
modules: [
  'module1',
  'module2'
]

// addImports of module1 does not work properly
modules: [
  'module2',
  'module1'
]

I have no idea what i can do or what I am doing wrong :/
Can someone help please ?