text:
Q: Require is not defined when using import (VSCode) I am trying to import a JS file into another JS file. However, whenever I try to use the import command, it throws the "Require not defined" problem. What could be the problem?
index.html File:

        <link rel="stylesheet" href="style.css">

Header.js File:
export default function Header() {
    return (

<button onClick={changePage(1)}>Mines</button>

<button onClick={changePage(2)}>Forest</button>

<button onClick={changePage(3)}>Smith</button>

<button onClick={changePage(4)}>Build</button>

    )
}

main.js File:
import Header from "./components/Header"

function Page() {
    return (

    )
}

// React Render
const rootDiv = document.getElementById("root");
ReactDOM.render(<Page />, rootDiv)

I tried using:

*

*tsconfig.json and jsconfig.json: I saw that some compilers may transform the import command to require, so I created this and added allowSyntheticDefaultImports to true. Nothing changed.

*webpacks-config: I also downloaded the webpacks extension from Visual Studio Code to see if it would help too. Nothing changed.

*Importing as a type="module" in HTML: I tried using the  tag in HTML, but it didnt work either.


text:
Q: How to move AntD Menu Submenu Arrow to the front to the menu name How can I move the submenu expand arrow showing in the below image to the front?

A: To override antd styles, 1st we need to inspect the elements and identify which styles/classNames applied. Then override these styles as we want.
In this scenario, Wrap your <Menu/> component from a div as below and apply below styles to div.
<div className="menuMain">
  <Menu
    onClick={onClick}
    style={{
      width: 256
    }}
    defaultSelectedKeys={["1"]}
    defaultOpenKeys={["sub1"]}
    mode="inline"
    items={items}
  />
</div>

CSS
.menuMain > ant-menu-submenu-expand-icon,
.ant-menu-submenu-arrow {
    right: 240px;
 }

Check here for codesandbox example.

redpajama_set_name: RedPajamaStackExchange


text:
Q: placed the div between the StickyContainer component to make it sticky
*

*I am trying to make a div sticky in react.

*so I included the package react-sticky.

*and placed the div between the StickyContainer component.

*I dont see any errors but still its not working.

*Can you tell me how to fix it, so that in future I will fix it myself.

*Providing my sandbox and code snippet below.

https://codesandbox.io/s/0prxxxvy0n
class App extends React.Component {
  render() {
    console.log("App---->");
    return (
      <StickyContainer>
        {/* Other elements can be in between `StickyContainer` and `Sticky`,
        but certain styles can break the positioning logic used. */}

          I am sticky------------------------------------------------------->

        <Sticky>
          {({
            style,

            // the following are also available but unused in this example
            isSticky,
            wasSticky,
            distanceFromTop,
            distanceFromBottom,
            calculatedHeight
          }) => {}}
        </Sticky>
        <SearchBar />

I am sticky

        <WholeText />
        <UploadDocuments />
        <VerticalLinearStepper />
        {/* ... */}
      </StickyContainer>
    );
  }
}

A: As the documentation says, you need to put your div within the render callback of the  component, i.e.
class App extends React.Component {
  render() {
    console.log("App---->");
    return (
      <StickyContainer>
        <Sticky>
          {({ style }) =>
I am sticky
}
        </Sticky>
        <SearchBar />

I am sticky

        <WholeText />
        <UploadDocuments />
        <VerticalLinearStepper />
        {/* ... */}
      </StickyContainer>
    );
  }
}

A "render callback" in this case just means that the child of the <Sticky> component needs to be a function that returns what should be rendered. This allows the parent to pass additional information to use in the rendering of the child via the arguments of the function. The syntax for specifying a function as a child is:
<Parent>{/*function goes here*/}</Parent>

In the example above, the function part is ({ style }) =>
I am sticky
 which assumes the parameter that will be passed to the function will be an object with a style property and then the function returns a div element using that style.
If you look at the react-sticky code you'll find that in its render method it does the following:
  const element = React.cloneElement(
      this.props.children({
        isSticky: this.state.isSticky,
        wasSticky: this.state.wasSticky,
        distanceFromTop: this.state.distanceFromTop,
        distanceFromBottom: this.state.distanceFromBottom,
        calculatedHeight: this.state.calculatedHeight,
        style: this.state.style
      }),
      {
        ref: content => {
          this.content = ReactDOM.findDOMNode(content);
        }
      }
    );

When it calls this.props.children(...), that executes the function you specified as a child and you can see that the last property on the object it passes to the function is the style property.


text:
Q: Retaining data in HTML form I have an HTML form. Let's say I fill out all the fields and submit it (PHP script runs here).
Then I want to go back to the form using "Back" button of my browser.
What I see is the empty form.
What do I do to have the entered data retain on the page after I come back to it using "Back" button of the browser?
Thank you!

A: If you use the "Back" button of your browser then your browser is responsible for re-populating your form data.

A: Usually that functionality is handled by the browser, however if you want to "force" the fields to always be pre-filled with the user's data, you can store the $_POST data in a session variable and use that to load the form.
Example:
// submission page
session_start();
if(isset($_POST)){
  // save the posted data in the session
  $_SESSION["POST"] = $_POST;
}

Then on the actual form page, you can check to see if session data exists. It won't if the form is being loaded the first time, but it will if the user submits the form and then presses the browser back button:
// form page
session_start();
if(isset($_SESSION["POST"])){
  // previous POST data has been saved
  // build the form with pre-defined values from $_SESSION
  ...
} else {
  // no previous data
  // build the form without pre-defined values
  ...
}

Note that you must call session_start() before outputting any HTML.

A: Store the value in a session
session_start();

//form so that you have all the potential forms in a single session array
//form_1 to identify the form in question

if(!empty($_POST)){
$_SESSION['forms']['form_1'] = $_POST;//if this is for the public internet, then I would really consider making sure that the posted data matches the received data... (and that its comming from YOUR form), which is way too long to post here...
}

then on the form page
<input name="flowers" value="<?php echo if(isset($_SESSION['forms']['forms_1']['flowers'])){ echo htmlspecialchars($_SESSION['forms']['forms_1']['flowers']);} ?>" />

obviously the above can be simplified, but for a example's sake it's better this way.
(make sure to clean out the old form data eventually)

A: You can potentially store the data in the session, and re-populate it back using PHP sessions. You should create a separate back button that takes you to the previous page.
Example:
Storing data:
$_SESSION['data'] = $_POST['item1'];

In the HTML Forms:
<input type="text" name="someinput" value="<?=$_SESSION['data']?>" />


text:
Q: define x-axe for time series data I would like to plot time series data. I have generated my data with this code:
PlotDataKanada <- ts(SortDataKanada[SortDataKanada$`Influenza Season and Epidemiological Week`>=201101 & SortDataKanada$`Influenza Season and Epidemiological Week`<201401,]$TotalPatienten, frequency = 52, start = 2011, end = 2014)

and then plot it:
plot(PlotDataKanada,type="l",ylab="Number of Patients")

My data in PlotDataKanada:
Time Series:
Start = c(2011, 1)
End = c(2014, 1)
Frequency = 52
  [1] 1323 1147 1145 1008  986 1034  958  816  789  692  499  427  406
 [14]  374  306  183  162  109   71   41   32    8    2    3    2    1
 [27]    2    3    2    2    2    2   NA    1    4    3    2    2    3
 [40]    6    6    2   10   14    8   13   26   15   30   72   64  102
 [53]  121  130  148  189  234  273  328  528  811  990 1128 1049  737
 [66]  605  626  590  369  345  231  179  113   58   33   27   16   11
 [79]    3    7    3   10    1    2    2    4    6    2    8    4   10
 [92]   24   14   31   83  126  185  302  389  843 1611 2528 3217 3729
[105] 2832 1805 1203  940  747  576  518  525  486  449  388  398  340
[118]  393  347  309  260  182   95   61   31   16    1    7   28    7
[131]    6   14   14   12   38   39   57  122  100  165  229  443  787
[144] 1313 1323 1147 1145 1008  986 1034  958  816  789  692  499  427
[157]  406

on x-axis I see float values 2011.0,2011.5,...
But I would like to have only integer values: 2011,2012,...
How should I change my code?

A: A very quick solution would be this:
plot(PlotDataKanada,type="l",ylab="Number of Patients", xaxt= "n")
axis(1, seq(2011,2014))


text:
Q: Sorting/Ordering a BlockingCollecion What would be the best way to sort the items in a BlockingCollection<T> based on their values in a particular order. I know there is an OrderBy method, can it be utilized to achieve ordering?

A: It sounds like you need to order the items in the queue according to some comparison criteria. That's basically a Priority Queue.
There is a way to use a priority queue with a BlockingCollection<T>. You have to write a Priority Queue that implements IProducerConsumerCollection and pass an instance of that queue to the appropriate BlockingCollection constructor.
Fortunately, Microsoft have provided sample code that demonstrates how to do this. It also includes the source code for a simple priority queue.
There are many other priority queue implementations available on line, for example here. You would, however, have to modify them to implement IProducerConsumerCollection, which is unlikely to be a trivial task.
[EDIT] I found a concurrent priority queue that implements IProducerConsumerCollection - you should be able to use it.

A: Check this https://msdn.microsoft.com/en-us/library/bb534966(v=vs.110).aspx
From MSDN:
class Pet
{
    public string Name { get; set; }
    public int Age { get; set; }
}

public static void OrderByEx1()
{
    Pet[] pets = { new Pet { Name="Barley", Age=8 },
                   new Pet { Name="Boots", Age=4 },
                   new Pet { Name="Whiskers", Age=1 } };

    IEnumerable<Pet> query = pets.OrderBy(pet => pet.Age);

    foreach (Pet pet in query)
    {
        Console.WriteLine("{0} - {1}", pet.Name, pet.Age);
    }
}

/*
 This code produces the following output:

 Whiskers - 1
 Boots - 4
 Barley - 8
*/


text:
Q: How to fix a segmentaion fault in a C program?
Possible Duplicate:
Segmentation fault

Currently I am upgrading an open source program used for HTTP streaming. It needs to support the latest FFMPEG.
The code compiles fine with no warnings although I am getting a segmentation fault error.
I would like to know how to fix the issue? and / or the best way to debug? Please find attached a portion of the code due to size. I will try to add the project to github :) Thanks in advance!
Sample Usage
# segmenter --i out.ts --l 10 --o stream.m3u8 --d segments --f stream

Makefile
FFLIBS=`pkg-config --libs libavformat libavcodec libavutil`
FFFLAGS=`pkg-config --cflags libavformat libavcodec libavutil`

all:
    gcc -Wall -g segmenter.c -o segmenter ${FFFLAGS} ${FFLIBS}

