text:
Q: How to set mark shape for a regression plot? I want to make a regression line from my data and add a legend to the drawing. The mark shape is OK in the legend, but wrong on the regression line. What do I wrong?
\documentclass[article]{standalone}
\usepackage{pgfplots}
\usepackage{pgfplotstable}
    \definecolor{webgreen}{rgb}{0,.5,0}
    \definecolor{webblue}{rgb}{0,0,.8}
\begin{document}
\begin{tikzpicture}
\begin{axis}[%
        legend style={
            cells={anchor=west},
            legend pos={south east},
        },
        xmin=0, xmax=51,% x scale
        ymode=log,
        ymin=5e-8, ymax=2e-5, % y scale
scatter/classes={%
    MPP={mark=diamond*,draw=webgreen},Cluster={mark=triangle*,draw=webblue}, MPPR={mark=diamond,draw=webgreen},ClusterR={mark=triangle,draw=webblue}}]
\addplot[scatter,only marks,%
    scatter src=explicit symbolic]%
table[meta=label] {
x y label
3   9.656E-07   MPP
4   1.096E-07   MPP
6   2.191E-07   MPP
45  1.052E-06   MPP
49  4.131E-06   MPP
50  4.682E-06   MPP
    };
    \addlegendentry{MPP data in 2016}

\addplot[scatter,only marks,%
    scatter src=explicit symbolic]%
table[meta=label] {
x y label
2   1.991E-07   Cluster
5   1.040E-07   Cluster
11  1.225E-06   Cluster
31  1.365E-05   Cluster
33  2.677E-06   Cluster
34  1.718E-06   Cluster
38  1.243E-06   Cluster
39  4.628E-06   Cluster
    };
    \addlegendentry{C data in 2016}

\addplot table[y={create col/linear regression={y=Y}}, mark=diamond,
 meta=label,    /pgf/number format/read comma as period
]
{
x Y label
3   9.656E-07   MPPR
4   1.096E-07   MPPR
6   2.191E-07   MPPR
45  1.052E-06   MPPR
49  4.131E-06   MPPR
50  4.682E-06   MPPR
    };
    \addlegendentry{Regression of MPP in 2016}

\addplot table[y={create col/linear regression={y=Y}}, mark=triangle,
 meta=label,    /pgf/number format/read comma as period
]
 {
x Y label
2   1.991E-07   ClusterR
5   1.040E-07   ClusterR
11  1.225E-06   ClusterR
33  2.677E-06   ClusterR
34  1.718E-06   ClusterR
38  1.243E-06   ClusterR
39  4.628E-06   ClusterR
    };
    \addlegendentry{Regression in 2016}
\end{axis}
\end{tikzpicture}
\end{document}

A: mark=diamond have to be set as option for \addplot:
\addplot+[mark=diamond] table[...]{...};

Code:
\documentclass{standalone}
\usepackage{pgfplotstable}% loads also pgfplots
\pgfplotsset{compat=1.15}% <- set a compat; current version is 1.15
    \definecolor{webgreen}{rgb}{0,.5,0}
    \definecolor{webblue}{rgb}{0,0,.8}
\begin{document}
\begin{tikzpicture}
\begin{axis}[%
        legend style={
            cells={anchor=west},
            legend pos={south east},
        },
        xmin=0, xmax=51,% x scale
        ymode=log,
        ymin=5e-8, ymax=2e-5, % y scale
scatter/classes={%
    MPP={mark=diamond*,draw=webgreen},Cluster={mark=triangle*,draw=webblue}, MPPR={mark=diamond,draw=webgreen},ClusterR={mark=triangle,draw=webblue}}]
\addplot[scatter,only marks,%
    scatter src=explicit symbolic]%
table[meta=label] {
x y label
3   9.656E-07   MPP
4   1.096E-07   MPP
6   2.191E-07   MPP
45  1.052E-06   MPP
49  4.131E-06   MPP
50  4.682E-06   MPP
    };
    \addlegendentry{MPP data in 2016}

\addplot[scatter,only marks,%
    scatter src=explicit symbolic]%
table[meta=label] {
x y label
2   1.991E-07   Cluster
5   1.040E-07   Cluster
11  1.225E-06   Cluster
31  1.365E-05   Cluster
33  2.677E-06   Cluster
34  1.718E-06   Cluster
38  1.243E-06   Cluster
39  4.628E-06   Cluster
    };
    \addlegendentry{C data in 2016}

\addplot+[mark=diamond]table[y={create col/linear regression={y=Y}},
 meta=label,    /pgf/number format/read comma as period
]
{
x Y label
3   9.656E-07   MPPR
4   1.096E-07   MPPR
6   2.191E-07   MPPR
45  1.052E-06   MPPR
49  4.131E-06   MPPR
50  4.682E-06   MPPR
    };
    \addlegendentry{Regression of MPP in 2016}

\addplot+[mark=triangle] table[y={create col/linear regression={y=Y}},
 meta=label,    /pgf/number format/read comma as period
]
 {
x Y label
2   1.991E-07   ClusterR
5   1.040E-07   ClusterR
11  1.225E-06   ClusterR
33  2.677E-06   ClusterR
34  1.718E-06   ClusterR
38  1.243E-06   ClusterR
39  4.628E-06   ClusterR
    };
    \addlegendentry{Regression in 2016}
\end{axis}
\end{tikzpicture}
\end{document}


text:
Q: How to repeat a string multiple times with spaces? I want to pass one string with n times to repeat it with spaces, my code look like:
def repeating(word, n):
  return word * n

I want the output look like:
hello hello hello

with spaces between each string.

A: Try using str.join as well:
def repeating(word, n):
    return ' '.join([word] * n)

As mentioned in the documentation:

Returns a string made from the elements of an iterable.

You can specify the separator of the elements in an iterable, like here I specified a space.
Also the reason I add brackets to word is because only that way it becomes a list, check the below examples:
>>> word = 'foo'
>>> word * 5
'foofoofoofoofoo'
>>> [word] * 5
['foo', 'foo', 'foo', 'foo', 'foo']
>>> ' '.join(word * 5)
'f o o f o o f o o f o o f o o'
>>> ' '.join([word] * 5)
'foo foo foo foo foo'
>>>

A: If you want better performance, don't use join, instead, you can use formatted string and multiply it, then finally take the slice upto second last value (or rstrip will also work if the string itself doesn't end with space character):
def repeat(word, n):
    return (f"{word} "*n)[:-1]

>>> repeat('hello', 10)
'hello hello hello hello hello hello hello hello hello hello'

Benchmark for word = 'Hello' and n=100
using join:
2.68 µs ± 300 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

without join:
786 ns ± 62.9 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

A: here is some started code to try.  I declare an empty string and loop through to 'append' the word on the return string.
def repeating(word, n):
    returnString =""
    i = 0
    while i < n:
        returnString += word + " "
        i += 1
    return returnString

testString = repeating("hello", 3)
print(testString)

small note I dont think Im actually appending the string but rather a new string is being created each time the loop runs.

A: def repeating(word, n):
    return ((' ' + word) * n)[1:]

Benchmark with word = 'hello' and n = 30000:
0.49 ms  0.48 ms  0.49 ms  0.48 ms  0.49 ms  ' '.join([word] * n)
0.19 ms  0.19 ms  0.19 ms  0.19 ms  0.19 ms  ((' ' + word) * n)[1:]

Code (Try it online!):
from timeit import repeat

setup = "word = 'hello'; n = 30000"
exprs = [
    "' '.join([word] * n)",
    "((' ' + word) * n)[1:]",
]

for _ in range(3):
    for expr in exprs:
        ts = repeat(expr, setup, number=1000)
        print(*('%.2f ms ' % t for t in ts), expr)
    print()

A: def repeating(word, n):
    return word*(n>0) + (' ' + word)*(n-1)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Where, and in what format, are the in-game assets (sounds, models, etc.) stored for League of Legends? Similar to this question, but that does not appear to contain the answer I need.
Where can I find the actual in-game assets used by League of Legends? I was able to find the champion select sounds in C:\Riot Games\League of Legends\RADS\projects\lol_air_client\releases\0.0.1.215\deploy\assets\sounds\en_US\champions, but where are the actual in game sounds (or the models, for that matter)?
I'd like to be able to replace some of those sounds with blanks so that I don't have to listen to as many character quips.

A: For assets images in general, Riot has released them. https://github.com/RiotAPI/Riot-Games-API-Developer-Assets
For audio, I'm gonna guess they are all compiled, and can't really be extracted except if you can find a way to decompile the game. Which is very hard to do.


text:
Q: Run Control-M job with a script that is stored in a GitLab repository is it possible to run a job in Control-M that accesses a (e.g. DB2) script stored in a Git repository?
Normally it is the case that you specify a path where the script is located. How would this look like when working with a remote Git repository? Is there a way to do this, or what could be a solution for this?


text:
Q: How do I removeAllObjects on my NSMutableArray that is part of another object? I have an object defined like this:
Scores.h:
@interface Scores : NSObject {
NSString *sentenceKey;
    NSMutableArray *scorrectAnswers;
}
@property (nonatomic, copy) NSString *sentenceKey;
@property (nonatomic, copy) NSMutableArray *scorrectAnswers;
+ (id)addScore:(NSString *)senKey;

- (id)initWithSentenceKey:(NSString *)sKey
    scorrectAnswers:(NSMutableArray *)scorrectAs;

- (id)initWithSentenceKey:(NSString *)sKey;
- (void)removeArrayObjects;

Score.m:
#import "Scores.h"
@implementation Scores

@synthesize sentenceKey, scorrectAnswers;

+ (id)addScore:(NSString *)senKey
{
Scores *newScore = [[self alloc] initWithSentenceKey:senKey
                    scorrectAnswers:[NSMutableArray new]];
return [newScore autorelease];}

I'm trying to removeAllObjects on my mutable array with this method:
- (void)removeArrayObjects;{
   [scorrectAnswers removeAllObjects];}

...which I call from another program like this:
for (Scores *sScore in scores)
{
    [sScore removeArrayObjects];
}

... and I get this error when I run it:
-[__NSArrayI removeAllObjects]: unrecognized selector sent to instance 0x53412d0
Can anyone tell me what I'm doing wrong here?  Thanks.

A: You are not dealing with an NSMutableArray as the error indicates you have an immutable NSArray.
This question may be your answer NSMutableArray addObject: -[__NSArrayI addObject:]: unrecognized selector sent to instance
Basically the copy you used when defining your @property will cause the setter to be generated using
scorrectAnswers = [newMutableArray copy];

which returns an immutable NSArray.
You can re-implement this method and change the previous line for:
scorrectAnswers = [newMutableArray mutableCopy];

or use retain instead of copy
This can also occur when getting data from a plist
If you are using a plist it will return an NSArray even if you save an NSMutableArray it will be cast. So when retrieving you will need to do something like:
scorrectAnswers = [[NSMutableArray alloc] initWithArray:[userDefault objectForKey:@"my_array_key"]]

A: It doesn't look like like the memory pointed to by scorrectAnswers is actually pointing to an NSMutableArray.  Where and how do you initialize that variable?  If you are setting the ivar directly with an autoreleased object, like:
scorrectAnswers = [NSMutableArray arrayWithCapacity:10];

then the autoreleased array will be destroyed, since you're not retaining it (or copying it).  If that memory gets reallocated to point to another object, you'll see an error like the one you're getting, with an unexpected type.  If the memory has not been reallocated, you'll get an EXC_BAD_ACCESS error.

A: Similar to what was mentioned above, I had an NSMutableArray which was being re-allocated somewhere in my code as an NSArray. Once I modified that to correctly be an NSMutableArray, it resolved my problem.
I would suggest doing a quick search to ensure that you have not reallocated the array somewhere in your project and modify accordingly.


text:
Q: Backbone - edit View template before render I'm trying to render a Bootstrap modal with Backbone. I need to check some HTML elements from the template (using $('#tpl-create-details').html()), and hide them before render, but I'm facing some problems.

*

*Element is not hidden even if I add display:none.

*I need to create the template as a jQuery object, so I can add display:none to the element, but after that I can't use the same template object because it won't be shown on the page as a Bootstrap modal but as plain HTML.

*

*Is a Backbone view the right place to do this?

*Am I doing something wrong?

View
app.Views.CreateDetails = Backbone.View.extend({

    initialize: function () {
        var template = $('#tpl-create-details').html();
        template = $(template);

        this.collection.each(function (item) {
            var customizingItem = item.toJSON();

            var fieldId = customizingItem.name;

            if (customizingItem.hidden) {
                var field = template.find('input[name=' + fieldId + ']');
                var field = $(field.get(0));
                field.parent().parent().css('display', 'none');
            }
        }, this);

        this.template = _.template(template.html());
    },

    render: function () {
        var html = this.template();
        this.$el.append(html);
        return this;
    }
});

Router
app.Router = Backbone.Router.extend({
    routes: {
        'create': 'create'
    },

    create: function () {
        var customizing = new app.Collections.Customizing();
        customizing.fetch({
            reset: true,
            success: function (collection, response, options) {
                var CreateDetailsView = new app.Views.CreateDetails({
                    collection: collection
                });
                $('#content').append(CreateDetailsView.render().$el);
                var modalAdd = this.$('#modalDetail');
                modalAdd.modal('show');
            }
        });
    }
});


text:
Q: Bar plot showing count by amount intervals So I have this column in Power BI:
Sales amount: 21, 22, 23, 45, 48, 50, 91, 100.
And all I would like to do is a plot where I can visualize a count by bins, so the expected result would be something that represents this table below:
Sales amount: 0-33, 34-66, 67-100
Count: 3, 3, 2.
What measure should I apply? I tried binning with the predefined options that come in Desktop, but so far haven't achieved what I want.
Thanks in advance!

A: Create this calculated column
Bins =
SWITCH(
    TRUE(),
    AND( 0 < Sales[Amount], Sales[Amount] <= 33 ), "0-33",
    AND(33 < Sales[Amount], Sales[Amount] <= 66 ), "33-66",
    AND(66 < Sales[Amount], Sales[Amount] <= 100 ), "66-100",
    "Outlier"
)

and this measure
Count = COUNTROWS(Sales)

and put it all together in a bar chart.


text:
Q: generating KML file using C# and LINQ with a recursive function I am trying to create a KML file dynamically in C#. I have wrote a recursive function to do this. However the result of output has a bit problem. The problem is the position of closing tags of all placemarks. I am really confused. Please tell me where am I making mistake in the recursive function???
My code:
private void xmlBuild()
    {
XDocument doc = new XDocument(
        new XDeclaration("1.0", "utf-8", ""),
        new XComment("This is comment by me"),
        new XElement(ns+"kml",
        new XElement(ns+"Document", rec_build())));
        doc.Save(Server.MapPath(@"~\App_Data\markers2.xml"));
}
private XElement rec_build()
    {
        if (iteration != 0)
        {
            iteration -= 1;
            return final_rec = new XElement(ns + "Placemark",
                    new XAttribute("id", "1"),
                    new XElement(ns + "title", "something"),
                    new XElement(ns + "description", "something"),
                    new XElement(ns + "LookAt",
                    new XElement(ns + "Longitude", "49.69"),
                    new XElement(ns + "Latitude", "32.345")), new XElement(ns + "Point", new XElement(ns + "coordinates", "49.69,32.345,0")),rec_build());
        }
        else
        {
            return null;
        }
    }

and this is the output for iteration value of 2: (please notice the closing tags of placemark id=1 at the end of file. It should be before the starting tag of placemark id=2!
<?xml version="1.0" encoding="utf-8"?>
<!--This is comment by me-->
<kml xmlns="http://earth.google.com/kml/2.2">
  <Document>
    <Placemark id="1">
      <title>something</title>
      <description>something</description>
      <LookAt>
        <Longitude>49.69</Longitude>
        <Latitude>32.345</Latitude>
      </LookAt>
      <Point>
        <coordinates>49.69,32.345,0</coordinates>
      </Point>
      <Placemark id="1">
        <title>something</title>
        <description>something</description>
        <LookAt>
          <Longitude>49.69</Longitude>
          <Latitude>32.345</Latitude>
        </LookAt>
        <Point>
          <coordinates>49.69,32.345,0</coordinates>
        </Point>
      </Placemark>
    </Placemark>
  </Document>
</kml>

A: So the problem is each time you recurse, you are adding the element to the newly created item. It seems that a loop would work better.
Essentially code is doing this:
set up the kml outbody
1st call and add element (element 1) to kml outerboy
2nd call add element (element 2) to (element 1)
3rd call add element (element 3) to (element 2).
If you wanted to do a recursive method rather then the looping mechanism, pass in a reference to the outer kml .
The recursive is more confusing if this is exactly how it works
(Sorry if I have an extra or missing parenthesis, comma, or other item. I don't have VS installed on this)
Looping:
private void xmlBuild()
{
    XElement documentElement = new XElement(ns + "Document");

    for (int i = 0; i < 2; i++)
    {
        documentElement.Add(rec_build());
    }

    XDocument doc = new XDocument(
        new XDeclaration("1.0", "utf-8", ""),
        new XComment("This is comment by me"),
        new XElement(ns + "kml", documentElement));

    doc.Save(Server.MapPath(@"~\App_Data\markers2.xml"));
}

private XElement rec_build()
{

    return new XElement(ns + "Placemark",
           new XAttribute("id", "1"),
           new XElement(ns + "title", "something"),
           new XElement(ns + "description", "something"),
           new XElement(ns + "LookAt",
           new XElement(ns + "Longitude", "49.69"),
           new XElement(ns + "Latitude", "32.345")),
           new XElement(ns + "Point",
           new XElement(ns + "coordinates", "49.69,32.345,0")));
}

Recursive:
private void xmlBuild()
{
    XElement docElement = new XElement(ns+"Document");
    rec_build(docElement);
    XDocument doc = new XDocument(
    new XDeclaration("1.0", "utf-8", ""),
    new XComment("This is comment by me"),
    new XElement(ns+"kml", docElement)));
    doc.Save(Server.MapPath(@"~\App_Data\markers2.xml"));
}
private XElement rec_build(XElement doc)
{
    if (iteration != 0)
    {
        iteration -= 1;
        doc.Add(new XElement(ns + "Placemark",
                new XAttribute("id", "1"),
                new XElement(ns + "title", "something"),
                new XElement(ns + "description", "something"),
                new XElement(ns + "LookAt",
                new XElement(ns + "Longitude", "49.69"),
                new XElement(ns + "Latitude", "32.345")),
                new XElement(ns + "Point", new XElement(ns + "coordinates", "49.69,32.345,0")));
        return recBuild(doc);
    }
    else
    {
        return null;
    }
}

A: You are adding the recursively build elements as children of Placemark and not Document. This should do the trick:
    private void xmlBuild()
    {
        XElement docElement = new XElement(ns + "Document");
        XDocument doc = new XDocument(
                new XDeclaration("1.0", "utf-8", ""),
                new XComment("This is comment by me"),
                new XElement(ns + "kml", docElement));
        rec_build(docElement);
        doc.Save(Server.MapPath(@"~\App_Data\markers2.xml"));
    }

    private XElement rec_build(XElement docElement)
    {
        if (iteration != 0)
        {
            iteration -= 1;
            return final_rec = new XElement(ns + "Placemark",
                    new XAttribute("id", "1"),
                    new XElement(ns + "title", "something"),
                    new XElement(ns + "description", "something"),
                    new XElement(ns + "LookAt",
                    new XElement(ns + "Longitude", "49.69"),
                    new XElement(ns + "Latitude", "32.345")),
                    new XElement(ns + "Point", new XElement(ns + "coordinates", "49.69,32.345,0")));
            docElement.Add(final_rec);
            rec_build(docElement);
        }
        else
            return null;
    }


text:
Q: Facebook send dialog box not able to send message I am getting an error every time when I try to send link with send dialog box, please any one help me out.
Error Detail: - "Sorry, something went wrong. We're working on getting this fixed as soon as we can."

A: I just got the same error, and I think it happened to me because I was using links that are not accessible publicly.  Try sending "www.google.com" as the link parameter and see if it still happens.


text:
Q: pushing an object onto an array from an array of objects in JavaScript I'm trying to make a function that looks through an array of objects (first argument) and returns an array of all objects that have matching property and value pairs (second argument). Each property and value pair of the source object has to be present in the object from the collection if it is to be included in the returned array.
For example, if the first argument is
[{
  first: "Romeo",
  last: "Montague"
}, {
  first: "Mercutio",
  last: null
}, {
  first: "Tybalt",
  last: "Capulet"
}]

, and the second argument is { last: "Capulet" }, then you must return the third object from the array (the first argument), because it contains the property and it's value, that was passed on as the second argument.
So far this is what I've tried but I either get nothing in my new array or all the objects pushed in:
function where(collection, source) {
    var arr = [];
    // iterating through the properties in course
    for (var name in source){
        // if the name from source is found in collection
        for (var i =0; i<collection.length; i++) {
            if (collection[i].hasOwnProperty(name))
            {
            // push the object onto the array?????
                arr.push(collection[i]);
                console.log(collection[i]);
            }
        }
    }
    return arr;
}

where([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null   }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });

A: Use Array.prototype.filter and Array.prototype.every:
If I understood correctly, you want something like this;
var src = {last: "Capulet"};

var arr = [
{
  first: "Romeo",
  last: "Montague"
},
{
  first: "Mercutio",
  last: null
},
{
  first: "Tybalt",
  last: "Capulet"
}];

var newArr = arr.filter(function(item) {
    if(Object.keys(src).every(function(k){
            return src.hasOwnProperty(k) && item.hasOwnProperty(k) && src[k] === item[k]}))
  {
    return item;
  }
});

console.log(newArr);

JSFIDDLE

A: i have two possible solutions

*

*you could use native function filter: https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Array/filter

*or use a library such as lodash with the "_.filter" function: https://lodash.com/docs
exemples:

*

*using lodash function:

var result = _.filter(array, {last: "Capulet"});

var arr = [
{
  first: "Romeo",
  last: "Montague"
},
{
  first: "Mercutio",
  last: null
},
{
  first: "Tybalt",
  last: "Capulet"
}];

var res = _.filter(arr, {last: "Capulet"});
console.log(res);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.1.0/lodash.js"></script>

A: If you are not wanting to write a function from scratch to meet your requirement, then UnderscoreJS might be at your rescue. Checkout the link below.
_.where(list, properties) in underscorejs library
var list = [{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null   }, { first: "Tybalt", last: "Capulet" }];

console.log(_.where(list, { last: "Capulet" })); // prints on console
// [{  first: "Tybalt", last: "Capulet"  }]

A: You can try this one
function where(collection, source) {
    for (var i = 0; i < collection.length; i++){
        var found = true;
        for (var name in source){
            //If one of the property does not match, do not return the object
            if (collection[i][name] != source[name]){ found = false; }
        }
        if (found) {
            //If you want the object
            return collection[i];

            //If you want the object in an array
            return [collection[i]];
        }
    }
}


text:
Q: Pandas iteration over rows for features calculation I have a pandas data frame and I want to calculate some features based on some short_window, long_window and bins values. More specifically, for each different row, I want to calculate some features. In order to do so, I move one row forward the df_long = df.loc[row:long_window+row] such as in the first iteration the pandas data frame for row=0 would be df_long = df.loc[0:50+0] and some features would be calculated based on this data frame, for row=1 would be df_long = df.loc[1:50+1] and some other features would be calculated and continues.
from numpy.random import seed
from numpy.random import randint
import pandas as pd
from joblib import Parallel, delayed

bins = 12
short_window = 10
long_window = 50

# seed random number generator
seed(1)

price = pd.DataFrame({
    'DATE_TIME': pd.date_range('2012-01-01', '2012-02-01', freq='30min'),
    'value': randint(2, 20, 1489),
    'amount': randint(50, 200, 1489)
})

def vap(row, df, short_window, long_window, bins):

    df_long = df.loc[row:long_window+row]
    df_short = df_long.tail(short_window)

    binning = pd.cut(df_long['value'], bins, retbins=True)[1]
    group_months = pd.DataFrame(df_short['amount'].groupby(pd.cut(df_short['value'], binning)).sum())

    return group_months['amount'].tolist(),  df.loc[long_window + row + 1, 'DATE_TIME']

def feature_extraction(data, short_window, long_window, bins):

    # Vap feature extraction
    ls = [f"feature{row + 1}" for row in range(bins)]
    amount, date = zip(*Parallel(n_jobs=4)(delayed(vap)(i, data, short_window, long_window, bins)
                                                for i in range(0, data.shape[0] - long_window - 1)))
    temp = pd.DataFrame(date, columns=['DATE_TIME'])
    temp[ls] = pd.DataFrame(amount, index=temp.index)
    data = data.merge(temp, on='DATE_TIME', how='outer')

    return data

df = feature_extraction(price, short_window, long_window, bins)

I tried to run it in parallel in order to save time but due to the dimensions of my data, it takes a long of time to finish.
Is there any way to change this iterative process (df_long = df.loc[row:long_window+row]) in order to reduce the computational cost? I was wondering if there is any way to use pandas.rolling but I am not sure how to use it in this case.
Any help would be much appreciated!
Thank you

A: This is the first try to speed up the calculation. I checked the first 100 rows and found out that the binning variable was always the same. So I managed to do an efficient algorithm with fixed bins. But when I checked the function on the whole data, I found out that there are about 100 lines out of 1489, that had a different binning variable so the solution below deviates in 100 lines from the original answer.
Benchmarking:
My fast function: 28 ms
My precise function: 388 ms
Original function: 12200 ms
So a speed up of around 500 times for the fast function and 20 times for precise function
Fast function code:
def feature_extraction2(data, short_window, long_window, bins):
    ls = [f"feature{row + 1}" for row in range(bins)]
    binning = pd.cut([2,19], bins, retbins=True)[1]
    bin_group = np.digitize(data['value'], binning, right=True)
    l_sum = []
    for i in range(1, bins+1):
        sum1 = ((bin_group == i)*data['amount']).rolling(short_window).sum()
        l_sum.append(sum1)

    ar_sum = np.array(l_sum).T
    ar_shifted = np.empty_like(ar_sum)
    ar_shifted[:long_window+1,:] = np.nan
    ar_shifted[long_window+1:,:] = ar_sum[long_window:-1,:]
    temp = pd.DataFrame(ar_shifted, columns = ls)
    data = pd.concat([data,temp], axis = 1, sort = False)
    return data

Precise function:
data = price.copy()
# Vap feature extraction
ls = [f"feature{row + 1}" for row in range(bins)]
data.shape[0] - long_window - 1)))
norm_volume = []
date = []
for i in range(0, data.shape[0] - long_window - 1):
    row = i
    df = data
    df_long = df.loc[row:long_window+row]
    df_short = df_long.tail(short_window)

    binning = pd.cut(df_long['value'], bins, retbins=True)[1]
    group_months = df_short['amount'].groupby(pd.cut(df_short['value'], binning)).sum().values

    x,y = group_months,  df.loc[long_window + row + 1, 'DATE_TIME']
    norm_volume.append(x)
    date.append(y)