segmenter.c
/*
 * Copyright (c) 2009 Chase Douglas
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License version 2
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <unistd.h>
#include "libavformat/avformat.h"

#include "libavformat/avio.h"

#include <sys/stat.h>

#include "segmenter.h"
#include "libavformat/avformat.h"

#define IMAGE_ID3_SIZE 9171

void printUsage() {
    fprintf(stderr, "\nExample: segmenter --i infile --d baseDir --f baseFileName --o playListFile.m3u8 --l 10 \n");
    fprintf(stderr, "\nOptions: \n");
    fprintf(stderr, "--i <infile>.\n");
    fprintf(stderr, "--o <outfile>.\n");
    fprintf(stderr, "--d basedir, the base directory for files.\n");
    fprintf(stderr, "--f baseFileName, output files will be baseFileName-#.\n");
    fprintf(stderr, "--l segment length, the length of each segment.\n");
    fprintf(stderr, "--a,  audio only decode for < 64k streams.\n");
    fprintf(stderr, "--v,  video only decode for < 64k streams.\n");
    fprintf(stderr, "--version, print version details and exit.\n");
    fprintf(stderr, "\n\n");
}

void ffmpeg_version() {
    // output build and version numbers
    fprintf(stderr, "  libavutil version:   %s\n", AV_STRINGIFY(LIBAVUTIL_VERSION));
    fprintf(stderr, "  libavutil build:     %d\n", LIBAVUTIL_BUILD);
    fprintf(stderr, "  libavcodec version:  %s\n", AV_STRINGIFY(LIBAVCODEC_VERSION));
    fprintf(stdout, "  libavcodec build:    %d\n", LIBAVCODEC_BUILD);
    fprintf(stderr, "  libavformat version: %s\n", AV_STRINGIFY(LIBAVFORMAT_VERSION));
    fprintf(stderr, "  libavformat build:   %d\n", LIBAVFORMAT_BUILD);
    fprintf(stderr, "  built on " __DATE__ " " __TIME__);
#ifdef __GNUC__
    fprintf(stderr, ", gcc: " __VERSION__ "\n");
#else
    fprintf(stderr, ", using a non-gcc compiler\n");
#endif
}

static AVStream *add_output_stream(AVFormatContext *output_format_context, AVStream *input_stream) {
    AVCodecContext *input_codec_context;
    AVCodecContext *output_codec_context;
    AVStream *output_stream;

    output_stream = avformat_new_stream(output_format_context, 0);
    if (!output_stream) {
        fprintf(stderr, "Segmenter error: Could not allocate stream\n");
        exit(1);
    }

    input_codec_context = input_stream->codec;
    output_codec_context = output_stream->codec;

    output_codec_context->codec_id = input_codec_context->codec_id;
    output_codec_context->codec_type = input_codec_context->codec_type;
    output_codec_context->codec_tag = input_codec_context->codec_tag;
    output_codec_context->bit_rate = input_codec_context->bit_rate;
    output_codec_context->extradata = input_codec_context->extradata;
    output_codec_context->extradata_size = input_codec_context->extradata_size;

    if (av_q2d(input_codec_context->time_base) * input_codec_context->ticks_per_frame > av_q2d(input_stream->time_base) && av_q2d(input_stream->time_base) < 1.0 / 1000) {
        output_codec_context->time_base = input_codec_context->time_base;
        output_codec_context->time_base.num *= input_codec_context->ticks_per_frame;
    } else {
        output_codec_context->time_base = input_stream->time_base;
    }

    switch (input_codec_context->codec_type) {
#ifdef USE_OLD_FFMPEG
        case CODEC_TYPE_AUDIO:
#else
        case AVMEDIA_TYPE_AUDIO:
#endif
            output_codec_context->channel_layout = input_codec_context->channel_layout;
            output_codec_context->sample_rate = input_codec_context->sample_rate;
            output_codec_context->channels = input_codec_context->channels;
            output_codec_context->frame_size = input_codec_context->frame_size;
            if ((input_codec_context->block_align == 1 && input_codec_context->codec_id == CODEC_ID_MP3) || input_codec_context->codec_id == CODEC_ID_AC3) {
                output_codec_context->block_align = 0;
            } else {
                output_codec_context->block_align = input_codec_context->block_align;
            }
            break;
#ifdef USE_OLD_FFMPEG
        case CODEC_TYPE_VIDEO:
#else
        case AVMEDIA_TYPE_VIDEO:
#endif
            output_codec_context->pix_fmt = input_codec_context->pix_fmt;
            output_codec_context->width = input_codec_context->width;
            output_codec_context->height = input_codec_context->height;
            output_codec_context->has_b_frames = input_codec_context->has_b_frames;

            if (output_format_context->oformat->flags & AVFMT_GLOBALHEADER) {
                output_codec_context->flags |= CODEC_FLAG_GLOBAL_HEADER;
            }
            break;
        default:
            break;
    }

    return output_stream;
}

int write_index_file(const char index[], const char tmp_index[], const unsigned int planned_segment_duration, const unsigned int actual_segment_duration[],
        const char output_directory[], const char output_prefix[], const char output_file_extension[],
        const unsigned int first_segment, const unsigned int last_segment) {
    FILE *index_fp;
    char *write_buf;
    unsigned int i;

    index_fp = fopen(tmp_index, "w");
    if (!index_fp) {
        fprintf(stderr, "Could not open temporary m3u8 index file (%s), no index file will be created\n", tmp_index);
        return -1;
    }

    write_buf = malloc(sizeof (char) * 1024);
    if (!write_buf) {
        fprintf(stderr, "Could not allocate write buffer for index file, index file will be invalid\n");
        fclose(index_fp);
        return -1;
    }

    unsigned int maxDuration = planned_segment_duration;

    for (i = first_segment; i <= last_segment; i++)
        if (actual_segment_duration[i] > maxDuration)
            maxDuration = actual_segment_duration[i];

    snprintf(write_buf, 1024, "#EXTM3U\n#EXT-X-TARGETDURATION:%u\n", maxDuration);

    if (fwrite(write_buf, strlen(write_buf), 1, index_fp) != 1) {
        fprintf(stderr, "Could not write to m3u8 index file, will not continue writing to index file\n");
        free(write_buf);
        fclose(index_fp);
        return -1;
    }

    for (i = first_segment; i <= last_segment; i++) {
        snprintf(write_buf, 1024, "#EXTINF:%u,\n%s-%u%s\n", actual_segment_duration[i], output_prefix, i, output_file_extension);
        if (fwrite(write_buf, strlen(write_buf), 1, index_fp) != 1) {
            fprintf(stderr, "Could not write to m3u8 index file, will not continue writing to index file\n");
            free(write_buf);
            fclose(index_fp);
            return -1;
        }
    }

    snprintf(write_buf, 1024, "#EXT-X-ENDLIST\n");
    if (fwrite(write_buf, strlen(write_buf), 1, index_fp) != 1) {
        fprintf(stderr, "Could not write last file and endlist tag to m3u8 index file\n");
        free(write_buf);
        fclose(index_fp);
        return -1;
    }

    free(write_buf);
    fclose(index_fp);

    return rename(tmp_index, index);
}

int main(int argc, const char *argv[]) {
    //input parameters
    char inputFilename[MAX_FILENAME_LENGTH], playlistFilename[MAX_FILENAME_LENGTH], baseDirName[MAX_FILENAME_LENGTH], baseFileName[MAX_FILENAME_LENGTH];
    char baseFileExtension[5]; //either "ts", "aac" or "mp3"
    int segmentLength, outputStreams, verbosity, version;

    char currentOutputFileName[MAX_FILENAME_LENGTH];
    char tempPlaylistName[MAX_FILENAME_LENGTH];

    //these are used to determine the exact length of the current segment
    double prev_segment_time = 0;
    double segment_time;
    unsigned int actual_segment_durations[2048];
    double packet_time = 0;

    //new variables to keep track of output size
    double output_bytes = 0;

    unsigned int output_index = 1;
    AVOutputFormat *ofmt;
    AVFormatContext *ic = NULL;
    AVFormatContext *oc;
    AVStream *video_st = NULL;
    AVStream *audio_st = NULL;
    AVCodec *codec;
    int video_index;
    int audio_index;
    unsigned int first_segment = 1;
    unsigned int last_segment = 0;
    int write_index = 1;
    int decode_done;
    int ret;
    int i;

    unsigned char id3_tag[128];
    unsigned char * image_id3_tag;

    size_t id3_tag_size = 73;
    int newFile = 1; //a boolean value to flag when a new file needs id3 tag info in it

    if (parseCommandLine(inputFilename, playlistFilename, baseDirName, baseFileName, baseFileExtension, &outputStreams, &segmentLength, &verbosity, &version, argc, argv) != 0)
        return 0;

    if (version) {
        ffmpeg_version();
        return 0;
    }

    fprintf(stderr, "%s %s\n", playlistFilename, tempPlaylistName);

    image_id3_tag = malloc(IMAGE_ID3_SIZE);
    if (outputStreams == OUTPUT_STREAM_AUDIO)
        build_image_id3_tag(image_id3_tag);
    build_id3_tag((char *) id3_tag, id3_tag_size);

    snprintf(tempPlaylistName, strlen(playlistFilename) + strlen(baseDirName) + 1, "%s%s", baseDirName, playlistFilename);
    strncpy(playlistFilename, tempPlaylistName, strlen(tempPlaylistName));
    strncpy(tempPlaylistName, playlistFilename, MAX_FILENAME_LENGTH);
    strncat(tempPlaylistName, ".", 1);

    //decide if this is an aac file or a mpegts file.
    //postpone deciding format until later
    /*  ifmt = av_find_input_format("mpegts");
    if (!ifmt)
    {
    fprintf(stderr, "Could not find MPEG-TS demuxer.\n");
    exit(1);
    } */

    av_log_set_level(AV_LOG_DEBUG);

    av_register_all();
    ret = avformat_open_input(&ic, inputFilename, NULL, NULL);
    if (ret != 0) {
        fprintf(stderr, "Could not open input file %s. Error %d.\n", inputFilename, ret);
        exit(1);
    }

    if (avformat_find_stream_info(ic, NULL) < 0) {
        fprintf(stderr, "Could not read stream information.\n");
        exit(1);
    }

    oc = avformat_alloc_context();
    if (!oc) {
        fprintf(stderr, "Could not allocate output context.");
        exit(1);
    }

    video_index = -1;
    audio_index = -1;

    for (i = 0; i < ic->nb_streams && (video_index < 0 || audio_index < 0); i++) {
        switch (ic->streams[i]->codec->codec_type) {

#ifdef USE_OLD_FFMPEG
            case CODEC_TYPE_VIDEO:
#else
            case AVMEDIA_TYPE_VIDEO:
#endif
                video_index = i;
                ic->streams[i]->discard = AVDISCARD_NONE;
                if (outputStreams & OUTPUT_STREAM_VIDEO)
                    video_st = add_output_stream(oc, ic->streams[i]);
                break;
#ifdef USE_OLD_FFMPEG
            case CODEC_TYPE_AUDIO:
#else
            case AVMEDIA_TYPE_AUDIO:
#endif
                audio_index = i;
                ic->streams[i]->discard = AVDISCARD_NONE;
                if (outputStreams & OUTPUT_STREAM_AUDIO)
                    audio_st = add_output_stream(oc, ic->streams[i]);
                break;
            default:
                ic->streams[i]->discard = AVDISCARD_ALL;
                break;
        }
    }

    if (video_index == -1) {
        fprintf(stderr, "Stream must have video component.\n");
        exit(1);
    }

    //now that we know the audio and video output streams
    //we can decide on an output format.
    if (outputStreams == OUTPUT_STREAM_AUDIO) {
        //the audio output format should be the same as the audio input format
        switch (ic->streams[audio_index]->codec->codec_id) {
            case CODEC_ID_MP3:
                fprintf(stderr, "Setting output audio to mp3.");
                strncpy(baseFileExtension, ".mp3", strlen(".mp3"));
                ofmt = av_guess_format("mp3", NULL, NULL);
                break;
            case CODEC_ID_AAC:
                fprintf(stderr, "Setting output audio to aac.");
                ofmt = av_guess_format("adts", NULL, NULL);
                break;
            default:
                fprintf(stderr, "Codec id %d not supported.\n", ic->streams[audio_index]->id);
        }
        if (!ofmt) {
            fprintf(stderr, "Could not find audio muxer.\n");
            exit(1);
        }
    } else {
        ofmt = av_guess_format("mpegts", NULL, NULL);
        if (!ofmt) {
            fprintf(stderr, "Could not find MPEG-TS muxer.\n");
            exit(1);
        }
    }
    oc->oformat = ofmt;

    if (outputStreams & OUTPUT_STREAM_VIDEO && oc->oformat->flags & AVFMT_GLOBALHEADER) {
        oc->flags |= CODEC_FLAG_GLOBAL_HEADER;
    }

    /*  Deprecated: pass the options to avformat_write_header directly.
        if (av_set_parameters(oc, NULL) < 0) {
            fprintf(stderr, "Invalid output format parameters.\n");
            exit(1);
        }
     */

    av_dump_format(oc, 0, baseFileName, 1);

    //open the video codec only if there is video data
    if (video_index != -1) {
        if (outputStreams & OUTPUT_STREAM_VIDEO)
            codec = avcodec_find_decoder(video_st->codec->codec_id);
        else
            codec = avcodec_find_decoder(ic->streams[video_index]->codec->codec_id);
        if (!codec) {
            fprintf(stderr, "Could not find video decoder, key frames will not be honored.\n");
        }

        if (outputStreams & OUTPUT_STREAM_VIDEO)
            ret = avcodec_open2(video_st->codec, codec, NULL);
        else
            avcodec_open2(ic->streams[video_index]->codec, codec, NULL);
        if (ret < 0) {
            fprintf(stderr, "Could not open video decoder, key frames will not be honored.\n");
        }
    }

    snprintf(currentOutputFileName, strlen(baseDirName) + strlen(baseFileName) + strlen(baseFileExtension) + 10, "%s%s-%u%s", baseDirName, baseFileName, output_index++, baseFileExtension);

    if (avio_open(&oc->pb, currentOutputFileName, URL_WRONLY) < 0) {
        fprintf(stderr, "Could not open '%s'.\n", currentOutputFileName);
        exit(1);
    }
    newFile = 1;

    int r = avformat_write_header(oc,NULL);
    if (r) {
        fprintf(stderr, "Could not write mpegts header to first output file.\n");
        debugReturnCode(r);
        exit(1);
    }

    //no segment info is written here. This just creates the shell of the playlist file
    write_index = !write_index_file(playlistFilename, tempPlaylistName, segmentLength, actual_segment_durations, baseDirName, baseFileName, baseFileExtension, first_segment, last_segment);

    do {
        AVPacket packet;

        decode_done = av_read_frame(ic, &packet);

        if (decode_done < 0) {
            break;
        }

        if (av_dup_packet(&packet) < 0) {
            fprintf(stderr, "Could not duplicate packet.");
            av_free_packet(&packet);
            break;
        }

        //this time is used to check for a break in the segments
        //  if (packet.stream_index == video_index && (packet.flags & PKT_FLAG_KEY))
        //  {
        //    segment_time = (double)video_st->pts.val * video_st->time_base.num / video_st->time_base.den;
        //  }
#if USE_OLD_FFMPEG
        if (packet.stream_index == video_index && (packet.flags & PKT_FLAG_KEY))
#else
        if (packet.stream_index == video_index && (packet.flags & AV_PKT_FLAG_KEY))
#endif
        {
            segment_time = (double) packet.pts * ic->streams[video_index]->time_base.num / ic->streams[video_index]->time_base.den;
        }
        //  else if (video_index < 0)
        //  {
        //      segment_time = (double)audio_st->pts.val * audio_st->time_base.num / audio_st->time_base.den;
        //  }

        //get the most recent packet time
        //this time is used when the time for the final segment is printed. It may not be on the edge of
        //of a keyframe!
        if (packet.stream_index == video_index)
            packet_time = (double) packet.pts * ic->streams[video_index]->time_base.num / ic->streams[video_index]->time_base.den; //(double)video_st->pts.val * video_st->time_base.num / video_st->time_base.den;
        else if (outputStreams & OUTPUT_STREAM_AUDIO)
            packet_time = (double) audio_st->pts.val * audio_st->time_base.num / audio_st->time_base.den;
        else
            continue;
        //start looking for segment splits for videos one half second before segment duration expires. This is because the
        //segments are split on key frames so we cannot expect all segments to be split exactly equally.
        if (segment_time - prev_segment_time >= segmentLength - 0.5) {
            fprintf(stderr, "looking to print index file at time %lf\n", segment_time);
            avio_flush(oc->pb);
            avio_close(oc->pb);

            if (write_index) {
                actual_segment_durations[++last_segment] = (unsigned int) rint(segment_time - prev_segment_time);
                write_index = !write_index_file(playlistFilename, tempPlaylistName, segmentLength, actual_segment_durations, baseDirName, baseFileName, baseFileExtension, first_segment, last_segment);
                fprintf(stderr, "Writing index file at time %lf\n", packet_time);
            }

            struct stat st;
            stat(currentOutputFileName, &st);
            output_bytes += st.st_size;

            snprintf(currentOutputFileName, strlen(baseDirName) + strlen(baseFileName) + strlen(baseFileExtension) + 10, "%s%s-%u%s", baseDirName, baseFileName, output_index++, baseFileExtension);
            if (avio_open(&oc->pb, currentOutputFileName, URL_WRONLY) < 0) {
                fprintf(stderr, "Could not open '%s'\n", currentOutputFileName);
                break;
            }

            newFile = 1;
            prev_segment_time = segment_time;
        }

        if (outputStreams == OUTPUT_STREAM_AUDIO && packet.stream_index == audio_index) {
            if (newFile && outputStreams == OUTPUT_STREAM_AUDIO) {
                //add id3 tag info
                //fprintf(stderr, "adding id3tag to file %s\n", currentOutputFileName);
                //printf("%lf %lld %lld %lld %lld %lld %lf\n", segment_time, audio_st->pts.val, audio_st->cur_dts, audio_st->cur_pkt.pts, packet.pts, packet.dts, packet.dts * av_q2d(ic->streams[audio_index]->time_base) );
                fill_id3_tag((char*) id3_tag, id3_tag_size, packet.dts);
                avio_write(oc->pb, id3_tag, id3_tag_size);
                avio_write(oc->pb, image_id3_tag, IMAGE_ID3_SIZE);
                avio_flush(oc->pb);
                newFile = 0;
            }

            packet.stream_index = 0; //only one stream in audio only segments
            ret = av_interleaved_write_frame(oc, &packet);
        } else if (outputStreams & OUTPUT_STREAM_VIDEO) {
            if (newFile) {
                //fprintf(stderr, "New File: %lld %lld %lld\n", packet.pts, video_st->pts.val, audio_st->pts.val);
                //printf("%lf %lld %lld %lld %lld %lld %lf\n", segment_time, audio_st->pts.val, audio_st->cur_dts, audio_st->cur_pkt.pts, packet.pts, packet.dts, packet.dts * av_q2d(ic->streams[audio_index]->time_base) );
                newFile = 0;
            }
            if (outputStreams == OUTPUT_STREAM_VIDEO)
                ret = av_write_frame(oc, &packet);
            else
                ret = av_interleaved_write_frame(oc, &packet);
        }

        if (ret < 0) {
            fprintf(stderr, "Warning: Could not write frame of stream.\n");
        } else if (ret > 0) {
            fprintf(stderr, "End of stream requested.\n");
            av_free_packet(&packet);
            break;
        }

        av_free_packet(&packet);
    } while (!decode_done);

    //make sure all packets are written and then close the last file.
    avio_flush(oc->pb);
    av_write_trailer(oc);

    if (video_st && video_st->codec)
        avcodec_close(video_st->codec);

    if (audio_st && audio_st->codec)
        avcodec_close(audio_st->codec);

    for (i = 0; i < oc->nb_streams; i++) {
        av_freep(&oc->streams[i]->codec);
        av_freep(&oc->streams[i]);
    }

    avio_close(oc->pb);
    av_free(oc);

    struct stat st;
    stat(currentOutputFileName, &st);
    output_bytes += st.st_size;

    if (write_index) {
        actual_segment_durations[++last_segment] = (unsigned int) rint(packet_time - prev_segment_time);

        //make sure that the last segment length is not zero
        if (actual_segment_durations[last_segment] == 0)
            actual_segment_durations[last_segment] = 1;

        write_index_file(playlistFilename, tempPlaylistName, segmentLength, actual_segment_durations, baseDirName, baseFileName, baseFileExtension, first_segment, last_segment);

    }

    write_stream_size_file(baseDirName, baseFileName, output_bytes * 8 / segment_time);

    return 0;
}