temp = pd.DataFrame(date, columns=['DATE_TIME'])
temp[ls] = pd.DataFrame(norm_volume, index=temp.index)
data = data.merge(temp, on='DATE_TIME', how='outer')


text:
Q: Suitable evaluation metrics for Content-based Recommender System I am building a course recommendation system. The idea is to build a personalize system that users can see all the course recommended by the system when they login.
All the data I have is four columns:

*

*username (str)

*position (str, for exp: data engineer)

*skill (str, for exp: python, java, machine learning)

I have already made a model based on Content-based that using cosine similarity to detect the nearest neighbor based on the combine of two columns (position and skill).
Please look at the code below:
count = CountVectorizer(token_pattern=r"(?u)\b\w+\b",
            stop_words=None, ngram_range=(2,2), analyzer='word')
count_matrix = count.fit_transform(user['keyword'])

cosine_sim = cosine_similarity(count_matrix, count_matrix)

def rec(role):
  idx = indices[role]
  sim_scores = list(enumerate(cosine_sim[(idx)]))
  sim_scores = sorted(sim_scores, key=lambda x: x[1], reverse=True)
  sim_scores = sim_scores[1:26]
  user_indices = [i[0] for i in sim_scores]

  users = user.iloc[user_indices][['real-skill']]
  return users.head(10)

The question is that I need a metrics to evaluate my model or event dataset. I tried reaching to many libraries or other metrics that are useful for RS system is MSE, RMSE, Novelty,...
However, it seems that without more data from users preferences the metrics won't be evaluated. So, there are anyways to measure the accuracy with my simple system?
Thank you!


text:
Q: router.post('/', controller) vs router.route('/').get(controller) What's the difference between writing routes:
//in this style
router.route('admin').get(getAllAdminsController).post(createAdminController)

and this type of writing:
router.get('admin', getallAdminsController);
router.post('admin', createAdminController);

A: There's no difference in terms of functionality. The first style is called chained route, and the purpose of it based on the documentation is:

Because the path is specified at a single location, creating modular routes is helpful, as is reducing redundancy and typos

From: https://expressjs.com/en/guide/routing.html#app-route


text:
Q: Putting two physical hard drives in a single 2.5" bay? My crazy brain came up with this ridiculous idea. "Why can't I have a single 2.5" drive device that actually contains two independent hard drives? I want RAID 1 data mirroring and the security of having redundant drives. This is a thing that must exist!"
To be clear, I am not asking if I can somehow shoehorn two 2.5" drives into a single bay, replace an optical drive with an additional HDD, or anything like that. What I have in mind is a single 2.5"-form-factor device that houses two independent hard drives, with separate housings (likely) and distinct controllers. Probably all they'd need to share is the power & SATA connections.
Probably no such thing exists, but because I know there exist hard drives the physical size of a stack of postage stamps (roughly), I have to ask.

A: Perhaps not exactly what you had in mind, but there does exist such a device - the WD dual 2.5 drive - it's a 2.5 hdd + a reasonably sized ssd inside a single 2.5" chassis - the main issue I see with alternatives is that even if you managed to get two small drives in there (say two mSata or similar), the laptop won't have more than one sata connection there, so you would also need an adapter/raid device right there, which would make it more complicate, but guess what - those also exist- look for 2.5 to dual mSata adapters, they will have raid support built-in

A: If you can get the drives to physically fit, I don't see any reason why this could not be done.
Be careful though, even if there is space, consider the room required to provide airflow for cooling.


text:
Q: Angular asynchronous call is not ending while loop as expected

var app = angular.module('myApp', []);
    app.controller('myCtrl', function($scope, $http) {
    for(var i=0;i<2;i++){
       //var temp;
       $http.get("https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js")
      .then(function(response) {
          console.log("inside");
        //  temp=10;
       });
       //while(temp!=10){}
       console.log("outside")}
    });
<!DOCTYPE html>
<html ng-app="myApp" ng-controller="myCtrl">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
</html>

In this code i want to make print outside only after inside prints,mean unless i receive the response i want to make the loop wait and then go for second loop,for this i have defined a variable temp and i'm running a loop until its value becomes 10,but its going into infinite loop even after getting response (so commented )and setting temp value to 10.
Please help

A: You can first save the promise in a variable and then execute outside console inside the success of the promise. This will ensure that outside will be printed only once the inside promise resolves.

var app = angular.module('myApp', []);
    app.controller('myCtrl', function($scope, $http) {
    for(var i=0;i<2;i++){
       //var temp;
       var  q=$http.get("https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js")
      .then(function(response) {
          console.log("inside");
         temp=10;
       });
       q.then(function(res){
         while(temp!=10){}
         console.log("outside")
       })
       }
    });
<!DOCTYPE html>
<html ng-app="myApp" ng-controller="myCtrl">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
</html>

The idea in below fiddle can be used if you want to abstract the code into different functions and then call it recursively.
Working Fiddle: http://jsfiddle.net/rmu6wuo8/1/

A: When I got you right, you want to repeat a request until you get a specific value. Maybe this could work for you https://jsfiddle.net/jpf4c24m/2/
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http, $q) {

  $scope.request = function request(object) {
    var counter = 0;
    var deferred = $q.defer();

    var httpConfig = {
      method: 'GET',
      url: '/echo/json'
    }

    var doRequest = function() {
      counter++;
      var self = this,
        args = arguments;
      $http(httpConfig).
      success(function(data, status) {
        if (data.key == 'your_droid') {
          deferred.resolve('Woohoo!');

        } else {
          console.log('Not the droids you are looking for..');
          //this will re-call doRequest();
          args.callee.apply(self);
        }
      }).
      error(function(data, status) {
        //just fail already, it's not working
        if (counter > 5) {
          return deferred.reject('Couldnt reach server this time...');
        }

        //this will re-call doRequest();
        args.callee.apply(self);
      });

    }

    doRequest();

    return deferred.promise;
  }

  $scope.request();
});

got the idea by this answer.


text:
Q: Custom loader animation how can I implement a similar loading animation on flutter?
loader animation
I was looking for similar solutions out of the box, but I didn't find it, maybe it's worth applying drawing on a custom painter in conjunction with an animation controller?


text:
Q: detect tab characters with javascript in IE I want to detect and replace tab characters in a bit of HTML like this:

  something
  {    something else
  }
</code

Right now, I am using something like this:
$(this).html(replaceAll(trim($(this).html()), "\t", "   "));

But IE, in all its cleverness, changes tab characters into spaces, and so doing the above is useless. Does anyone know how I can detect tab characters in the HTML source with javascript for IE?

A: So, jmaglasang gave me a good idea. He said IE respects whitespace in a pre tag. So, I thought why not insert a pre tag with javascript, read the html, then remove the pre tag afterward. It works but theres a catch - you have to use a setTimeout callback. Heres the code:
$("code").each(function()
{   $(this).wrap("

");
    var element = $(this);

    setTimeout(function()   // read the html
    {   var x = element.html().split("");
        for(n in x)
        {    alert(x[n].charCodeAt(0) + " '" + x[n] + "'");
        }
    }, 0);
});

The setTimeout is neccessary because for some reason, IE waits to re-render the html until after all the javascript finishes running. Incidentally, it also waits to execute any callbacks issued by setTimeout. I wish I knew how I could force IE to render the html immediately... If anyone knows I'd definitely appreciate it.


text:
Q: Make selected text bold using javascript I have a text in my markup:

Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Vestibulum condimentum consectetur tellus, at bibendum felis ultrices eu.
Nullam nibh urna, euismod a blandit ut, fermentum a leo. Maecenas pharetra elementum fringilla.
Quisque condimentum, nibh quis elementum porttitor, magna libero malesuada dolor, ut feugiat tortor lectus ac turpis. Integer tristique molestie enim, sit amet commodo risus tempus non.

When user selects a text and presses CTRL+Enter I want to wrap the selected text with  tags. I got to getting the selected text, but cannot find how I can wrap it with the markup. Here is what I have:
function getSelectedText () {
    if (window.getSelection) {
        return window.getSelection ().toString ();
    }
    else {
        if (document.selection) {
            return document.selection.createRange ().text;
        }
    }
    return '';
}

$ (document).ready (function() {

    // User pressed a key
    $ (document).keydown (function(e) {
        // is it CTRL+ENTER?
    if (e.which == 13 && e.ctrlKey) {
            alert('You have selected ' + getSelectedText ());
            // now I need to highlight the text I got
            // ????
    }
    });
});

Please note! A simple find/replace does not do, if a user selected a single 'a' letter which can be found 10 times in the text, I want to highlight the only 'a' he selected. I've studied range objects, but can't figure out how to achieve it, help me out, please.
Please see demo at jsfiddle.

A: Perhaps this can help you: http://code.google.com/p/rangy/
one of the examples is exactly what you're after.

A: You could use document.execCommand() for this. Here's my answer to a similar question: Javascript: how to un-surroundContents range

A: This works (in Chrome), but so long as it's only called once!
(running code at http://jsfiddle.net/HaD6k/)
$(document).keypress(function(e) {
    if (e.which == 13 && e.ctrlKey) {
        var s = getSelection();
        var i = s.baseOffset;
        var j = s.extentOffset;
        var t = $('div').text();
        var t0 = t.substring(0, i) + '' +
                 t.substring(i, j) + '' +
                 t.substring(j);
        $('div').html(t0);
    }
});

The reason it only works once is because it modifies the DOM to add the tags, which means next time around the selection offsets and elements aren't contiguous.  I'm still looking at that...


text:
Q: Given $AO:OA' + BO:OB' + CO:OC' = 92$ find the value of $AO:OA' \times BO:OB' \times CO:OC'$.
In $\triangle ABC$, points $A',B',C'$ are on sides $BC,AC,AB$ respectively. $AA', BB', CC'$ are concurrent at point $O$.
  Given $AO:OA' + BO:OB' + CO:OC' = 92$ find the value of $AO:OA' \times BO:OB' \times CO:OC'$.

My work

I can find these relations -
$AO:OA' =[AOB]:[BOA'] = [AOC]:[COA']\\
 BO:OB' =[AOB]:[AOB'] = [COB]:[COB']\\
 CO:OC' =[AOC]:[AOC'] = [BOC]:[BOC']$
Now how to continue?
Source: BdMO 2015 national secondary.

A: Let $u,v,w$ be the ratios $\frac{BA'}{A'C},\frac{CB'}{B'A},\frac{AC'}{C'B}$.
By Van Obel's theorem
$$\frac{AO}{OA'}=w+\frac{1}{v}$$
and so on, hence we know that
$$ 92=(u+v+w)+\left(\frac{1}{u}+\frac{1}{v}+\frac{1}{w}\right)$$
and $uvw=1$ by Ceva's theorem. It follows that:
$$ \left(w+\frac{1}{v}\right)\left(v+\frac{1}{u}\right)\left(u+\frac{1}{w}\right)=(u+v+w)+\left(\frac{1}{u}+\frac{1}{v}+\frac{1}{w}\right)+\frac{1}{uvw}+uvw = \color{red}{94}.$$

In general, if $AA',BB',CC'$ concur at $O$, $$
 \prod_{cyc}\frac{AO}{OA'}=2+\sum_{cyc}\frac{AO}{OA'}.$$

A: Another way to solve this problem is to use the method of Mass Points. Assign the masses $a,b,c$ to the points $A, B, C$. This implies that we should assign the masses $(a+b), (b+c), (c+a), (a+b+c)$ to $C', A', B', O$. Then we have:
$$\frac{AO}{A'O} = \frac{b+c}{a} \quad \frac{BO}{B'O} = \frac{c+a}{b} \quad \frac{CO}{C'O} = \frac{a+b}{c}$$
Then using this we have:
$$92 = \frac{AO}{A'O} + \frac{BO}{B'O} + \frac{CO}{C'O} = \frac{b+c}{a} + \frac{c+a}{b} + \frac{a+b}{c} = \frac{bc(b+c) + ac(a+c) + ab(a+b)}{abc} = \frac{(a+b)(b+c)(c+a) - 2abc}{abc} = \frac{AO}{A'O} \times \frac{BO}{B'O} \times \frac{CO}{C'O} - 2$$
Therefore: $\frac{AO}{A'O} \times \frac{BO}{B'O} \times \frac{CO}{C'O} = 94$


text:
Q: Check exchange 2013 mailbox, for any un-answered emails and send an email alert (server side) I have been doing some research for sometime, trying to find if it is possible to do the following.
Send a email to X if a mailbox has emails that have not been replied to in 7 days. This mailbox will have out of office enabled so someone sending an email to this mailbox will get an auto reply. I have been asked if it is possible to have some sort of alert setup if the email received has not been physically replied to within 7 days.

*

*Out of office will be enabled on the mailbox

*Someone needs to know if any of the received has been replied to by an actual person, not the oof message

*server side, no client side rule

From my research i cannot find a way to accomplish this.
If anyone has any methods of accomplishing this, i would be very grateful for a solution. I have not found any powershell scripts that can do this as of yet!


text:
Q: setString vs. setStringValue in Cocoa I tried to use the method setString to change the text in a textfield and it didn't work. Then I changed it to setStringValue and it worked. So what is setString used for?

A: NSTextField does not have a setString: method. NSTextField is a type of NSControl, and NSControl has a setStringValue: method.
NSText and its more famous subclass NSTextView have a setString: method. @John Boker is correct that the field editor is an NSText, but you still can't send setString: to an NSTextField, even in edit mode. You'd need to get the field editor from the window and then call setString: on that (not that you really should do that).
While it is confusing to newcomers, there is a good rationale behind the different methods. NSControl has a "value", and that value can take different types (setDoubleValue:, setObjectValue:, etc.) This allows me to set the value as a double, but then retrieve in as a string. For the broad range of possible controls, this makes good sense and is very flexible. NSText is not a control; note how it doesn't have setAction: or setTarget: either. Its purpose is to display and edit (attributed) strings. When you call string, you are actually getting the real backing text storage, not just the value of the object in string form (as stringValue does for NSControl).
That said, when you say "it didn't work," I hope you mean that you got a compiler warning about this that told you that NSTextField may not respond to setString:. If you're ignoring compiler warnings, then you're going to have a lot of problems in ObjC.

A: from: http://macosx.com/forums/software-programming-web-scripting/43905-_outlet-setstring-testing-selector-not-recognized.html#5

setString: is for NSText, which is the
  class used for an NSTextField's field
  editor while it is being edited, and
  for the NSText subclass NSTextView
  which can display and edit styled text
  as in TextEdit.

So the way i take it is you can only use setString: when the field is in an edit mode, i think.

A: Going a bit more generically (in contrast to my comment on Rob's answer):
Objects respond to messages. You can send a message to any object that responds to that message; you can't send a message to any object that doesn't respond to it.
Instances of NSText and its subclass NSTextView respond to setString:, so you can send NSText objects and NSTextView objects setString: messages.
Instances of NSControl and its subclasses, including NSTextField, respond to setStringValue:, so you can send NSControl objects, NSTextField objects, and other control objects setStringValue: messages.
See Rob's answer and my comment on it for why these two specific branches of the class hierarchy have these seemingly-similar-but-differently-named methods.


text:
Q: Passing arrays from controller to view to again view This is my controller code..
 $data1['billing_info']=$this->billings->get_info1($billing_id);
    $data2['sale_info']=$this->billings->get_sale_info($billing_id);
    $data3['sale_payment_info']=$this->billings->get_sale_payment_info($billing_id);
    $data['all_modules']=$this->Module->get_all_modules();
    $array=array('data1'=>$data1,
                    'data2'=>$data2,'data3'=>$data3,);
                    print_r($array);
 $this->load->view("billing/form1",$array);

This is my form1.php code
<?php $this->load->view("billing/form_basic_info1"); ?>

So I again want to pass that $array to form_basic_info1 view. So how do I do that??

A: By default your sub views have access of the variables of the parent view.

A: In controller e.x you have $array['name'] and in first view you can access to $name, As I know you can't pass whole controller's array to second view. Try this in your view:
//first view
//you have access to $name from controller
$data['new_name'] = array();
foreach($name as $row){
    array_push($data['new_name'], $row->name);
}
//pass $data to other view


text:
Q: MySQL select highest users highest ranked group doublets My problem is that in the result a user can be in it more then one time if he is in more then 1 higher ranked group.
SELECT xf_user_group_relation.user_id , xf_user_identity.account_name, xf_user_group_relation.user_group_id, MAX( xf_user_group.display_style_priority ) AS display_style_priority
FROM xf_user_group_relation
INNER JOIN xf_user_group ON xf_user_group_relation.user_group_id = xf_user_group.user_group_id
INNER JOIN xf_user_identity ON xf_user_group_relation.user_id = xf_user_identity.user_id
WHERE xf_user_group.display_style_priority >=1000 AND identity_service_id = 'Minecraft'
GROUP BY xf_user_group_relation.user_id, xf_user_group_relation.user_group_id, xf_user_identity.account_name

Result:
|user_id|account_name|user_group_id|display_style_priority|
|1|yuriman|5|10000
|1|yuriman|6|9000
|2|skull905|5|10000
|13|ryan1271|5|10000
|21|mr_matt|9|6000
|37|Gaurav251|12|1000
|38|tvmaniac9|9|6000
|38|tvmaniac9|11|2000
|44|robyrq|9|6000
|44|robyrq|12|1000
|86|sabasNL|11|2000
|86|sabasNL|15|5200
|128|Scarykittens|9|6000
|133|Sargent5|10|5000
|133|Sargent5|11|2000
|142|kevy76|9|6000
|142|kevy76|11|2000
|144|liljew29|10|5000
|144|liljew29|11|2000
|149|a7xtdgfan332|10|5000
|160|TheNeoStrike|11|2000
|189|CptToddney|11|2000

The result should look like this:
|user_id|account_name|user_group_id|display_style_priority|
|1|yuriman|5|10000
|2|skull905|5|10000
|13|ryan1271|5|10000
|21|mr_matt|9|6000
|37|Gaurav251|12|1000
|38|tvmaniac9|9|6000
|44|robyrq|9|6000
|86|sabasNL|11|2000
|128|Scarykittens|9|6000
|133|Sargent5|10|5000
|142|kevy76|9|6000
|144|liljew29|10|5000
|149|a7xtdgfan332|10|5000
|160|TheNeoStrike|11|2000
|189|CptToddney|11|2000

I want the result to have the users highest ranked group only which is the one with the highest display_style_priority.
Im not sure how to fix that.
Best Regards

A: i think you need to change the group by
GROUP BY xf_user_group_relation.user_id, xf_user_identity.account_name


text:
Q: How to make a optional group, but if the group exists most match with my regex? I have this JS regex:
var re = /(\w\w\d-{1})?\w\w-{1}\w-{1}?/;

For file name, and the first group must be optional:
Complete name example. Example:
qq8-qq-q-anything => OK

Without first group:
qq-q-anything => OK

But if I put anything, still worked:
anything-qq-q-anything => OK
I want the first group to be optinal, but if the file name has the first group it must match with my regex word wor digit.

A: You should specify that the string should "start with" your regex, so only add ^ to specify the start point.

const re = /^(\w\w\d-{1})?\w\w-{1}\w-{1}?/;

const strs = ['qq8-qq-q-anything', 'qq-q-anything', 'anything-qq-q-anything'];

const result = strs.map(str => re.test(str));

console.log(result);

A: \w matches both digits and letters. It includes _ character too. You should explicitly use a character class for letters and anchor your regex with circumflex ^ to assert start of input string. You don't need to have {1} quantifier either since a preceding pattern is only checked once unless defined otherwise. You may need i (case-insensitive) flag too:
var re = /^(?:[a-z]{2}\d-)?[a-z]{2}-[a-z]-/i;

Live demo


text:
Q: Compatibility/ Documentation with ML.NET on MVC5 I've read online and watched some videos concerning ML.NET and the usage of it. All the videos and documentation that I've read online were on ASP.NET Core. I was wondering if it was possible to use the ML.NET on MVC5 (Since that's what we've been taught in class and have to use for our project)
If it is compatible are there any links or suggestions on how to go about it?

A: ML.NET requires .NET Core in version 2.1 (or newer) or .NET Framework version 4.6.1 (or newer):

First, ensure you have installed .NET Core 2.1 or later. ML.NET also works on the .NET Framework 4.6.1 or later, but 4.7.2 or later is recommended.

Source: GitHub page for ML.NET
As long as your app is running on one of those .NET implementations, you should be good to go. Regardless of the app type (ASP.NET, Winforms, ...).
You can find samples here.


text:
Q: Can not send email from android apps I want to send an email from android without user interaction. I use this code Send email from android
It's running good on my Samsung phone(which version is 2.3.2 and API label 9). But the same app is not working in my Walton phone (which version is 4.2.2 and API label 17). I use minsdk 8 and targetsdk 19.
Here is my manifest file
<?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.hiddencamera"
        android:versionCode="1"
        android:versionName="1.0" >

        <uses-sdk
            android:minSdkVersion="8"
            android:targetSdkVersion="19" />

         <uses-permission android:name="android.permission.CAMERA" />
        <uses-feature android:name="android.hardware.camera" android:required="false" />
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
        <uses-permission android:name="android.permission.RECORD_AUDIO" />

         <uses-permission android:name="android.permission.INTERNET" />
      <uses-permission android:name="android.permission.INTERNET" />
        <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
        <uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

        <application
            android:allowBackup="true"
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name"
            android:theme="@style/AppTheme" >
            <activity
                android:name="com.hiddencamera.Main"
                android:label="@string/app_name" >
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />

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

    </manifest>

A: You can refer to the following code. It works fine.
public class Email extends Activity implements View.OnClickListener {

    EditText personsEmail, intro, personsName, stupidThings, hatefulAction,
            outro;
    // Your mail address here
    String emailAdd;
    Button sendEmail;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.email);
        initializeVars();
        sendEmail.setOnClickListener(this);
    }

    private void initializeVars() {
        // TODO Auto-generated method stub
        sendEmail = (Button) findViewById(R.id.bSentEmail);
    }

    public void onClick(View v) {
        // TODO Auto-generated method stub
        //Your mail addresses needs to be converted to Array/List before passing, so you can append more mail_id's too
        String emailaddress[] = { emailAdd };
        String message = "Your mail content here ";

        Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
        emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, emailaddress);
        emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject of the mail");
        emailIntent.setType("plain/text");
        emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, message);
        startActivity(emailIntent);

    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        finish();
    }

}

In Manifest just remember to add the permission for Internet once only. You have mentioned it twice.Though it do not have any effect I thunk, but still you should be careful with everything.


text:
Q: Jenkins Git Changelog Plugin throwing "no protocol" error when talking to JIRA I am trying to figure out how to get the Git Changelog Plugin to pull issue information from our JIRA server. But I'm getting "no protocol" errors like this:
java.net.MalformedURLException: no protocol: /rest/api/2/issue/JIRA-1234?fields=parent,summary,issuetype,labels,description

Details follow. Does anyone happen to see what I'm doing wrong here?
Research: I got zero hits searching StackOverflow for "jenkins git changelog plugin throwing no protocol error talking to jira". I got one hit for "jenkins git changelog plugin no protocol" but it does not appear relevant. I cannot seem to find specific examples of invoking the Git Changelog Plugin from a scripted pipeline, with JIRA integration, anywhere online.
DETAILS
I'm using the following syntax to invoke the Git Changelog Plugin v2.11 from a Jenkins v2.144 pipeline:
        withCredentials([[
            $class: 'UsernamePasswordMultiBinding',
            credentialsId: 'JiraUserCredentials',
            usernameVariable: 'jiraUserName',
            passwordVariable: 'jiraUserPw'
        ]]) {
            changelogString = gitChangelog returnType: 'STRING',
                from: [type: 'COMMIT', value: startCommitHash],
                to: [type: 'COMMIT', value: endCommitHash],
                jira: [
                    issuePattern: '\\b[A-Z]([A-Z]+)-([0-9]+)\\b',
                    password: '$jiraUserPw',
                    server: 'https://my.jira.server/jira/',
                    username: '$jiraUserName'
                    ],
                template: template
        }

The Mustache template I am passing in refers to information from JIRA issues using the {{title}} and {{type}} tags. The Jenkins pipeline "succeeds" but no information is retrieved from JIRA. The master Jenkins log shows the following stack trace:
GET:
/rest/api/2/issue/JIRA-1234?fields=parent,summary,issuetype,labels,description
Oct 01, 2018 11:42:05 AM SEVERE se.bjurr.gitchangelog.internal.integrations.rest.RestClient doGet
Got:
null
java.net.MalformedURLException: no protocol: /rest/api/2/issue/JIRA-1234?fields=parent,summary,issuetype,labels,description
                at java.net.URL.<init>(URL.java:593)
                at java.net.URL.<init>(URL.java:490)
                at java.net.URL.<init>(URL.java:439)
                at se.bjurr.gitchangelog.internal.integrations.rest.RestClient.doGet(RestClient.java:63)
                at se.bjurr.gitchangelog.internal.integrations.rest.RestClient.access$000(RestClient.java:21)
                at se.bjurr.gitchangelog.internal.integrations.rest.RestClient$1.load(RestClient.java:35)
                at se.bjurr.gitchangelog.internal.integrations.rest.RestClient$1.load(RestClient.java:32)
                at com.google.common.cache.LocalCache$LoadingValueReference.loadFuture(LocalCache.java:3568)
                at com.google.common.cache.LocalCache$Segment.loadSync(LocalCache.java:2350)
                at com.google.common.cache.LocalCache$Segment.lockedGetOrLoad(LocalCache.java:2313)
                at com.google.common.cache.LocalCache$Segment.get(LocalCache.java:2228)
                at com.google.common.cache.LocalCache.get(LocalCache.java:3965)
                at com.google.common.cache.LocalCache.getOrLoad(LocalCache.java:3969)
                at com.google.common.cache.LocalCache$LocalManualCache.get(LocalCache.java:4829)
                at se.bjurr.gitchangelog.internal.integrations.rest.RestClient.get(RestClient.java:52)
                at se.bjurr.gitchangelog.internal.integrations.jira.DefaultJiraClient.getIssue(DefaultJiraClient.java:29)
                at se.bjurr.gitchangelog.internal.issues.IssueParser.createParsedIssue(IssueParser.java:200)
                at se.bjurr.gitchangelog.internal.issues.IssueParser.parseForIssues(IssueParser.java:82)
                at se.bjurr.gitchangelog.api.GitChangelogApi.getChangelog(GitChangelogApi.java:456)
                at se.bjurr.gitchangelog.api.GitChangelogApi.getChangelog(GitChangelogApi.java:77)
                at se.bjurr.gitchangelog.api.GitChangelogApi.render(GitChangelogApi.java:99)
                at se.bjurr.gitchangelog.api.GitChangelogApi.render(GitChangelogApi.java:123)
                at org.jenkinsci.plugins.gitchangelog.steps.GitChangelogStep.perform(GitChangelogStep.java:404)
                at org.jenkinsci.plugins.gitchangelog.steps.GitChangelogStep.access$000(GitChangelogStep.java:44)
                at org.jenkinsci.plugins.gitchangelog.steps.GitChangelogStep$1$1.call(GitChangelogStep.java:322)
                at hudson.FilePath.act(FilePath.java:1163)
                at org.jenkinsci.plugins.gitchangelog.steps.GitChangelogStep$1.run(GitChangelogStep.java:326)
                at org.jenkinsci.plugins.workflow.steps.SynchronousNonBlockingStepExecution$1$1.call(SynchronousNonBlockingStepExecution.java:50)
                at hudson.security.ACL.impersonate(ACL.java:290)
                at org.jenkinsci.plugins.workflow.steps.SynchronousNonBlockingStepExecution$1.run(SynchronousNonBlockingStepExecution.java:47)
                at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
                at java.util.concurrent.FutureTask.run(FutureTask.java:266)
                at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
                at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
                at java.lang.Thread.run(Thread.java:748)

A: It turns the syntax I'm using above to invoke the Git Changelog Plugin and interface with JIRA is fine. The problem was that I was running the job on a Jenkins node that did not have access to the company's JIRA server. (The Jenkins node was running in the public cloud.) Once I updated the plan to run the job on a Jenkins node that did have access to the company's JIRA server (on-prem), the plan was able to contact JIRA and pull down attributes of JIRA issues successfully.


text:
Q: Why does transform canvas change where the caption is? I have a fairly large tikz diagram here:
\documentclass[12pt]{amsart}
\usepackage[all,cmtip]{xy}
\usepackage{rotating, tikz}
\usetikzlibrary{matrix,arrows}

\title{None}%

\begin{document}

\begin{sidewaysfigure}[p]
\vspace*{350pt}
\hspace{50pt}
\begin{tikzpicture} [description/.style={fill=white,inner sep=2pt}]
    \matrix (m) [matrix of math nodes, row sep=31pt,
    column sep=40pt, text height=1.5ex, text depth=0.25ex]
    { \\ \\ \\ \underset{v_0}{\bullet} & \underset{v_1}{\bullet} & \underset{v_2}{\bullet} & \underset{v_3}{\bullet} & \cdots & \underset{v_{\lambda - 3}}{\bullet} & \underset{v_{\lambda - 2}}{\bullet} & \underset{v_{\lambda - 1}}{\bullet} & \underset{v_\lambda}{\bullet} \\ \\ \\ \\ \\ \\ \\ \\ \underset{\hat v_0}{\bullet} & \underset{\hat v_1}{\bullet} & \underset{\hat v_2}{\bullet} & \underset{\hat v_3}{\bullet} & \cdots & \underset{\hat v_{\lambda - 3}}{\bullet} & \underset{\hat v_{\lambda - 2}}{\bullet} & \underset{\hat v_{\lambda - 1}}{\bullet} & \underset{\hat v_\lambda}{\bullet} \\};
    \path[->,font=\scriptsize]
    (m-4-1) edge [bend left=20] node[auto] {$1$} (m-4-2)
    (m-4-2) edge [bend left=20] node[auto] {$\lambda$} (m-4-1)
            edge [bend left=20] node[auto] {$2$} (m-4-3)
    (m-4-3) edge [bend left=20] node[auto] {$\lambda - 1$} (m-4-2)
            edge [bend left=20] node[auto] {$3$} (m-4-4)
    (m-4-4) edge [bend left=20] node[auto] {$\lambda - 2$} (m-4-3)
            edge [bend left=20] node[auto] {$4$} (m-4-5)
    (m-4-5) edge [bend left=20] node[auto] {$\lambda - 3$} (m-4-4)
            edge [bend left=20] node[auto] {$\lambda - 3$} (m-4-6)
    (m-4-6) edge [bend left=20] node[auto] {$4$} (m-4-5)
            edge [bend left=20] node[auto] {$\lambda - 2$} (m-4-7)
    (m-4-7) edge [bend left=20] node[auto] {$3$} (m-4-6)
            edge [bend left=20] node[auto] {$\lambda - 1$} (m-4-8)
    (m-4-8) edge [bend left=20] node[auto] {$2$} (m-4-7)
            edge [bend left=20] node[auto] {$\lambda$} (m-4-9)
    (m-4-9) edge [bend left=20] node[auto] {$1$} (m-4-8);
    \draw[<-] (m-4-1) .. controls +(70:50pt) and +(110:50pt) .. node[pos=.5, above]{\scriptsize $\lambda$} (m-4-1);
    \draw[<-] (m-4-2) .. controls +(70:50pt) and +(110:50pt) .. node[pos=.5, above]{\scriptsize $\lambda - 2$} (m-4-2);
    \draw[<-] (m-4-3) .. controls +(70:50pt) and +(110:50pt) .. node[pos=.5, above]{\scriptsize $\lambda - 4$} (m-4-3);
    \draw[<-] (m-4-4) .. controls +(70:50pt) and +(110:50pt) .. node[pos=.5, above]{\scriptsize $\lambda - 6$} (m-4-4);
    \draw[<-] (m-4-6) .. controls +(70:50pt) and +(110:50pt) .. node[pos=.5, above]{\scriptsize $6 - \lambda$} (m-4-6);
    \draw[<-] (m-4-7) .. controls +(70:50pt) and +(110:50pt) .. node[pos=.5, above]{\scriptsize $4 - \lambda$} (m-4-7);
    \draw[<-] (m-4-8) .. controls +(70:50pt) and +(110:50pt) .. node[pos=.5, above]{\scriptsize $2 - \lambda$} (m-4-8);
    \draw[<-] (m-4-9) .. controls +(70:50pt) and +(110:50pt) .. node[pos=.5, above]{\scriptsize $-\lambda$} (m-4-9);
    \path[draw] (-4.1, -2) rectangle (3.7, 0);
    \draw (-3.5, -1) node {$e$:};
    \draw[<-] (-3.2, -1) .. controls +(-20:18pt) and +(200:18pt) .. (-1.7, -1);
    \draw (-.5, -1) node {$f$:};
    \draw[->] (-.2, -1) .. controls +(20:18pt) and +(160:18pt) .. (1.3, -1);
    \draw (2.5, -1) node {$h$:};
    \draw[<-] (3.1, -1.5) .. controls +(70:40pt) and +(110:40pt) ..  (2.9, -1.5);
    \draw (-.5, 5) node {$V(\lambda)$};
    \path[->,font=\scriptsize]
    (m-12-1) edge [bend left=20] node[auto] {$\lambda$} (m-12-2)
    (m-12-2) edge [bend left=20] node[auto] {$1$} (m-12-1)
            edge [bend left=20] node[auto] {$\lambda - 1$} (m-12-3)
    (m-12-3) edge [bend left=20] node[auto] {$2$} (m-12-2)
            edge [bend left=20] node[auto] {$\lambda - 2$} (m-12-4)
    (m-12-4) edge [bend left=20] node[auto] {$3$} (m-12-3)
            edge [bend left=20] node[auto] {$\lambda - 3$} (m-12-5)
    (m-12-5) edge [bend left=20] node[auto] {$4$} (m-12-4)
            edge [bend left=20] node[auto] {$4$} (m-12-6)
    (m-12-6) edge [bend left=20] node[auto] {$\lambda - 3$} (m-12-5)
            edge [bend left=20] node[auto] {$3$} (m-12-7)
    (m-12-7) edge [bend left=20] node[auto] {$\lambda - 2$} (m-12-6)
            edge [bend left=20] node[auto] {$2$} (m-12-8)
    (m-12-8) edge [bend left=20] node[auto] {$\lambda - 1$} (m-12-7)
            edge [bend left=20] node[auto] {$1$} (m-12-9)
    (m-12-9) edge [bend left=20] node[auto] {$\lambda$} (m-12-8);
    \draw[<-] (m-12-1) .. controls +(70:50pt) and +(110:50pt) .. node[pos=.5, above]{\scriptsize $\lambda$} (m-12-1);
    \draw[<-] (m-12-2) .. controls +(70:50pt) and +(110:50pt) .. node[pos=.5, above]{\scriptsize $\lambda - 2$} (m-12-2);
    \draw[<-] (m-12-3) .. controls +(70:50pt) and +(110:50pt) .. node[pos=.5, above]{\scriptsize $\lambda - 4$} (m-12-3);
    \draw[<-] (m-12-4) .. controls +(70:50pt) and +(110:50pt) .. node[pos=.5, above]{\scriptsize $\lambda - 6$} (m-12-4);
    \draw[<-] (m-12-6) .. controls +(70:50pt) and +(110:50pt) .. node[pos=.5, above]{\scriptsize $6 - \lambda$} (m-12-6);
    \draw[<-] (m-12-7) .. controls +(70:50pt) and +(110:50pt) .. node[pos=.5, above]{\scriptsize $4 - \lambda$} (m-12-7);
    \draw[<-] (m-12-8) .. controls +(70:50pt) and +(110:50pt) .. node[pos=.5, above]{\scriptsize $2 - \lambda$} (m-12-8);
    \draw[<-] (m-12-9) .. controls +(70:50pt) and +(110:50pt) .. node[pos=.5, above]{\scriptsize $-\lambda$} (m-12-9);
    \draw (-.5, -4) node {$V(\lambda)^\ast$};
\end{tikzpicture}
\caption{Graphs of $V(\lambda)$ and $V(\lambda)^\ast$} \label{figV}
\end{sidewaysfigure}

\end{document}

I would like to shrink it.  When I change
\begin{tikzpicture}    [description/.style={fill=white,inner sep=2pt}]
to
\begin{tikzpicture}    [description/.style={fill=white,inner sep=2pt}, transform canvas={scale=.7}]
The caption moves to the side of the figure and I can't figure out why or how to stop it from happening.  Any suggestions?

A: The manual states: "Tracking of the picture size is (locally) switched off …"
This means that the bounding box is lost, which needs to be specified manually via the \useasboundingbox path (= \path[use as bounding box]) which also needs to be outside of the scope that has transform canvas applied to.
You might consider the necessarity to transform your whole picture (this also affects font-sizes!).
Notes

*

*I replaced your \hspace macro with the \centering macro.

*The \vpsace* is not needed with other classes like article. I don't know what amsart does here.

*The backgrounds library and its keys show background grid and show background rectangle are only temporarily used as they show the bounding box visually.

Code
\documentclass[12pt]{amsart}
\usepackage{rotating, tikz}
\usetikzlibrary{matrix,arrows,backgrounds}

\title{None}%

\begin{document}

\begin{sidewaysfigure}
\centering
\vspace*{350pt}
\begin{tikzpicture}[description/.style={fill=white,inner sep=2pt},show background grid,show background rectangle]
    \useasboundingbox (-6.5,-5) rectangle (6.5,4);
    \scope[transform canvas={scale=.7}]
         % Your actual drawing
    \endscope
\end{tikzpicture}
\caption{Graphs of $V(\lambda)$ and $V(\lambda)^\ast$} \label{figV}
\end{sidewaysfigure}
\end{document}

Output


text:
Q: Proof by Induction of a Recursively Defined Sequence The question I'm currently struggling with is:

Consider the following recursively defined sequence:
$$\ a_1 = 0, a_{n+1}= \frac{a^2_n+4}{5} $$
a) Show by induction that $0\le a_n \le 1 $ for all n
b) Prove that if $a_n$ converges, so that $\lim_{n\to \infty}a_n=A$ then $A^2−5A+4 =0$, and thus $A = 1$.
c) Prove by induction that $a_n$ is strictly increasing, $a_{n+1}>a_n$ for all n.
d) Conclude that $\lim_{n \to\infty}a_n$ exists, and thus that $\lim_{n \to \infty}a_n=1$