A: What rudimentary debugging steps have you tried?  Have you run your code under gdb or a debugger to discover what line it is crashing on?  Or at the very least, added print statements to see how far into your program it is getting before the crash?
Start by compiling your source with the "-g" option in the compiler to add debugging symbols.  Then run your code under gdb.
valgrind is another useful tool that might help you find where your program is crashing if it's touching invalid memory.


text:
Q: Save cookie persistence var url:NSURL=NSURL(string:"http://xxxxxxxx/index.php?s=/Public_verify.html")!
var data:NSData=NSData(contentsOfURL: url)!
var img:UIImage=UIImage(data:data)!
self.Verify.setBackgroundImage(img, forState: UIControlState.Normal)

var username=UserName.text
var password=PassWord.text
var verifycode=VerifyCode.text

let url=NSURL(string:"http://xxxxxxxx/index.php?s=/Public_doLogin.html")!
let request = NSMutableURLRequest(URL: url)
        request.HTTPMethod = "POST"
let postString = "username=\(username)&password=\(password)&verifyCode=\(verifycode)&ajax=1"
        request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)

let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
            data, response, error in
              //cookie?
        }
        task.resume()

Code above, I used NSURLSession.sharedSession (). DataTaskWithRequest to POST login.
I quit APP, COOKIE disappears need to re-login
How to make cookie has been recorded, unless I log off the user?