I've managed to complete part a) where I did:
Basis - at $n=1$ $a_{1+1}=\frac{0+4}{5}$
Inductive Hypothesis - for k as an element of the natural numbers, it is always true that $0 \le a_{k+1} \le 1$ where $a_{k+1}=\frac{a_k+4}{5}$
Inductive Step - Here I tried to prove it by making $n=k+1$ which meant
$a_{k+2}= \frac{a_k+1^2+4}{5}$
which I split in to $\frac{a_k+1^2}{5}+\frac{4}{5}$
and from the inductive hypothesis I know that $0 \le a_{k+1} \le 1$ and therefore it's evident that  $\frac{a_k+1^2}{5}$ can take a minimum value of $\frac{0}{5}$ and a minimum value of $\frac{1}{5}$
Part b) seems relatively simple as you can prove
$A^2−5A+4 =0$ quite easily but I'm unsure how to get the equation in the first place. I think it has something to do with rearranging:
$a_{k+1}= \frac{a^2_k+4}{5} $
Part c) is the part I'm struggling with most and the answer in my notes doesn't really explain to me how it's done.
I did the basis and my inductive hypothesis and at the inductive step I got to:
$a_{k+1}^2-5a_{k+1}+4>0$ but I'm not sure what to do after this
Would anyone mind helping me with part c) and d)?