text:
Q: Email attachments to unique recipients based on attachment name Good day,
I am an absolute newbie at using any form of scripting or programing so please forgive me if I don't provide enough information or context.
I need to email around 1000 PDF documents a day to various recipients.
We receive a request with a unique 9 digit reference number.
Each request is logged in a table which details the requestors email address and the reference number generated.
We then process the order and save the invoice with the same 9 digit reference number as a pdf.
I then need to open outlook,
attach the relevant document (named with the reference number),
add the relevant email address in the To: field, from the table.
Copy and paste a standard worded message and send to the client.
Doing this manually ofcourse takes time, and in some instances results in errors,
eg. reference number 1 gets sent to the wrong receipient.
we cannot add any new programs other than outlook to handle the process.
Any and all advice is appreciated.
Thanks in advance.

A: This really sounds like the need for a bit of programming.
It could quite easily be solved with VBA in Access or even in Excel.
It's not very complex but maybe not a job for an absolute newbie.


text:
Q: What is a good workflow for java with EJB, JSP, Servlet, and shared project, jQuery in eclipse/glassfish? I am attempting to learn java EE by developing an app from scratch.  What I have now is JSPs, EJBs, Servlets, jQuery script. I feel my progress is very slow right now.
I am afraid to consider JRebel-like tools at the moment.

*

*Is there a step by step cycle I can follow to be more efficient?

*When should I trigger the .reload file?

*When should I delete/restart glassfish, when I modify: java, jsp, jsp fragment, dependent project?

*Do I need to restart every time I modify a java file or only on major changes like add/remove class, add/remove method?

*Do I need to run in debug mode every time so I can immediately see my changes on the fly?