A: It is $$a_{k+1}^2-5a_{k+1}+4>0$$ and not $a_{k+1}^2-5a_{k+1}-4>0$. So you have $$(a_{k+1}-1)(a_{k+1}-4)>0$$
which is true by a).

A: The inductive step for the monotonicity (c) is just
$$
 a_{n+1} > a_n \implies \frac{a^2_{n+1}+4}{5} > \frac{a^2_n+4}{5} \implies  a_{n+2} >  a_{n+1}
$$
The first implication holds because $a_n \ge 0$.
The convergence (d) then follows from the monotone convergence theorem.

A: b) The argument is that at the fixed point, which has the value A,
$$a_{k+1}=a_{k}=A$$
So
$$a_{k+1}=\frac{a_k^2+4}{5}$$
becomes
$$A=\frac{A^2+4}{5}$$
$$5A=A^2+4$$
$$A^2+5A+4=0$$

A: a) By the assumption of the induction we obtain:
$$0\leq a_{n+1}=\frac{a_n^2+4}{5}<\frac{1^2+4}{5}=1.$$
b),c) $$a_{n+1}-a_n=\frac{a_n^2+4}{5}-a_n=\frac{(a_n-1)(a_n-4)}{5}>0,$$
which says that $a$ increases and bounded.
Thus, there is $\lim\limits_{n\rightarrow+\infty}a_n$ and let this limit be equal to $A$.
Thus, by theorems about limits we obtain: $$A^2-5A+4=0,$$ which gives $A=1$.
I like the following way:
$$|a_{n+1}-1|=\left|\frac{a_n^2+4}{5}-1\right|=\frac{a_n+1}{5}|a_n-1|<\frac{2}{5}|a_n-1|<...<\left(\frac{2}{5}\right)^n|a_1-1|\rightarrow0,$$
Which says $$\lim_{n\rightarrow+\infty}a_n=1.$$


text:
Q: How to move the main entry file path to index.json? I'm building a jquery/sass project and I need to export the javascript and the scss file to node.
Using the main field in the package.json file I can link the main entry point which if the package was only a jquery module, I'd point to the main javascript file dist/jquery.package.js
But since I work with node-sass too, I need to export the path to the package too in order to use the sass bindings. To do so, I have to create a index.js file in which I have to resolve the path to the package:
index.js file would looke like this:
var path = require( "path" );

module.exports = {
  includePaths: [
    path.join( __dirname )
  ]
};

To make the node-sass bindings works, I have to change the main field in the package.json file from dist/jquery.package.js to index.js but by doing so, I would lose the the chace to export my jquery plugin.
Is it possible to move the main entry path dist/jquery.package.json inside index.js along with the includePaths for node-sass option?
How can I do both?

A: Use browser field at package.json. Example:
{
  ...
  "main": "index.js",
  "browser": "dist/jquery.package.js",
  ...
}


text:
Q: How do I get the day month and year from a Windows cmd.exe script? How do I get the current day month and year from inside a Windows cmd script? I need to get each value into a separate variable.

A: LANGUAGE INDEPENDENCY:
The Andrei Coscodan solution is language dependent, so a way to try to fix it is to reserve all the tags for each field: year, month and day on target languages. Consider Portugese and English, after the parsing do a final set as:
set Year=%yy%%aa%
set Month=%mm%
set Day=%dd%

Look for the year setting, I used both tags from English and Portuguese, it worked for me in Brazil where we have these two languages as the most common in Windows instalations. I expect this will work also for some languages with Latin origin like as French, Spanish, and so on.
Well, the full script could be:
@echo off
setlocal enabledelayedexpansion