A: Since your last comment, I think maybe I understand a little better what you're after.
I know you're looking for a glassfish solution, which I don't know very well, but if you're willing to work with other application servers, there are some good solutions for fast turnaround.
The JBoss IDE is free and integrates tightly with the JBoss Application Server. If you use the default directory layouts created by the Eclipse project wizards, turnaround for most changes is completely transparent and nearly simultaneous. I think you can find other IDEs with similar characteristics. (BTW - I don't use JRebel myself but hear very good reports from those I know who do.)


text:
Q: MSDB is growing due to our sending database mail with attachments. Can I update MSDB system table 'attachment = NULL'? sysmail_attachments is growing and using a lot of space for backups. I don't want to keep what's in the attachment, just the record of the mail, including recipients and attachments.
I am considering running the below on our live system but don't know what effect it will have:
update dbo.sysmail_attachments
set attachment = null

Has anybody done this before? Can anyone think of potential problems?

A: Make a new logging table to store counts, then create a SQL Agent job that runs the aggregations of how many emails you sent, insert that to your logging table, then run sysmail_delete_mailitems_sp to clean up to msdb table. If your only need is to keep track of how many emails went out, this would be the safer option.
In fact, you might be able to get all the info you need from the Database Mail logs instead of the Database Mail tables. Get your counts from sysmail_log and then you can purge sysmail_mailitems. Double check this on a dev box.


text:
Q: Why 2 linux machine behave differently with command of the same syntax? I am using 2 machine , which is both Red Hat Enterprise Linux AS release 3 (Taroon Update 2)
 ( I check it in /etc/*-release ).
I checked they are using the same default shell by ps -p $$, which is bash.
I tried to execute a find command with wildcard pattern:
find path -name pattern -type f -ctime +3
and the pattern contain * character as wildcard.
The first machine seems to expanded the wildcard character and causing error:
find /home/primbat/testing -name sftp_bcs_report_*.log -type f -ctime +7
find: paths must precede expression

and I need to either make the pattern in between 2 delimited qoute, e.g: \"sftp_bcs_report_*.log\" or using set -f in the script to suppress wildcard expansion.
Which in the other machine, it have no such problem. Do you have any idea?

A: Sounds like there is no file matching sftp_bcs_report_*.log in the starting directory on the second machine and more than one such file on the first server.  For using find, patterns should always be quoted.

A: By default, shells expand wildcards if a file matches them but keep unexpanded without match. For example, if you run touch /tmp/111; touch /tmp/11* this will create and then update mtime on /tmp/111, but if /tmp is empty but you call touch /tmp/11* you will get file named "11*" in /tmp.
This is rather weird feature of shells. Sometimes proper expanding isn't possible without special hacks as intermediate function. Most current shells invent special options for typical cases; e.g. "shopt -s failglob" in bash rejects it from running any command where wildcard match fails.
One shall rely on find's wildcard expanding, so such pattern shall be quoted against expansion in shell:
find /home/primbat/testing -name 'sftp_bcs_report_*.log' -type f -ctime +7

(note single quotes). With zero or one file, it works, but with two or more files you get broken command syntax and it complains - this is what is said by colleague Arcege. Your "set -f" disables expansion totally - well, it is good measure for diagnostics but can give underwater rakes for a future moving. Quotes are simpler:)


text:
Q: Android layout confusing Here is my capture picture:

And here is my code:

<RelativeLayout
    android:id="@+id/wrapper"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="left">

    <TextView
        android:id="@+id/timeIn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/messageIn"
        android:layout_gravity="center"
        android:layout_marginTop="15dip"
        android:text="23:23"/>

    <TextView
        android:id="@+id/messageIn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_margin="5dip"
        android:background="@drawable/bubble_yellow"
        android:paddingLeft="10dip"
        android:text="HIHIHIHIHIHI" />

</RelativeLayout>

However, if the text "HIHIHIHIHIHI" changes to "HIHIHIHIHIHIHIHIHIHIHIHIHIHIHIHIHIHI":
the time will missing and the bubble will fill parent

How can I do so that the time will still to the right of the bubble even the text is mult-line?

A: Try this
<RelativeLayout
    android:id="@+id/wrapper"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="left">

    <TextView
        android:id="@+id/timeIn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="15dip"
        android:layout_alignParentRight="true"
        android:text="23:23"/>

    <TextView
        android:id="@+id/messageIn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_margin="5dip"
        android:background="@drawable/bubble_yellow"
        android:layout_toLeftOf="@+id/timeIn"
        android:layout_alignParentLeft="true"
        android:paddingLeft="10dip"
        android:text="HIHIHIHIHIHI" />

</RelativeLayout>

To work for small texts also (To resize the width of messageIn according to message) and time to appear right of message (not right aligned)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/wrapper"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:weightSum="1.0" >

<LinearLayout
    android:id="@+id/lin_lay1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="1.0" >

    <TextView
        android:id="@+id/messageIn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_margin="5dip"
        android:background="@drawable/bubble_yellow"
        android:paddingLeft="10dip"
        android:text="HIHIHI" />
</LinearLayout>

<LinearLayout
    android:id="@+id/lin_lay2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="0.1" >

    <TextView
        android:id="@+id/timeIn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="15dip"
        android:padding="5dp"
        android:text="23:23" />
</LinearLayout>

</LinearLayout>

A: Use android:maxwidth in your textview.

A: A solution is to set the android:maxWidth="" property of your "messageIn" TextView. On runtime - get the width of the device screen, the width of the "timeIn" TextView and set the difference (screen width - timeIn width) with setMaxWidth(int maxpixels) method of TextView.
See how to get screen size here
See how to get GUI object size here

A: make use of layout_weight it will take only assigned space and will not cover time textview.
<LinearLayout
    android:id="@+id/wrapper"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:weightsum="1">

    <TextView
        android:id="@+id/timeIn"
        android:layout_width="0dip"
        android:layout_height="wrap_content"
        android:layout_weight="0.7"
        android:layout_gravity="center"
        android:layout_marginTop="15dip"
        android:text="23:23"/>

    <TextView
        android:id="@+id/messageIn"
        android:layout_width="0dip"
        android:layout_height="wrap_content"
        android:layout_weight="0.3"
        android:layout_margin="5dip"
        android:background="@drawable/bubble_yellow"
        android:paddingLeft="10dip"
        android:text="HIHIHIHIHIHI" />

</LinearLayout>

A: You can do it in two ways:-

*

*You can use Linear Layout and set its  android:orientation="horizontal" and you need to fix the layout_width for a Textview.

*Concatinate time with TextView in the code.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/wrapper"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
 <TextView
 android:id="@+id/messageIn"
 android:layout_width="200dp"
 android:layout_height="wrap_content"
 android:text="HIHIHIHIdsfffffffffffffffffffffffffffffffffffffffffffffHIHI" />
<TextView
 android:id="@+id/timeIn"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_marginTop="5dp"
 android:text="23:23"/>

 </LinearLayout>


text:
Q: Stochastic Gradient Descent (SGD) algorithm explanation I am new to machine learning and am currently trying to understand the Stochastic Gradient Descent (SGD) algorithm.
$$
w := w - \eta\nabla Q_i(w)
$$
As I understand it so far $Q_i(w)$ is what is going to be estimated - $i$ being the current dataset under observation.
Can anyone help break down what the equation means?
Thank you

A: I am not sure how much you know, but basically SGD is trying to find the best $w$, by minimizing $Q$. Generally, $Q$ is an error function; thus, by following the gradient direction in the space of values of $w$, we are going towards to the $w$ that minimizes the error. More concretely, if you consider linear regression or perceptron classification, $w$ specifies the weight parameters of the model and $Q(w)$ is a measure of the error that the model makes on the data.
To make sure you understand, normal gradient descent is written:
$$
w \leftarrow w - \eta \nabla Q(w)
$$
where the error objective is written (with its gradient):
$$
Q(w) = \frac{1}{n}\sum_i Q_i(w)\;\;\;\;\implies\;\;\;\; \nabla Q(w) = \frac{1}{n}\sum_i \nabla Q_i(w)
$$
Let's break it down: rewriting as an iteration via $w_{t+1}=w_t - \eta \nabla Q(w_t)$ makes it a bit easier to see. Basically, $w$ is is the machine learning model (i.e. its parameters, which determine its behaviour). So, given some $w_t$, we will add some small vector to it (or take a small step, if you prefer), to move in the direction of the optimal $w_*$ (which specifies the model with the least $Q$). The size of the step is determined by the $\eta\in\mathbb{R}$ parameter. Then, the direction is determined by the gradient of $Q$. (Note that when the gradient is zero, all the partial derivatives of $Q$ with respect to $w$ have vanished, meaning we have reached a minimum. If you are confused as to why the gradient is the direction of steepest descent, see here).
Now for the stochastic part:
do you see a possible problem with the regular method? Imagine $n$ is enormous, and/or $\nabla Q(w)$ is complex (e.g. in deep neural networks). Then, computationally, evaluating $\nabla Q(w)$ may be very costly.
The common solution is to just estimate $\nabla Q$, instead of actually calculating it. The obvious and simplest method is to pick a random $j$ and use $\nabla Q \approx \nabla Q_j$ or (perhaps better) a minibatch (note indeed even that $\mathbb{E}_j[\nabla Q_j]=\nabla Q$).
This has another benefit, beyond computational efficiency, in that it helps avoid local minima in the error function, which "real" gradient descent could get stuck in.
See also here.


text:
Q: Integrating TinyMCE to Django So i have been trying to use tinymce on my django project but i kept getting: ImportError: cannot import name 'TinyMCE' from 'tinymce' and Cannot find reference TinyMCE in init.py
The very few articles online talks about integrating tinymce with django admin but i'm trying to integrate it with my django forms.
pip installed django-tinymce
settings.py:
INSTALLED_APPS = [ 'tinymce',]

urls.py:
path('tinymce/', include('tinymce.urls')),

models.py:
from tinymce.models import HTMLField

container_description = HTMLField()

forms.py
from tinymce import TinyMCE

class TinyMCEWidget(TinyMCE):
    def use_required_attribute(self, *args):
        return False

class ContainerForm(forms.ModelForm):
    container_serial_number = forms.CharField(widget=forms.TextInput(attrs=
                          {'placeholder': 'Enter serial number'}))
    container_description = forms.CharField(required=False,
                          widget=TinyMCEWidget(attrs={'placeholder': 'Enter
                          description'}), max_length=100)

Followed instructions online for setting up but i still got ImportError. And what else am i supposed to do to set TinyMCE up?

A: You need to replace:
from tinymce import TinyMCE

with:
from tinymce.widgets import TinyMCE

as per the example in the documentation.


text:
Q: Getting the last n elements of a vector. Is there a better way than using the length() function? If, for argument's sake, I want the last five elements of a 10-length vector in Python, I can use the - operator in the range index like so:
>>> x = range(10)
>>> x
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> x[-5:]
[5, 6, 7, 8, 9]
>>>

What is the best way to do this in R? Is there a cleaner way than my current technique, which is to use the length() function?
> x <- 0:9
> x
 [1] 0 1 2 3 4 5 6 7 8 9
> x[(length(x) - 4):length(x)]
[1] 5 6 7 8 9
>

The question is related to time series analysis btw where it is often useful to work only on recent data.

A: The disapproval of tail here based on speed alone doesn't really seem to emphasize that part of the slower speed comes from the fact that tail is safer to work with, if you don't for sure that the length of x will exceed n, the number of elements you want to subset out:
x <- 1:10
tail(x, 20)
# [1]  1  2  3  4  5  6  7  8  9 10
x[length(x) - (0:19)]
#Error in x[length(x) - (0:19)] :
#  only 0's may be mixed with negative subscripts

Tail will simply return the max number of elements instead of generating an error, so you don't need to do any error checking yourself.  A great reason to use it.  Safer cleaner code, if extra microseconds/milliseconds don't matter much to you in its use.

A: You can do exactly the same thing in R with two more characters:
x <- 0:9
x[-5:-1]
[1] 5 6 7 8 9

or
x[-(1:5)]

A: How about rev(x)[1:5]?
x<-1:10
system.time(replicate(10e6,tail(x,5)))
 user  system elapsed
 138.85    0.26  139.28

system.time(replicate(10e6,rev(x)[1:5]))
 user  system elapsed
 61.97    0.25   62.23

A: Here is a function to do it and seems reasonably fast.
endv<-function(vec,val)
{
if(val>length(vec))
{
stop("Length of value greater than length of vector")
}else
{
vec[((length(vec)-val)+1):length(vec)]
}
}

USAGE:
test<-c(0,1,1,0,0,1,1,NA,1,1)
endv(test,5)
endv(LETTERS,5)

BENCHMARK:
                                                    test replications elapsed relative
1                                 expression(tail(x, 5))       100000    5.24    6.469
2 expression(x[seq.int(to = length(x), length.out = 5)])       100000    0.98    1.210
3                       expression(x[length(x) - (4:0)])       100000    0.81    1.000
4                                 expression(endv(x, 5))       100000    1.37    1.691

A: I just add here something related. I was wanted to access a vector with backend indices, ie writting something like tail(x, i) but to return x[length(x) - i + 1] and not the whole tail.
Following commentaries I benchmarked two solutions:
accessRevTail <- function(x, n) {
    tail(x,n)[1]
}

accessRevLen <- function(x, n) {
  x[length(x) - n + 1]
}

microbenchmark::microbenchmark(accessRevLen(1:100, 87), accessRevTail(1:100, 87))
Unit: microseconds
                     expr    min      lq     mean median      uq     max neval
  accessRevLen(1:100, 87)  1.860  2.3775  2.84976  2.803  3.2740   6.755   100
 accessRevTail(1:100, 87) 22.214 23.5295 28.54027 25.112 28.4705 110.833   100

So it appears in this case that even for small vectors, tail is very slow comparing to direct access

A: see ?tail and ?head for some convenient functions:
> x <- 1:10
> tail(x,5)
[1]  6  7  8  9 10

For the argument's sake : everything but the last five elements would be :
> head(x,n=-5)
[1] 1 2 3 4 5

As @Martin Morgan says in the comments, there are two other possibilities which are faster than the tail solution, in case you have to carry this out a million times on a vector of 100 million values. For readibility, I'd go with tail.
test                                        elapsed    relative
tail(x, 5)                                    38.70     5.724852
x[length(x) - (4:0)]                           6.76     1.000000
x[seq.int(to = length(x), length.out = 5)]     7.53     1.113905

benchmarking code :
require(rbenchmark)
x <- 1:1e8
do.call(
  benchmark,
  c(list(
    expression(tail(x,5)),
    expression(x[seq.int(to=length(x), length.out=5)]),
    expression(x[length(x)-(4:0)])
  ),  replications=1e6)
)


text:
Q: Why is my Unity 2D character not flipping? My character is moving just fine. But it is not flipping. Is there anything wrong in my script?
It's my first time developing a demo game for practice, so I would be glad if someone helps me.
public class movement2 : MonoBehaviour
{
    public float speed = 100;

    void Start()
    {
    }

    void Update()
    {
        var inputX = Input.GetAxis("Horizontal");
        Vector3 movement = new Vector3(inputX, 0, 0)*speed;
        movement *= Time.deltaTime;
        transform.Translate(movement);

        Vector2 CharacterScale = transform.localScale;

        if (inputX < 0)
        {
            CharacterScale.x = -1;
        }

        if (inputX > 0)
        {
            CharacterScale.x = 1;
        }
    }
}

A: Because you don't assign the value of transform.localscale you just change the local variable.
    if (inputX < 0)
    {
        transform.localScale = new Vector3(-1, transform.localScale.y, transform.localScale.z);
    }

    if (inputX > 0)
    {
        transform.localScale = new Vector3(1, transform.localScale.y, transform.localScale.z);
    }


text:
Q: Good data structure to use for range counting uniques? I'v been learning about k-d trees for storing data and performing range counts in n-dimensional space. I was wondering if there are other data structures that would work well for counting unique values along some dimesion. So, for example, say I have some purchase data that looks like:
{ "name" : "Bill", "paid_amount" : 10.00 }
{ "name" : "Anne", "paid_amount" : 3.00 }
{ "name" : "Carl", "paid_amount" : 15.00 }
{ "name" : "Bill", "paid_amount" : 8.00 }
...

and I want to find out how many people (e.g. unique "names") made a purchase greater than 10. Any ideas?

A: Here's an article on efficient data structures for unique counting (and tradeoffs for size and accuracy).
StreamLib's source, documentation and fairly active mailing list are a good resource as well.


text:
Q: 403 forbidden using wss4jOutInterceptor with camel and cxf First things first:

*

*War with camel and cxf (tried latests versions and actually trying with 2.12.0 and 2.7.6 respectively).

*A simple camel route without process, just from - log - to.

*The final goal is to add WS-Security to a SOAP message.

Configuration:
application-context.xml
<!-- Import for camel config and beans -->
<import resource="./cxf-beans-testws.xml" />
<import resource="./camel-testws.xml" />

camel-testws.xml
<!-- CAMEL CONTEXT -->
<camelContext id="camelContextTest" xmlns="http://camel.apache.org/schema/spring">
    <!-- CAMEL ROUTE -->
    <route id="TestWSRoute">
        <description>
            Camel route for testws
        </description>
        <from uri="cxf:bean:serviceTestProvider" />
        <log message="Process" loggingLevel="DEBUG" />
        <to uri="cxf:bean:serviceTestClient" />
    </route>
</camelContext>

cxf-beans-testws.xml (just the relevant part)
<bean id="wss4JOutInterceptorRea" class="org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor">
    <constructor-arg>
        <map>
            <entry key="action" value="Encrypt Signature"/>
            <entry key="useSingleCertificate" value="true" />
            <entry key="user" value="xxxx" />
            <entry key="signaturePropRefId" value="signaturePropertiesBean" />
            <entry key="signaturePropertiesBean" value-ref="signaturePropertiesTest" />
            <entry key="signatureUser" value="${test.signature.certificate.alias}" />
            <entry key="passwordCallbackRef" value-ref="clientCallbackTest" />
            <entry key="signatureAlgorithm" value="http://www.w3.org/2000/09/xmldsig#rsa-sha1" />
            <entry key="signatureKeyIdentifier" value="DirectReference" />
            <entry key="signatureParts" value="{Element}{http://schemas.xmlsoap.org/soap/envelope/}Body" />
            <entry key="encryptionUser" value="${test.encryption.certificate.alias}" />
            <entry key="encryptionPropRefId" value="encryptionPropertiesBean" />
            <entry key="encryptionPropertiesBean" value-ref="encryptionPropertiesTest" />
        </map>
    </constructor-arg>
</bean>

When I call the web service exposed (serviceTestProvider), the SOAP message comes in, the log appears and the WSS configuration is placed. Then the message is sent to the endPoint... and always returns:
HTTP response '403: Forbidden' when communicating with http://...

If I remove the wss4jOutInterceptor, then the response is that there is no wss security (expected response).
But if I put log level to DEBUG, take the Outbound message from the log after all the interceptor chain handling and send it manually from REST Console or SoapUI... then works OK, no 403. So it seems that the message is well formed. Both calls are made from the same computer and without proxy or similar.
2016-06-17 08:59:12 INFO  WSTestCXFService:234 - Outbound Message
---------------------------
ID: 4
Address: http://correct-ws-url
Http-Method: POST
Content-Type: text/xml;charset=UTF-8
Headers: {Accept=[text/xml;charset=UTF-8], accept-encoding=[gzip,deflate], breadcrumbId=[ID-MACHINENAME-55387-1466145154908-1-4], Cache-Control=[No-Cache], Connection=[Keep-Alive], host=[correct-host], SOAPAction=[method], User-Agent=[Apache-HttpClient/4.1.1 (java 1.5)]}
Payload: <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><SOAP-ENV:Header xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"><wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" soap:mustUnderstand="1">...</wsse:Security></SOAP-ENV:Header><soap:Body xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="id-5"><xenc:EncryptedData xmlns:xenc="http://www.w3.org/2001/04/xmlenc#" Id="ED-4" Type="http://www.w3.org/2001/04/xmlenc#Content">...</xenc:EncryptedData></soap:Body></soap:Envelope>

No https, just http endpoint. Tried with conduit to add headers just to match REST Console or SoapUI raw messages with no luck. Any guess?

A: Finally, it was a Windows/network problem. Some days later (2-3), no changes at all... it started working.


text:
Q: jQuery UI Accordion create event isn't firing I need to run some code after my jQuery UI accordion initializes. According to the documentation, I should be able to define a create event that runs when an accordion is created. But it never fires, even though the accordion is very successfully created.
$('#accordion').accordion({
    create: function(event, ui) { alert('This never fires'); },
});

I'm using jQuery 1.4.2 and UI 1.8.5. Any idea why this event may be not firing?

A: Turns out the problem is that jQuery UI 1.8.5 does not support the create: event. So you have to be using at least 1.8.9 in order to use it.
I wish the jQuery UI documentation had some reference to what version these features were added to.


text:
Q: Linux serial port listener and interpreter? I'm using a serial device for a project, and what I'm trying to accomplish PC side, is listening for a command sent by the serial device, interpreting the query, running some code depending on the query, and transmitting back the result.
To be honest I tried out using PHP as the listener, and it works, unfortunately the infinite loop required to make the script act as a receiver, loads the CPU to 25%. So it's not really the best option.
I'm using cygwin right now, I'd like to create a bash script using linux native commands.
I can receive data by using:
cat /dev/ttyS2

And send a response with:
echo "command to send" > /dev/ttyS2

My question is, how do I make an automated listener to be able to receive and send data? The main issue I have, is actually how do I stop the cat /dev/ttyS2 command once information was received, put it into a variable which then I could compare with a switch, or a series of if else then blocks. Afterwards send back a response and start the cycle all over again?
Thanks

A: Is this not what you're looking for?
while read -r line < /dev/ttyS2; do
  # $line is the line read, do something with it
  # which produces $result
  echo $result > /dev/ttyS2
done

It's possible that reopening the serial device on every line has some side-effect, in which case you could try:
while read -r line; do
  # $line is the line read, do something with it
  # which produces $result
  echo $result > /dev/ttyS2
done < /dev/ttyS2

You could also move the output redirection, but I suspect you will have to turn off stdout buffering.

A: To remain fairly system independent, use a cross platform programming language: like Python, use a cross platform serial library like : pySerial and do the processing inside a script. I have used pySerial and I could run the script cross platform with almost no changes in source code. By using BASH you're limiting yourself a fair little.

A: If you use right tools, it is possible to actually have your CPU usage to be exactly 0 when your device does not have any output.
To accomplish this, you should use some higher level language (Perl, Python, C/C++ would do, but not bash) and use select loop on top of file handle of your serial device. This is an example for Perl http://perldoc.perl.org/IO/Select.html, but you can use any other language as long as it has support for select() syscall.

A: I would recommend to use C/C++ with Qt 5.1.1, it's really easy and if you are familiar with the framework it'll be a piece of cake!!!
Here you can find more information and here more helpful examples, give it a try,
it's really pain free!! Also you can develop on win and then port your code to linux...straight forward.
Declare an object like this:
QSerialPort mPort; //remember to #include <QtSerialPort/QSerialPort>
//also add QT += serialport to your .pro file

Then add this code:
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent)
{
    setupUi(this);

    connect(this->pushButton,SIGNAL(clicked()),this,SLOT(sendData()));

    mPort.setPortName("ttyS0");
    mPort.setBaudRate(QSerialPort::Baud115200);
    mPort.setParity(QSerialPort::EvenParity);

    if(!mPort.open(QSerialPort::ReadWrite))
    {
        this->label->setText(tr("unable to open port, %1").arg(mPort.error()));
    }

    connect(&(this->mPort),SIGNAL(readyRead()),this,SLOT(readData()));
}

void MainWindow::sendData()
{

    QByteArray data = lineEdit->text().toLatin1();
    if(mPort.isOpen())
    {
        mPort.write(data);
    }
    else
    {
        this->label->setText(tr("port closed %1").arg( mPort.error()));

    }
}

void MainWindow::readData()
{

    QString newData;
    int bread=0;
    while(bread < mPort.bytesAvailable() ){
        newData += mPort.readAll();
        bread++;
    }
  this->textEdit->insertPlainText("\n" + newData);
}


text:
Q: Get the new square InfoWindows with Google Maps? I'm building a website that's primarily function is a map search and displays professional wrestling events happening across the UK. I'm using v3 of the Google Maps JavaScript API to achieve this, but I have a question about why my app's InfoWindows look different to the InfoWindows on maps.google.co.uk.
Compare the following two screen-shots. Mine:

And the Google Maps website:

Why does the Google Maps website have squared InfoWindows, and why does my app using the latest version of the Google Maps JavaScript API have rounded InfoWindows?

A: Martin,
I've gone to the Google Maps API demos and found this demo:
http://gmaps-samples-v3.googlecode.com/svn/trunk/geocoder/v3-geocoder-tool.html#q%3D42.032974%2C-90.703125
You should see the squared InfoWindow.
I looked under the hood and found the code below, could be the bounds overlay of your window. Hope it helps.
var openInfoWindow = function(resultNum, result, marker) {
    return function() {
      if (selected != null) {
        document.getElementById('p' + selected).style.backgroundColor = "white";
        clearBoundsOverlays();
      }

      map.fitBounds(result.geometry.viewport);
      infowindow.setContent(getAddressComponentsHtml(result.address_components));
      infowindow.open(map, marker);

      if (result.geometry.bounds) {
        boundsOverlay = new google.maps.Rectangle({
          'bounds': result.geometry.bounds,
          'strokeColor': '#ff0000',
          'strokeOpacity': 1.0,
          'strokeWeight': 2.0,
          'fillOpacity': 0.0
        });
        boundsOverlay.setMap(map);
        google.maps.event.addListener(boundsOverlay, 'click', onClickCallback);
        document.getElementById('boundsLegend').style.display = 'block';
      } else {
        boundsOverlay = null;
      }

      viewportOverlay = new google.maps.Rectangle({
          'bounds': result.geometry.viewport,
          'strokeColor': '#0000ff',
          'strokeOpacity': 1.0,
          'strokeWeight': 2.0,
          'fillOpacity': 0.0
        });
      viewportOverlay.setMap(map);
      google.maps.event.addListener(viewportOverlay, 'click', onClickCallback);
      document.getElementById('viewportLegend').style.display = 'block';

      document.getElementById('p' + resultNum).style.backgroundColor = "#eeeeff";
      document.getElementById('matches').scrollTop =
        document.getElementById('p' + resultNum).offsetTop -
        document.getElementById('matches').offsetTop;
      selected = resultNum;
    }
  }

A: Just a small note. It seams that v2 of the API now has the squared info windows. I have the same question. But maybe it will be fixed automatically on v3 soon as well.


text:
Q: How to check whether the point is at end of visual line when `visual-line-mode` is on? (eolp) works only for "hard" line wraps, and I'd like to be able to check whether I'm at the end of screen line.  I'd think that looking at the source code of end-of-visual-line would help, but it didn't: it uses a built-in function vertical-motion, and digging into C sources is not something I'd prefer to do.  (Of course, I could save point position, go to end-of-visual-line, compare the point position with the saved one, but is there a better way?)
This would be quite useful, especially that I could hit C-t at the end of visual line and not be surprised;).

A: There may be a better way, but I think your idea to save point position and compare with point at the end of the visual line is reasonable.  Lots of things that behave like pure functions in Emacs actually work by changing state like this and restoring it on exit. The save-excursion special form is designed for this kind of pattern:
(defun end-of-visual-line-p ()
  (= (point)
     (save-excursion
       (end-of-visual-line)
       (point))))


text:
Q: Configure SSL Certificate on Apache for Django Application (mod_wsgi) I've purchased a SSL certificate from namecheap.com and placed the required files on my Ubuntu server (key & crt's). I'm using mod_wsgi to serve my Django application with Apache. I'm having issues installing the SSL certificate.
Current Configuration (/etc/apache2/sites-available/000-default.conf)
<VirtualHost *:80>
        ServerAdmin admin@example.com
        #DocumentRoot /var/www/html

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

        #Django Application
        Alias /static /home/Django/professor/static_root
        <Directory /home/Django/professor/static_root>
                Require all granted
        </Directory>
        <Directory /home/Django/professor/professor>
                <Files wsgi.py>
                        Require all granted
                </Files>
        </Directory>

        WSGIDaemonProcess professor python-path=/home/Django/professor:/home/Django/professor-vm/lib/python2.7/site-packages
        WSGIProcessGroup professor
        WSGIScriptAlias / /home/Django/professor/professor/wsgi.py

        #ServerName example.com
        #SSLEngine on
        #SSLCertificateFile /etc/apache2/ssl/server.crt
        #SSLCertificateKeyFile /etc/apache2/ssl/server.key
        #SSLCACertificateFile /etc/apache2/ssl/intermediate.crt

</VirtualHost>

I've commented out the lines for the SSL certificate. Currently, my application is running fine but when I uncomment the lines to enable to SSL certificate my site serves the files from /var/www and not the application. Any ideas?

A: Your problem is that your apache is only configured for port 80, hence it doesn't serve pages over https (port 443).
For this example I assume you want to serve your website only over https, so here is how your config should approximately look like.
Here is your: 000-default.conf
<VirtualHost *:80>
    ServerName example.com
    ServerAdmin admin@example.com

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

    # This is optional, in case you want to redirect people
    # from http to https automatically.
    RewriteEngine On
    RewriteCond %{SERVER_PORT} !^443$
    RewriteRule ^(.*)$ https://%{HTTP_HOST}$1 [R=301,L]

</VirtualHost>

Now here is default-ssl.conf:
<VirtualHost *:443>
    ServerName example.com
    ServerAdmin admin@example.com

    # Django Application
    Alias /static /home/Django/professor/static_root
    <Directory /home/Django/professor/static_root>
        Require all granted
    </Directory>

    <Directory /home/Django/professor/professor>
        <Files wsgi.py>
            Require all granted
        </Files>
    </Directory>

    WSGIDaemonProcess professor python-path=/home/Django/professor:/home/Django/professor-vm/lib/python2.7/site-packages
    WSGIProcessGroup professor
    WSGIScriptAlias / /home/Django/professor/professor/wsgi.py

    SSLEngine on
    SSLCertificateFile /etc/apache2/ssl/server.crt
    SSLCertificateKeyFile /etc/apache2/ssl/server.key
    SSLCACertificateFile /etc/apache2/ssl/intermediate.crt

</VirtualHost>

After configuration is done, we need to turn on the ssl site and (optionally) rewrite mod:
> sudo a2ensite default-ssl
> sudo a2enmod rewrite
> sudo service apache2 reload

A: to complete Alexey's answer, when i faced the problem i had to disable the 000-default.conf site and use only ssl configuration


text:
Q: Which sentence sounds better? Grammatical question about sentences I seriously can't tell which sounds natural in English. Need some help.

a) From tomorrow on, she'll be coming to our place to work with us.
b) She'll be coming to our place to work with us, from tomorrow on.

If there are better answers, suggestions, anything is welcome.
Not a must but preferable:

*

*I'd like to use them in casual conversations between friends.

*Shorter sentences will help. Long lines won't fit.

A: I hear sentences similar to the first one more often in a natural context, and indeed, that modifier you are adding is in regards to "she," so you want to make the modifier as close to the subject as possible for clarity. I would, however, in regards to what is natural, say "starting tomorrow" instead of "from tomorrow on"; the former is more casual.


text:
Q: Motion is taking an image every second even though it is setup not to I am running motion on a Raspberry Pi with a surplus Microsoft Xbox camera. To the best of my knowlege I have set it up to only take an image every 30 minutes and to also create a daily timelapse with the images. However from the second I start it, motion is taking an image every second or so and saving it to my snapshoots folder. I dont want this to happen! Of course I want the live feed visable via the web UI but I only want an image to be saved every half hour as well as the daily timelapse.
Here is what I belive are the relevant parts of my config files:
My /etc/motion/motion.conf: The entire thing is here: https://pastebin.com/32cZNeGU
# Maximum number of frames to be captured per second.
# Valid range: 2-100. Default: 100 (almost no limit).
framerate 100

# Minimum time in seconds between capturing picture frames from the camera.
# Default: 0 = disabled - the capture rate is given by the camera framerate.
# This option is used when you want to capture images at a rate lower than 2 per second.
minimum_frame_time 0

############################################################
# Motion Detection Settings:
############################################################

# Threshold for number of changed pixels in an image that
# triggers motion detection (default: 1500)
threshold 9999

# Automatically tune the threshold down if possible (default: off)
threshold_tune off

# Noise threshold for the motion detection (default: 32)
noise_level 32

# Automatically tune the noise threshold (default: on)
noise_tune on

# Despeckle motion image using (e)rode or (d)ilate or (l)abel (Default: not defined)
# Recommended value is EedDl. Any combination (and number of) of E, e, d, and D is valid.
# (l)abeling must only be used once and the 'l' must be the last letter.
# Comment out to disable
despeckle_filter EedDl

# Detect motion in predefined areas (1 - 9). Areas are numbered like that:  1 2 3
# A script (on_area_detected) is started immediately when motion is         4 5 6
# detected in one of the given areas, but only once during an event.        7 8 9
# One or more areas can be specified with this option. Take care: This option
# does NOT restrict detection to these areas! (Default: not defined)
; area_detect value

# PGM file to use as a sensitivity mask.
# Full path name to. (Default: not defined)
; mask_file value

# Dynamically create a mask file during operation (default: 0)
# Adjust speed of mask changes from 0 (off) to 10 (fast)
smart_mask_speed 0

# Ignore sudden massive light intensity changes given as a percentage of the picture
# area that changed intensity. Valid range: 0 - 100 , default: 0 = disabled
lightswitch 0

# Picture frames must contain motion at least the specified number of frames
# in a row before they are detected as true motion. At the default of 1, all
# motion is detected. Valid range: 1 to thousands, recommended 1-5
minimum_motion_frames 1

# Specifies the number of pre-captured (buffered) pictures from before motion
# was detected that will be output at motion detection.
# Recommended range: 0 to 5 (default: 0)
# Do not use large values! Large values will cause Motion to skip video frames and
# cause unsmooth movies. To smooth movies use larger values of post_capture instead.
pre_capture 0

# Number of frames to capture after motion is no longer detected (default: 0)
post_capture 0

# Event Gap is the seconds of no motion detection that triggers the end of an event.
# An event is defined as a series of motion images taken within a short timeframe.
# Recommended value is 60 seconds (Default). The value -1 is allowed and disables
# events causing all Motion to be written to one single movie file and no pre_capture.
# If set to 0, motion is running in gapless mode. Movies don't have gaps anymore. An
# event ends right after no more motion is detected and post_capture is over.
event_gap 60

# Maximum length in seconds of a movie
# When value is exceeded a new movie file is created. (Default: 0 = infinite)
max_movie_time 0

# Always save images even if there was no motion (default: off)
emulate_motion off

############################################################
# Image File Output
############################################################

# Output 'normal' pictures when motion is detected (default: on)
# Valid values: on, off, first, best, center
# When set to 'first', only the first picture of an event is saved.
# Picture with most motion of an event is saved when set to 'best'.
# Picture with motion nearest center of picture is saved when set to 'center'.
# Can be used as preview shot for the corresponding movie.
output_pictures off

# Output pictures with only the pixels moving object (ghost images) (default: off)
output_debug_pictures off

# The quality (in percent) to be used by the jpeg compression (default: 75)
quality 75

# Type of output images
# Valid values: jpeg, ppm (default: jpeg)
picture_type jpeg

############################################################
# FFMPEG related options
# Film (movies) file output, and deinterlacing of the video input
# The options movie_filename and timelapse_filename are also used
# by the ffmpeg feature
############################################################

# Use ffmpeg to encode movies in realtime (default: off)
ffmpeg_output_movies on

# Use ffmpeg to make movies with only the pixels moving
# object (ghost images) (default: off)
ffmpeg_output_debug_movies off

# Use ffmpeg to encode a timelapse movie
# Default value 0 = off - else save frame every Nth second
ffmpeg_timelapse 1800000

# The file rollover mode of the timelapse video
# Valid values: hourly, daily (default), weekly-sunday, weekly-monday, monthly, manual
ffmpeg_timelapse_mode daily

# Bitrate to be used by the ffmpeg encoder (default: 400000)
# This option is ignored if ffmpeg_variable_bitrate is not 0 (disabled)
ffmpeg_bps 400000

# Enables and defines variable bitrate for the ffmpeg encoder.
# ffmpeg_bps is ignored if variable bitrate is enabled.
# Valid values: 0 (default) = fixed bitrate defined by ffmpeg_bps,
# or the range 1 - 100 where 1 means worst quality and 100 is best.
ffmpeg_variable_bitrate 0

# Codec to used by ffmpeg for the video compression.
# Timelapse videos have two options.
#   mpg - Creates mpg file with mpeg-2 encoding.
#     If motion is shutdown and restarted, new pics will be appended
#     to any previously created file with name indicated for timelapse.
#   mpeg4 - Creates avi file with the default encoding.
#     If motion is shutdown and restarted, new pics will create a
#     new file with the name indicated for timelapse.
# Supported formats are:
# mpeg4 or msmpeg4 - gives you files with extension .avi
# msmpeg4 is recommended for use with Windows Media Player because
# it requires no installation of codec on the Windows client.
# swf - gives you a flash film with extension .swf
# flv - gives you a flash video with extension .flv
# ffv1 - FF video codec 1 for Lossless Encoding
# mov - QuickTime
# mp4 - MPEG-4 Part 14 H264 encoding
# mkv - Matroska H264 encoding
# hevc - H.265 / HEVC (High Efficiency Video Coding)
ffmpeg_video_codec hevc

# When creating videos, should frames be duplicated in order
# to keep up with the requested frames per second
# (default: true)
ffmpeg_duplicate_frames false

############################################################
# Snapshots (Traditional Periodic Webcam File Output)
############################################################

# Make automated snapshot every N seconds (default: 0 = disabled)
snapshot_interval 1800000

############################################################
# Text Display
# %Y = year, %m = month, %d = date,
# %H = hour, %M = minute, %S = second, %T = HH:MM:SS,
# %v = event, %q = frame number, %t = camera id number,
# %D = changed pixels, %N = noise level, \n = new line,
# %i and %J = width and height of motion area,
# %K and %L = X and Y coordinates of motion center
# %C = value defined by text_event - do not use with text_event!
# You can put quotation marks around the text to allow
# leading spaces
############################################################
# Locate and draw a box around the moving object.
# Valid values: on, off, preview (default: off)
# Set to 'preview' will only draw a box in preview_shot pictures.
locate_motion_mode off

# Set the look and style of the locate box if enabled.
# Valid values: box, redbox, cross, redcross (default: box)
# Set to 'box' will draw the traditional box.
# Set to 'redbox' will draw a red box.
# Set to 'cross' will draw a little cross to mark center.
# Set to 'redcross' will draw a little red cross to mark center.
locate_motion_style box

# Draws the timestamp using same options as C function strftime(3)
# Default: %Y-%m-%d\n%T = date in ISO format and time in 24 hour clock
# Text is placed in lower right corner
text_right %Y-%m-%d\n%T-%q

# Draw a user defined text on the images using same options as C function strftime(3)
# Default: Not defined = no text
# Text is placed in lower left corner
text_left %t Skycam facing South East %T *d frame%q noise%N

# Draw the number of changed pixed on the images (default: off)
# Will normally be set to off except when you setup and adjust the motion settings
# Text is placed in upper right corner
text_changes off

# This option defines the value of the special event conversion specifier %C
# You can use any conversion specifier in this option except %C. Date and time
# values are from the timestamp of the first image in the current event.
# Default: %Y%m%d%H%M%S
# The idea is that %C can be used filenames and text_left/right for creating
# a unique identifier for each event.
text_event %Y%m%d%H%M%S

# Draw characters at twice normal size on images. (default: off)
text_double on

# Text to include in a JPEG EXIF comment
# May be any text, including conversion specifiers.
# The EXIF timestamp is included independent of this text.
;exif_text %i%J/%K%L

############################################################
# Target Directories and filenames For Images And Films
# For the options snapshot_, picture_, movie_ and timelapse_filename
# you can use conversion specifiers
# %Y = year, %m = month, %d = date,
# %H = hour, %M = minute, %S = second,
# %v = event, %q = frame number, %t = camera id number,
# %D = changed pixels, %N = noise level,
# %i and %J = width and height of motion area,
# %K and %L = X and Y coordinates of motion center
# %C = value defined by text_event
# Quotation marks round string are allowed.
############################################################

# Target base directory for pictures and films
# Recommended to use absolute path. (Default: current working directory)
target_dir /home/pi/skycam-snapshots

# File path for snapshots (jpeg or ppm) relative to target_dir
# Default: %v-%Y%m%d%H%M%S-snapshot
# Default value is equivalent to legacy oldlayout option
# For Motion 3.0 compatible mode choose: %Y/%m/%d/%H/%M/%S-snapshot
# File extension .jpg or .ppm is automatically added so do not include this.
# Note: A symbolic link called lastsnap.jpg created in the target_dir will always
# point to the latest snapshot, unless snapshot_filename is exactly 'lastsnap'
snapshot_filename %v-%Y%m%d%H%M%S-snapshot

# File path for motion triggered images (jpeg or ppm) relative to target_dir
# Default: %v-%Y%m%d%H%M%S-%q
# Default value is equivalent to legacy oldlayout option
# For Motion 3.0 compatible mode choose: %Y/%m/%d/%H/%M/%S-%q
# File extension .jpg or .ppm is automatically added so do not include this
# Set to 'preview' together with best-preview feature enables special naming
# convention for preview shots. See motion guide for details
picture_filename %v-%Y%m%d%H%M%S-%q

# File path for motion triggered ffmpeg films (movies) relative to target_dir
# Default: %v-%Y%m%d%H%M%S
# File extensions(.mpg .avi) are automatically added so do not include them
movie_filename %v-%Y%m%d%H%M%S

# File path for timelapse movies relative to target_dir
# Default: %Y%m%d-timelapse
# File extensions(.mpg .avi) are automatically added so do not include them
timelapse_filename %Y%m%d-timelapse

############################################################
# Global Network Options
############################################################
# Enable IPv6 (default: off)
ipv6_enabled off

############################################################
# Live Stream Server
############################################################

# The mini-http server listens to this port for requests (default: 0 = disabled)
stream_port 8081

# Quality of the jpeg (in percent) images produced (default: 50)
stream_quality 75

# Output frames at 1 fps when no motion is detected and increase to the
# rate given by stream_maxrate when motion is detected (default: off)
stream_motion off

# Maximum framerate for stream streams (default: 1)
stream_maxrate 100

# Restrict stream connections to localhost only (default: on)
stream_localhost off

# Limits the number of images per connection (default: 0 = unlimited)
# Number can be defined by multiplying actual stream rate by desired number of seconds
# Actual stream rate is the smallest of the numbers framerate and stream_maxrate
stream_limit 0

# Set the authentication method (default: 0)
# 0 = disabled
# 1 = Basic authentication
# 2 = MD5 digest (the safer authentication)
stream_auth_method 0

# Authentication for the stream. Syntax username:password
# Default: not defined (Disabled)
stream_authentication admin:admin

# Percentage to scale the stream image for preview
# Default: 25
; stream_preview_scale 25

# Have stream preview image start on a new line
# Default: no
; stream_preview_newline no

############################################################
# HTTP Based Control
############################################################

# TCP/IP port for the http server to listen on (default: 0 = disabled)
webcontrol_port 8181

# Restrict control connections to localhost only (default: on)
webcontrol_localhost on

# Output for http server, select off to choose raw text plain (default: on)
webcontrol_html_output on

# Authentication for the http based control. Syntax username:password
# Default: not defined (Disabled)
webcontrol_authentication admin:admin

############################################################
# External Commands, Warnings and Logging:
# You can use conversion specifiers for the on_xxxx commands
# %Y = year, %m = month, %d = date,
# %H = hour, %M = minute, %S = second,
# %v = event, %q = frame number, %t = camera id number,
# %D = changed pixels, %N = noise level,
# %i and %J = width and height of motion area,
# %K and %L = X and Y coordinates of motion center
# %C = value defined by text_event
# %f = filename with full path
# %n = number indicating filetype
# Both %f and %n are only defined for on_picture_save,
# on_movie_start and on_movie_end
# Quotation marks round string are allowed.
############################################################

# Do not sound beeps when detecting motion (default: on)
# Note: Motion never beeps when running in daemon mode.
quiet on

# Command to be executed when an event starts. (default: none)
# An event starts at first motion detected after a period of no motion defined by event_gap
; on_event_start value

# Command to be executed when an event ends after a period of no motion
# (default: none). The period of no motion is defined by option event_gap.
; on_event_end value

# Command to be executed when a picture (.ppm|.jpg) is saved (default: none)
# To give the filename as an argument to a command append it with %f
; on_picture_save value

# Command to be executed when a motion frame is detected (default: none)
; on_motion_detected value

# Command to be executed when motion in a predefined area is detected
# Check option 'area_detect'.   (default: none)
; on_area_detected value

# Command to be executed when a movie file (.mpg|.avi) is created. (default: none)
# To give the filename as an argument to a command append it with %f
; on_movie_start value

# Command to be executed when a movie file (.mpg|.avi) is closed. (default: none)
# To give the filename as an argument to a command append it with %f
; on_movie_end value

# Command to be executed when a camera can't be opened or if it is lost
# NOTE: There is situations when motion don't detect a lost camera!
# It depends on the driver, some drivers dosn't detect a lost camera at all
# Some hangs the motion thread. Some even hangs the PC! (default: none)
; on_camera_lost value

############################################################
# Video Loopback Device (vloopback project)
############################################################

# Output images to a video4linux loopback device
# The value '-' means next available (default: not defined)
; video_pipe value

# Output motion images to a video4linux loopback device
# The value '-' means next available (default: not defined)
; motion_video_pipe value

##############################################################
# camera config files - One for each camera.
# Except if only one camera - You only need this config file.
# If you have more than one camera you MUST define one camera
# config file for each camera in addition to this config file.
##############################################################

# Remember: If you have more than one camera you must have one
# camera file for each camera. E.g. 2 cameras requires 3 files:
# This motion.conf file AND camera1.conf and camera2.conf.
# Only put the options that are unique to each camera in the
# camera config files.
camera /etc/motion/camera1.conf
; camera /etc/motion/camera2.conf
; camera /etc/motion/camera3.conf
; camera /etc/motion/camera4.conf

##############################################################
# Camera config directory - One for each camera.
##############################################################
#
camera_dir /etc/motion/conf.d

Here is my /etc/motion/camera1.conf: (This is the entire file)
# /etc/motion/camera1.conf
#
# This config file was generated by motion 4.0

###########################################################
# Capture device options
############################################################

# Camera Id
# Consistent identification number to assign to each camera across multiple
# invocations of Motion.
# Default: The order when the camera file was read
# camera_id = 1

# Videodevice to be used for capturing  (default /dev/video0)
# for FreeBSD default is /dev/bktr0
videodevice /dev/video0

# The video input to be used (default: -1)
# Should normally be set to 1 for video/TV cards, and -1 for USB cameras
input -1

# Draw a user defined text on the images using same options as C function strftime(3)
# Default: Not defined = no text
# Text is placed in lower left corner
text_left %t Skycam facing SE %T *d frame%q noise%N

############################################################
# Target Directories and filenames For Images And Films
# For the options snapshot_, picture_, mpeg_ and timelapse_filename
# you can use conversion specifiers
# %Y = year, %m = month, %d = date,
# %H = hour, %M = minute, %S = second,
# %v = event, %q = frame number, %t = camera id number,
# %D = changed pixels, %N = noise level,
# %i and %J = width and height of motion area,
# %K and %L = X and Y coordinates of motion center
# %C = value defined by text_event
# Quotation marks round string are allowed.
############################################################

# Target base directory for pictures and films
# Recommended to use absolute patch. (Default: current working directory)
#target_dir /tmp/motion/cam1

# File path for motion triggered images (jpeg or ppm) relative to target_dir
# Default: %v-%Y%m%d%H%M%S-%q
# Default value is equivalent to legacy oldlayout option
# For Motion 3.0 compatible mode choose: %Y/%m/%d/%H/%M/%S-%q
# File extension .jpg or .ppm is automatically added so do not include this
# Set to 'preview' together with best-preview feature enables special naming
# convention for preview shots. See motion guide for details
picture_filename CAM1_%v-%Y%m%d%H%M%S-%q

############################################################
# Live Stream Server
############################################################

# The mini-http server listens to this port for requests (default: 0 = disabled)
stream_port 8081

# Command to be executed when a picture (.ppm|.jpg) is saved (default: none)
# The filename of the picture is appended as an argument for the command.
#on_picture_save /usr/local/motion-extras/camparse2.pl

# Command to be executed when a movie file (.mpg|.avi) is closed. (default: none)
# Filename of movie is appended as an argument for the command.
#on_movie_end /usr/local/motion-extras/mpegparse2.pl

A: Change the below value to 'best' for example:
# Output 'normal' pictures when motion is detected (default: on)
# Valid values: on, off, first, best, center
# When set to 'first', only the first picture of an event is saved.
# Picture with most motion of an event is saved when set to 'best'.
# Picture with motion nearest center of picture is saved when set to 'center'.
# Can be used as preview shot for the corresponding movie.
output_pictures on

A: Playing with something like this at the moment, ran into some similar issues.  Here's what I see:
minimum_motion_frames 1

It looks like this is going to take a picture for every motion    detected on the camera.  Not sure if you're aware - on RasPi I bump    this up to 5.
webcontrol_localhost on

I normally turn this off so that I can control from remote reasons are:

*

*Motion is built to capture motion by default and telling it not to requires manual intervention

*The best way to intervene here is actually by the web UI (Action > detection > pause)

*The other, more manual way is to call motion from the command line with a -m switch (motion -m ...).  This requires a bit more management of the process but works as well.

A: Apparently this happens because we upgrade the motion program and still use the old (previously working) config file.  The new program defaults to this unfortunate behaviour when the new "output_pictures" setting is missing, which is it from old config file.


text:
Q: Problem with configuring HTTPS on my WCF service I am trying to add transport security layer to my WCF service. But after following all the instructions i still get error "Could not find a base address that matches scheme https for the endpoint with binding BasicHttpBinding. Registered base address schemes are [http]."
Already did all needed configurations in IIS Manager and add need code in web.config but i still have a feeling i am missing something
web.config:
   <system.serviceModel>
          <services>
              <service name="MyNameSpace.MyService" behaviorConfiguration="secureBehavior">
                <endpoint address="" binding="basicHttpBinding" bindingConfiguration="secureHttpBinding" contract="MyNameSpace.IMyService" />
                <endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange" />
              </service>
            </services>

        <bindings>
          <basicHttpBinding>
            <binding name="secureHttpBinding">
              <security mode="Transport">
                <transport clientCredentialType="None" />
              </security>
            </binding>
          </basicHttpBinding>
        </bindings>

        <behaviors>
          <serviceBehaviors>
            <behavior name="secureBehavior">
              <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
              <serviceDebug includeExceptionDetailInFaults="false" />
            </behavior>
          </serviceBehaviors>
        </behaviors>

        <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
      </system.serviceModel>

A: There is no problem with your present configuration, configure an https endpoint and it uses Transport security mode. One more thing we need to do is configuring an https binding address in IIS binding module. Like below.

It locates in the IIS site binding module.

Then we could use the above https service address to access it.
https://IP:4431/Service1.svc (service base address)
Feel free to let me know if the problem still exists.


text:
Q: How to add exchange course to currency in dataframe I need to add a new column with exchange rates. Is it possible with the mutate function?
Example:
> dat
  currency
1 $
2 €
3 £
4 ¥

output:
> dat
  currency  ex_rate
1 $         1
2 €         0.8
3 £         0.55
4 ¥         130

Thank you!