:: Extract date fields - language dependent
for /f "tokens=1-4 delims=/-. " %%i in ('date /t') do (
        set v1=%%i& set v2=%%j& set v3=%%k
        if "%%i:~0,1%%" gtr "9" (set v1=%%j& set v2=%%k& set v3=%%l)

        for /f "skip=1 tokens=2-4 delims=(-)" %%m in ('echo.^|date') do (
            set %%m=!v1!& set %%n=!v2!& set %%o=!v3!
    )
)

:: Final set for language independency (English and Portuguese - maybe works for Spanish and French)
set year=%yy%%aa%
set month=%mm%
set day=%dd%

:: Testing
echo Year:[%year%] - month:[%month%] - day:[%day%]

endlocal
pause

I hope this helps someone that deal with diferent languages.

A: The only reliably way I know is to use VBScript to do the heavy work for you. There is no portable way of getting the current date in a usable format with a batch file alone. The following VBScript file
Wscript.Echo("set Year=" & DatePart("yyyy", Date))
Wscript.Echo("set Month=" & DatePart("m", Date))
Wscript.Echo("set Day=" & DatePart("d", Date))

and this batch snippet
for /f "delims=" %%x in ('cscript /nologo date.vbs') do %%x
echo %Year%-%Month%-%Day%

should work, though.
While you can get the current date in a batch file with either date /t or the %date% pseudo-variable, both follow the current locale in what they display. Which means you get the date in potentially any format and you have no way of parsing that.

A: This variant works for all localizations:
@echo off
FOR /F "skip=1 tokens=1-6" %%A IN ('WMIC Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year /Format:table') DO (
    if "%%B" NEQ "" (
        SET /A FDATE=%%F*10000+%%D*100+%%A
    )
)
@echo on
echo date=%FDATE%
echo year=%FDATE:~2,2%
echo month=%FDATE:~4,2%

A: To get the year, month, and day you can use the %date% environment variable and the :~ operator.  %date% expands to something like Thu 08/12/2010 and :~ allows you to pick up specific characters out of a variable:
set year=%date:~10,4%
set month=%date:~4,2%
set day=%date:~7,2%
set filename=%year%_%month%_%day%

Use %time% in similar fashion to get what you need from the current time.
set /? will give you more information on using special operators with variables.

A: The following batch code returns the components of the current date in a locale-independent manner and stores day, month and year in the variables CurrDay, CurrMonth and CurrYear, respectively:
for /F "skip=1 delims=" %%F in ('
    wmic PATH Win32_LocalTime GET Day^,Month^,Year /FORMAT:TABLE
') do (
    for /F "tokens=1-3" %%L in ("%%F") do (
        set CurrDay=0%%L
        set CurrMonth=0%%M
        set CurrYear=%%N
    )
)
set CurrDay=%CurrDay:~-2%
set CurrMonth=%CurrMonth:~-2%
echo Current day  :  %CurrDay%
echo Current month:  %CurrMonth%
echo Current year :%CurrYear%

There are two nested for /F loops to work around an issue with the wmic command, whose output is in unicode format; using a single loop results in additional carriage-return characters which impacts proper variable expansion.
Since day and month may also consist of a single digit only, I prepended a leading zero 0 in the loop construct. Afterwards, the values are trimmed to always consist of two digits.

A: I have converted to using Powershell calls for this purpose in my scripts. It requires script execution permission and is by far the slowest option. However it is also localization independent, very easy to write and read, and it is much more feasible to perform adjustments to the date like addition/subtraction or get the last day of the month, etc.
Here is how to get the day, month, and year
for /f %%i in ('"powershell (Get-Date).ToString(\"dd\")"') do set day=%%i
for /f %%i in ('"powershell (Get-Date).ToString(\"MM\")"') do set month=%%i
for /f %%i in ('"powershell (Get-Date).ToString(\"yyyy\")"') do set year=%%i

Or, here is yesterday's date in yyyy-MM-dd format
for /f %%i in ('"powershell (Get-Date).AddDays(-1).ToString(\"yyyy-MM-dd\")"') do set yesterday=%%i
Day of the week
for /f %%d in ('"powershell (Get-Date).DayOfWeek"') do set DayOfWeek=%%d
Current time plus 15 minutes
for /f %%i in ('"powershell (Get-Date).AddMinutes(15).ToString(\"HH:mm\")"') do set time=%%i

A: A variant of script that works locale-independently. Put it in a text file with .cmd extension and run.
::: Begin set date

for /f "tokens=1-4 delims=/-. " %%i in ('date /t') do (call :set_date %%i %%j %%k %%l)
goto :end_set_date

:set_date
if "%1:~0,1%" gtr "9" shift
for /f "skip=1 tokens=2-4 delims=(-)" %%m in ('echo,^|date') do (set %%m=%1&set %%n=%2&set %%o=%3)
goto :eof

:end_set_date
::: End set date

echo day in 'DD' format is %dd%; month in 'MM' format is %mm%; year in 'YYYY' format is %yy%

The variables %dd%, %mm% and %yy% will keep the day('DD' format), the month('MM' format) and the year('YYYY' format) respectively.

A: I think that Andrei Coscodan answer is the best when you can't make many assumptions.  But sometimes having a one-liner is nice if you can make some some assumptions.  This solution assumes that 'date \t' will return one of two formats.  On WindowsXP 'date /t 'returns "11/23/2011", but on Windows7 it returns "Wed 11/23/2011".
FOR /f "tokens=1-4 delims=/ " %%a in ('date /t') do (set mm=%%a&set dd=%%b&set yyyy=%%c& (if "%%a:~0,1" gtr "9" set mm=%%b&setdd=%%c&set yyyy=%%d))
:: Test results
echo day in 'DD' format is '%dd%'; month in 'MM' format is '%mm%'; year in 'YYYY' format is '%yyyy%'

Thanks to Andrei Consodan answer to help me with this one-line solution.

A: For one line!

Try using for wmic OS Get localdatetime^|find "." in for /f without tokens and/or delims, this works in any language / region and also, no user settings interfere with the layout of the output.

*

*In command line:

for /f %i in ('wmic OS Get localdatetime^|find "."')do @cmd/v/c "set _date=%i &echo= year: !_date:~0,4!&&echo=month:   !_date:~4,2!&echo=  day:   !_date:~6,2!"

*

*In bat/cmd file:

for /f %%i in ('wmic OS Get localdatetime^|find "."')do @cmd/v/c "set _date=%%i &echo= year: !_date:~0,4!&&echo=month:   !_date:~4,2!&echo=  day:   !_date:~6,2!"

Results:

 year: 2019
month:   06
  day:   12

*

*With Hour and Minute in bat/cmd file:

for /f %%i in ('wmic OS Get localdatetime^|find "."')do @cmd/v/c "set _date=%%i &echo=  year: !_date:~0,4!&&echo= month:   !_date:~4,2!&echo=   day:   !_date:~6,2!&echo=  hour:   !_date:~8,2!&echo=minute:   !_date:~10,2!"

*

*With Hour and Minute in command line:

for /f %i in ('wmic OS Get localdatetime^|find "."')do @cmd/v/c "set _date=%i &echo=  year: !_date:~0,4!&&echo= month:   !_date:~4,2!&echo=   day:   !_date:~6,2!&echo=  hour:   !_date:~8,2!&echo=minute:   !_date:~10,2!"

Results:

  year: 2020
 month:   05
   day:   16
  hour:   00
minute:   46

A: echo %Date:~7,2% gets current day

7 is starting position
2 number of digits to display
echo %Date:~7,2% gets current day

echo %Date:~4,2% gets current month

echo %Date:~10,4% gets current year

A: Extract Day, Month and Year
The highest voted function and the accepted one do NOT work locale-independently since the DATE command is subject to localization too. For example (the accepted one): In English you have YYYY for year and in Holland it is JJJJ. So this is a no-go. The following script takes the users' localization from the registry, which is locale-independent.
@echo off

::: Begin set date
setlocal EnableExtensions EnableDelayedExpansion

:: Determine short date format (independent from localization) from registry
for /f "skip=1 tokens=3-5 delims=- " %%L in ( '2^>nul reg query "HKCU\Control Panel\International" /v "sShortDate"' ) do (

    :: Since we can have multiple (short) date formats we only use the first char from the format in a new variable
    set "_L=%%L" && set "_L=!_L:~0,1!" && set "_M=%%M" && set "_M=!_M:~0,1!" && set "_N=%%N" && set "_N=!_N:~0,1!"

    :: Now assign the date values to the new vars
    for /f "tokens=2-4 delims=/-. " %%D in ( "%date%" ) do ( set "!_L!=%%D" && set "!_M!=%%E" && set "!_N!=%%F" )
)

:: Print the values as is
echo.
echo This is the original date string --^> %date%
echo These are the splitted values    --^> Day: %d%, Month:%m%, Year: %y%.
echo.

endlocal

Extract only the Year
For a script I wrote I wanted only to extract the year (locale-independent) so I came up with this oneliner as I couldn't find any solution.  It uses the 'DATE' var, multiple delimiters and checks for a number greater than 31. That then will be the current year. It's low on resources in contrast to some of the other solutions.
@echo off

setlocal EnableExtensions

for /f " tokens=2-4 delims=-./ " %%D in ( "%date%" ) do ( if %%D gtr 31 ( set "_YEAR=%%D" ) else ( if %%E gtr 31 ( set "_YEAR=%%E" ) else ( if %%F gtr 31 ( set "_YEAR=%%F" ) ) ) )

echo And the year is... %_YEAR%.
echo.

endlocal

A: You can use simple variable syntax, here is an example:
@echo off
set month=%date:~0,2%
set day=%date:~3,2%
set year=%date:~6,4%
echo The current month is %month%
echo The current day is %day%
echo The current year is %year%
pause >nul

Another option is the for command, again here is my example:
@echo off
for /f "delims=/ tokens=1-3" %%a in ("%date%") do (
set month=%%a
set day=%%b
set year=%%c
)
echo The current month is %month%
echo The current day is %day%
echo The current year is %year%
pause >nul

A: Based on the great answers above, I would like to add this variation as a one-liner that simply assigns the year to the %year% environment variable:
for /f "skip=1 tokens=2 delims==" %%y in ('wmic PATH Win32_LocalTime GET Year /value') do set year=%%y

A: To set the variable Day in a batch script just use
FOR /F %%F IN ('date.exe +%%d') DO SET Day=%%F

where date.exe is in the GnuWin32 package coreutils.  Proceed analogously for month and year.  This solution does not depend on localization.  You can use UnxUtils instead of GnuWin32, as well as other alternatives.  No setup required.  Just copy date.exe where you need it.

A: powershell Set-Date -Da (Get-Date -Y 1980 -Mon 11 -Day 17)


text:
Q: creating a query using a data in a list format For this list:
mylist = ['a', 'b', 'c', 'd', 'm']

I need to create a query as follows:
(("a"[Journal]) OR ("b" [Journal]) OR ("c" [Journal]) OR ("d" [Journal]) OR ("m" [Journal])) AND ("2007/01/01"[Date] : "2017/12/31"[Date])

I tried to use "join" to print output but I could not create this query.
any suggestion?

A: You indeed need the join and a list comprehension:
pieces = ['("{}" [Journal])'.format(j) for j in mylist]
journal_list = " OR ".join(pieces)
query = "({}) {}".format(journal_list, more_stuff)

more_stuff is the "date" part of your query (say, 'AND ("2007/01/01"[Date] : "2017/12/31"[Date])'.
Another approach (less Pythonic) is to apply the format function to the list of journals:
pieces = map('("{}" [Journal])'.format, mylist)
journal_list = " OR ".join(pieces)
query = "({}) {}".format(journal_list, more_stuff)

The result, of course, is the same.


text:
Q: Moment.js not giving correct format for GMT date and time I am trying to convert local time into GMT time in 'YYYY-DD-MM HH:MM' format. I have tried:
moment.utc(new Date(),'YYYY-DD-MM HH:MM').format('YYYY-DD-MM HH:MM')

and also tried
 moment().utc().format('YYYY-DD-MM HH:MM')

but for PST time 2017-12-10 17:45 the output is coming 2017-13-10 00:10. The minutes are not coming properly. Not sure what am I doing wrong.

A: This is because M is short for month, and m is short for minute.  Read  the documentation more thoroughly.


text:
Q: Change Tracking autocleanup blocked I am encountering these errors every 30 minutes. Is there a permanent fix? I referred the link but wanted to make sure we have a trace flag 8293? The sql server version we are using is 2017 and its in cu25.
Sample error: Change Tracking autocleanup is blocked on side table of 'sampletablename'.If the failure persists, check if the table 'sampletablename' is blocked by any process .
Please suggest any possible fixes for the above issues. We cannot do manual cleanup due to business requirement.


text:
Q: why the data is not appearing in datagridview I have a form with 4 textboxes in VB.net for inserting Customer Info into a table. Now I want to show all data into DataGridView on the same form, the following code runs when clicking the "showall" button.
dtCustomer = retrieveFull("CustomerInfo")
    dgvCustomer.DataSource = dtCustomer

The retrieveFull function is as follows:
Public Function retrieveFull(ByVal tblName As String) As DataTable

    Try
        If dsSql.Tables.Contains(tblName) Then
            dsSql.Tables.Remove(tblName)
        End If

        cmdSql1.CommandText = "select * from " & tblName
        cmdSql1.Connection = Connect()
        daSql.SelectCommand = cmdSql1
        daSql.Fill(dsSql, tblName)

    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try

    Return dsSql.Tables(tblName)
End Function

My question is that when I press the "ShowAll" button so data is loaded into the DataGridView, all the cells are empty. When I click inside the cell then the text appears. Why it is like this? Why the data does not show directly? Kindly guide me.

A: I think there is no method called like databind() in vb, databind() available in c#.


text:
Q: Connect and disconnect USB devices programmatically I need to connect and disconnect USB devices, such as flash drives, in a programmatical manner, without unplugging and re-plugging the device.
Is there any way to do it in a C# Windows application?

A: You might want to look at some related questions:

*

*Safe remove USB-Drive using Win32 API?

*Windows - Power off an usb device in software
Both of the approaches mentioned in the answers are readily translatable to C#.


text:
Q: In what ways can I force a session to end? I want to force a session to end after 30 minutes regardless of activity. The first thing I thought of was this (untested):
function onApplicationStart() application.sessionLife = 30;

function onSessionStart() session.timeStarted = now();

function onRequestStart() {
    if ( dateDiff("n", session.timeStarted, now()) > application.sessionLife)
        structClear(session);
}

What other ways are available to force a session to end?
The obvious one is a session cookie that expires after 30 minutes. But I'm not sure if session cookies listen to the sessionTimeOut sessting or not.
Update
I just found out that StructClear() does not end the session. So I guess I should just expire the cookies.

A: As usual, Ben Nadel has already blogged the answer...
http://www.bennadel.com/blog/1847-Explicitly-Ending-A-ColdFusion-Session.htm
There are a few options, some quite safe, others use hidden methods that aren't guaranteed to be around in future version of ColdFusion or other CFML engines.  You might spot that I get a mention in his post since I love messing about with those hidden methods.  But if you want to do things properly (more future proof / engine switch proof), I'd suggest Ben's alternative methods.
Edit
Almost forgot, I created a function to stop the current session using another method (not mentioning in Ben Nadel's blog post).  It's still an undocumented feature, but is an improvement as it stops the session instantly, instead of setting it to 1 second to time out.
http://misterdai.wordpress.com/2010/06/15/cf-sessionstop-ending-a-cf-session/
Further Edit
Just explaining the different methods briefly, in case the linked sites ever disapppear.
To summarise the ways to stop a session in it's tracks...

*

*Set the sessionTimeout to a value of 1 second.

*

*Flag the targetted session (e.g. session.remove = true)

*Detect and set low timeout (application.cfc)
if (StructKeyExists(session, 'remove') And aession.remove) {
this.sessionTimeout = CreateTimeSpan(0, 0, 0, 1);
}

*Remove the association between the client and the sesssion by deleting the CFID / CFTOKEN cookies.

*Similar to above but using session.setMaxInactiveInterval(1)

*

*Undocumented, works but could change without notice between versions.

*More flexible, doesn't have to have code within the application.cfc file.

*Still have to remove cookies.

*Force ColdFusion to remove the session instantly.

*

*More use of undocumented features that could break between versions.

*Can be used anywhere, don't have to worry about cookies or single second timeouts.

Code for approach 3...
<cffunction name="sessionStop" output="false">
  <cfset var local = StructNew() />
  <cfif Not StructKeyExists(application, 'applicationName')>
    <cfthrow message="Application.applicationName is missing." />
  </cfif>
  <cftry>
    <cfset local.sid = session.cfid & '_' & session.cftoken />
    <cfset local.jTracker = CreateObject('java', 'coldfusion.runtime.SessionTracker') />
    <cfset local.jTracker.cleanUp(application.applicationName, local.sid) />
    <cfcatch type="any">
      <cfthrow message="Error stopping session, may not exist." />
    </cfcatch>
  </cftry>
</cffunction>

A: I don't think you want to use structClear(). If I remember correctly, there are issues if the CFID and CFTOKEN keys get deleted from the SESSION struct. Here is the code we use to end a session:
<!--- Delete the session --->
<cfloop collection="#session#" item="skey">
    <cfif NOT listFindNoCase("cfid,cftoken,sessionid,urltoken", skey)>
        <cfset structDelete(session, skey) />
    </cfif>
</cfloop>

<!--- Expire the CFID and CFTOKEN cookies to start a new session --->
<cfcookie name="cfid" expires="Now" />
<cfcookie name="cftoken" expires="Now" />

<!--- Expire the JSESSIONID cookie - only needed if J2EE sessions are used --->
<cfcookie name="jsessionid" expires="Now" />

So we delete all the keys from the SESSION except for CFID, CFTOKEN, SESSIONID, and URLTOKEN, then we expire the cookies that identify the session. When this happens CF should create new cookies and start a new session.


text:
Q: JS/jQuery for assigning values I am trying to achieve this:

*

*Currently value has been set on 2 radio buttons.

*Once one of the button is selected, the value(attribute) of that button should be assigned to the value of the div with an id.

I am not sure where I am going wrong. Below is the code snippet.

var init_font_one = $('input[id="init-one-name"]'),
  init_font_two = $('input[id="init-two-name"]'),
  init_id_value = $("#test");

if (init_font_one == 'checked') {
  init_id_value.val(init_font_one.val());
}

if (init_font_two == 'checked') {
  init_id_value.val(init_font_two.val());
}

<input type="text" id="test" value="abc"> Testing
<input id="init-one-name" type="radio" name="init-one-name" value="abcd">Test1
<input id="init-two-name" type="radio" name="init-one-name" value="xyz">Test2

A: There is few problems with your code:

*

*
 can't have value property.

*Your code executes on page load and not when some event was triggered.

*init_font_one == 'checked' compares jQuery object with string.

*input[id="init-one-name"] can be replaced with #init-one-name

*Your labels are not linked with inputs.

$('.radios').change(function() {
  $("#test").val($('.radios:checked').val());
});

  <input type="text" id="test" value="abc" /> Testing

<input class="radios" id="init-one-name" type="radio" name="init-one-name" value="abcd">Test1

<input class="radios" id="init-two-name" type="radio" name="init-one-name" value="xyz">Test2

A: You have to use on('change' to update the value of div when radio button is click. And use attr of jQuery to update the value of particular element.
Try this.

var init_font_one = $('input[id="init-one-name"]'),
    init_font_two = $('input[id="init-two-name"]'),
    init_id_value = $("#test");

init_font_one.change(function() {
  init_id_value.attr("value",init_font_one.val());
  console.log(init_id_value.attr("value"));
});

init_font_two.on('change',function() {
  init_id_value.attr("value",init_font_two.val());
  console.log(init_id_value.attr("value"));
});

 Testing

 <input id="init-one-name" type="radio" name="init-one-name" value="abcd">Test1

        <input id="init-two-name" type="radio" name="init-one-name" value="xyz">Test2

A: try this
$(document).ready(function(){
        $("input[type='button']").click(function(){
            var radioValue =
$("input[name='init-one-name']:checked").val();
            if(radioValue){
                alert("Your are a - " + radioValue);
            }
        });

    });

A: You should use jQuery change event to detect the change in the radio buttons and assign the value of checked radio button to the div with id="test"

var init_id_value = $("#test");

$('input[id="init-one-name"]').on('change', function() {
  init_id_value.text($(this).val());
});
$('input[id="init-two-name"]').on('change', function() {
  init_id_value.text($(this).val());
});

 Testing

 <input id="init-one-name" type="radio" name="init-one-name" value="abcd">Test1

        <input id="init-two-name" type="radio" name="init-one-name" value="xyz">Test2

A: I do not understand what you are trying to do, but try this:

$( "input[name='init-one-name']" ).change(function(){
  $('#test').val('New Value: ' + $(this).val());
});

    <textarea id="test">Testing
    </textarea>

     <input type="radio" name="init-one-name" value="abcd">Op 1
      <input type="radio" name="init-one-name" value="xyz">OP 2

A: There is no value on a div, but you can change the text content or you can assing a "virtual value" to the div using .data()
Check the snippet

$(function(){ // On jquery initialize
  var idtest = $('#test'); // the target Div
 $('input[type="radio"]').on('change',function(){ // change event for the two radio buttons

     /*** Method 1 : Using data attribute to assing a value ***/
     idtest.data('value',$(this).val()); // Value of the selected radio

     /*** Method 2 : Add the value of the selected radio to the text inside the div ***/
     idtest.text( $(this).val() ) // Value of the selected radio

     //retrieve the setted data value
     console.log( idtest.data('value') );
  });
});

 Testing

 <input id="init-one-name" type="radio" name="init-one-name" value="abcd">Test1

 <input id="init-two-name" type="radio" name="init-one-name" value="xyz">Test2

A: Refer to the fixed code below.
Added a listener to detect action performed over the radio buttons and changed method to check if radio is checked or not.

let ele = document.getElementById('init-one-div');
ele.addEventListener('click', function(e) {
  if ("INPUT" === e.target.nodeName)
    checkAndAssign();
});

function checkAndAssign() {
  var init_font_one = $('#init-one-name'),
    init_font_two = $('#init-two-name'),
    init_id_value = $("#test");

  if (init_font_one.is(':checked')) {
    init_id_value.val(init_font_one.val());
  }

  if (init_font_two.is(':checked')) {
    init_id_value.val(init_font_two.val());
  }

  //REMOVE below line if you want to remove the line printing the result
  init_id_value.html(' Testing [ ' + init_id_value.val() + ' ] ');
}

  Testing

  <input id="init-one-name" type="radio" name="init-one-name" value="abcd"> Test1

  <input id="init-two-name" type="radio" name="init-one-name" value="xyz"> Test2


text:
Q: I want to add take and skip inside relations using nestjs and typeorm Hi I would like to do something like this -
  where: {id : id},
  relations: {
      photos: true
  },
  photos: {
    take: 10,
    skip: 5
  }

I want to add take and skip inside relations. Do you have a suggestion?
Thank you.

A: maybe you can take a look at this code:
async findSomethings(ids, page, limit) {
   aRepository.find({
      where: {
          id: In(ids)
      },
      relations: ["photos"],
      take: limit,
      skip: (page - 1) * limit,
   })
}

for reference maybe you can see more detaiils in typeorm documentation https://typeorm.io/find-options, thank you


text:
Q: In-App payment in android I am developing an application that has some digital contents like image,audio etc is there. I need to implement the In-App payment in the application so that users can purchase the content and enjoy it. How do i implement it ?

A: Please look at the android documentation on In-app Billing.

A: You can start with the Android In-app Billing sample application and modify the code to make it work in your app:
http://developer.android.com/guide/market/billing/billing_integrate.html