Q:

Why does this expression simplify as such?

I'm reading through my professor's lecture notes on the multiple linear regression model and at one point he writes the following:
$$E[(b-\beta)e']=E[(X'X)^{-1}\epsilon\epsilon'M_{[X]}]. $$
In the above equation, $b$, $\beta$, $e$, and $\epsilon$ are all vectors, $X$ is a regressor matrix and $M$ is the residual maker matrix. In general, I have no idea why these expressions are equivalent, and I'm particularly confused at how the $e$ vector disappears and the $\epsilon$ vector appears.

A:

I am assuming $b$ is the OLS estimate of $\beta$ and $e$ is the corresponding estimate of $\epsilon$. Also I believe you have a typo above in your expression, as there should be $X'$ in front of $\epsilon \epsilon'$ and behind $(X'X)^{-1}$.
Start with the definition of $b$:
$$b=(X'X)^{-1}X'Y.$$
Replacing $Y$ with $X\beta+\epsilon$ in our expression above, we get
$$b=(X'X)^{-1}X'(X\beta+\epsilon)=\beta+(X'X)^{-1}X'\epsilon.$$
It follows that
$$b-\beta = (X'X)^{-1}X'\epsilon$$
Now turn to the defintion of $e$:
$$e=Y-\hat{Y}=Y-Xb=Y-X(X'X)^{-1}X'Y.$$
Notice $X(X'X)^{-1}X'$ is the projection matrix for $X$, which we will denote with $P_{[X]}$.
Replacing this in our expression for $e,$ we get
$$e=(I-P_{[X]})Y=M_{[X]}Y.$$
Replacing $Y$ in the expression above with $X\beta+\epsilon$, we get
$$e=M_{[X]}(X\beta+\epsilon)=M_{[X]}\epsilon,$$
since $M_{[X]}X$ is a matrix of zeros.
Post-multiplying $b-\beta$ with $e'$, we get
$$(b-\beta)e'=(X'X)^{-1}X'\epsilon \epsilon' M_{[X]},$$
since $e'=\epsilon'M_{[X]}.$

A:

Assuming that the coefficient estimator $b$ is calculated by OLS estimation, you have:
$$\begin{equation} \begin{aligned}
b-\beta
&= (X'X)^{-1} X'y - \beta \\[6pt]
&= (X'X)^{-1} X'(X \beta + \epsilon)- \beta \\[6pt]
&= (X'X)^{-1} (X'X) \beta + (X'X)^{-1} X' \epsilon - \beta \\[6pt]
&= \beta + (X'X)^{-1} X' \epsilon - \beta \\[6pt]
&= (X'X)^{-1} X' \epsilon. \\[6pt]
\end{aligned} \end{equation}$$
Presumably $e$ is the residual vector (different to the error vector $\epsilon$) so we have $e = M_{[X]} Y = M_{[X]} \epsilon$.  Substituting this vector gives:
$$\begin{equation} \begin{aligned}
(b-\beta) e'
&= (X'X)^{-1} X' \epsilon \ (M_{[X]} \epsilon)' \\[6pt]
&= (X'X)^{-1} X' \epsilon \epsilon' M_{[X]}' \\[6pt]
&= (X'X)^{-1} X' \epsilon \epsilon' M_{[X]}. \\[6pt]
\end{aligned} \end{equation}$$
(The last step follows from the fact that $M_{[X]}$ is a symmetric matrix.)  So the expression given by your professor is missing the $X'$ term.


Q:

Asp.Net Mvc Display exception in View from tempdata

I am handling error in Base controller. I need to display the error stored in tempdata, Exception type in a razor view.  How can I do that?
Base Controller code
protected override void OnException(ExceptionContext filterContext)
{
    // if (filterContext.ExceptionHandled)
    //   return;

    //Let the request know what went wrong
    filterContext.Controller.TempData["Exception"] = filterContext.Exception.Message;

    //redirect to error handler
    filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(
            new { controller = "Error", action = "Index" }));

    // Stop any other exception handlers from running
    filterContext.ExceptionHandled = true;

    // CLear out anything already in the response
    filterContext.HttpContext.Response.Clear();
}

Razor View Code

    This is the error Description
    @Html.Raw(Html.Encode(TempData["Exception"]))

A:

Try to make common exception attribute handling and register it as global filters. Like,
Common Exception Handling attribute :
    ///
    /// This action filter will handle the errors which has http response code 500.
    /// As Ajax is not handling this error.
    ///
    [AttributeUsage(AttributeTargets.Class)]
    public sealed class HandleErrorAttribute : FilterAttribute, IExceptionFilter
    {
        private Type exceptionType = typeof(Exception);

        private const string DefaultView = "Error";

        private const string DefaultAjaxView = "_Error";

        public Type ExceptionType
        {
            get
            {
                return this.exceptionType;
            }

            set
            {
                if (value == null)
                {
                    throw new ArgumentNullException("value");
                }

                this.exceptionType = value;
            }
        }

        public string View { get; set; }

        public string Master { get; set; }

        public void OnException(ExceptionContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }

            if (!filterContext.IsChildAction && (!filterContext.ExceptionHandled && filterContext.HttpContext.IsCustomErrorEnabled))
            {
                Exception innerException = filterContext.Exception;

                // adding the internal server error (500 status http code)
                if ((new HttpException(null, innerException).GetHttpCode() == 500) && this.ExceptionType.IsInstanceOfType(innerException))
                {
                    var controllerName = (string)filterContext.RouteData.Values["controller"];
                    var actionName = (string)filterContext.RouteData.Values["action"];
                    var model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);

                    // checking for Ajax request
                    if (filterContext.HttpContext.Request.IsAjaxRequest())
                    {
                        var result = new PartialViewResult
                        {
                            ViewName = string.IsNullOrEmpty(this.View) ? DefaultAjaxView : this.View,
                            ViewData = new ViewDataDictionary<HandleErrorInfo>(model),
                            TempData = filterContext.Controller.TempData
                        };
                        filterContext.Result = result;
                    }
                    else
                    {
                        var result = this.CreateActionResult(filterContext, model);
                        filterContext.Result = result;
                    }

                    filterContext.ExceptionHandled = true;
                }
            }
        }

        private ActionResult CreateActionResult(ExceptionContext filterContext, HandleErrorInfo model)
        {
            var result = new ViewResult
            {
                ViewName = string.IsNullOrEmpty(this.View) ? DefaultView : this.View,
                MasterName = this.Master,
                ViewData = new ViewDataDictionary<HandleErrorInfo>(model),
                TempData = filterContext.Controller.TempData,
            };

            result.TempData["Exception"] = filterContext.Exception;

            return result;
        }
    }

And Error/_Error view
@model HandleErrorInfo

    This is the error Description
    @TempData["Exception"]

A:

I agree that you should never expose an exception to your view but if you really need to, try using a custom attribute.
 public class CustomExceptionAttribute : System.Web.Mvc.HandleErrorAttribute
    {
        public override void OnException(System.Web.Mvc.ExceptionContext filterContext)
        {
            if (!filterContext.ExceptionHandled)
            {
                filterContext.Controller.TempData.Add("Exception", filterContext.Exception);
                filterContext.ExceptionHandled = true;
            }
        }
    }

    public class MyController : System.Web.Mvc.Controller
    {
        [CustomException]
        public ActionResult Test()
        {
            throw new InvalidOperationException();
        }
    }

If you override the OnException method in the base controller, then every action will get an  Exception object placed in temp data.  This maybe the desired behavior but with an attribute you can selectively enable this feature.


Q:

Need a solution for middleware caching in C#

I have an ASP.net application that uses some common business object that we have created. These business objects are also used in a few other windows services or console applications.
The problem I am running into is that if I have a class "foo" and a class "bar" and each has a function loadClient(), if I call foo.loadClient() and bar.loadClient(), each request will hit the database. I figure implementing some sort of cache would reduce unnecessary round trips to the DB.
Here's the catch. I want the cache to be specific to each HTTP request that comes in on the ASP.net App. That is, a new request gets a brand new cache. The cache can exist for the lifetime of the other console applications since 90% of them are utilities.
I know I can use System.Web.Cache but I don't want my middleware tied to the System.Web libraries.
Hope that explains it. Can anyone point me in the right direction?
Thanks!

A:

Are you reusing objects during the lifetime of a request? If not,then the model you have suggests that each postback will also create a new set of objects in effect obviating the need for a cache. Typically a cache has value when objects are shared across requests
As far as using a non web specific caching solution I've found the Microsoft Caching Application Block very robust and easy to use.


Q:

I cant use JTextField

I have a problem with JTextField. I will type in my form name, surname, phone_number and email. But I don't know how. Actually System.out.print prints 4 times null. Method .getText() return unknow source.
This is my code:
package View;

import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

import Date.DaneDoKontaktow;
import Date.KolekcjaKontaktow;
import Main.main;
import Model.OperacjeKontakty;

public class DodajKontakt extends JFrame implements ActionListener {

public JButton dodaj;
public JButton anuluj;
public JTextField s_imie;
public JTextField s_nazwisko;
public JTextField s_telefon;
public JTextField s_email;
private OperacjeKontakty operacje = new OperacjeKontakty();

public DodajKontakt(){
    super("Dodawanie kontaktu");
    setSize(300,300);
    setLocationRelativeTo(null);
    setLayout(null);
    setResizable(false);
    setVisible(true);

    dodaj = new JButton("Dodaj");
    dodaj.setBounds(50, 220, 100, 30);
    add(dodaj);

    anuluj = new JButton("Anuluj");
    anuluj.setBounds(165, 220, 100, 30);
    add(anuluj);

    DaneDoKontaktow dane = new DaneDoKontaktow();

    JLabel imie = new JLabel(dane.imie);
    imie.setBounds(15,30,70,15);
    add(imie);

    JLabel nazwisko = new JLabel(dane.nazwisko);
    nazwisko.setBounds(15,60,70,20);
    add(nazwisko);

    JLabel telefon = new JLabel(dane.telefon);
    telefon.setBounds(15,90,70,20);
    add(telefon);

    JLabel email = new JLabel(dane.email);
    email.setBounds(15,120,70,20);
    add(email);

    anuluj.addActionListener(this);
    anuluj.setActionCommand("klik_anuluj");

    JTextField s_imie = new JTextField();
    s_imie.setBounds(100,20,150,30);
    add(s_imie);

    JTextField s_nazwisko = new JTextField();
    s_nazwisko.setBounds(100,52,150,30);
    add(s_nazwisko);

    JTextField s_telefon = new JTextField();
    s_telefon.setBounds(100,85,150,30);
    add(s_telefon);

    JTextField s_email = new JTextField();
    s_email.setBounds(100,117,150,30);
    add(s_email);

    dodaj.addActionListener(this);
    dodaj.setActionCommand("dodaj");

}

public void actionPerformed(ActionEvent e) {

    if( e.getActionCommand().equals("klik_anuluj")){
        this.dispose();
    }
    if (e.getActionCommand().equals("dodaj")){
        System.out.print(s_imie);
        System.out.print(s_nazwisko);
        System.out.print(s_telefon);
        System.out.print(s_email);
        //operacje.dodaj(s_imie.getText(), s_nazwisko.getText(), s_email.getText(), s_telefon.getText());
        this.dispose();
    }
}
}

A:

you are overriding the visibility of your Attibutes
public JTextField s_imie;
public JTextField s_nazwisko;
public JTextField s_telefon;
public JTextField s_email;

Instead of :
JTextField s_imie = new JTextField();
s_imie.setBounds(100,20,150,30);
add(s_imie);

use this to initialize your declared variable instead of creating a new one:
s_imie = new JTextField();
s_imie.setBounds(100,20,150,30);
add(s_imie);

Afterwards use the following to print out the content:
System.out.print(s_imie.getText());

Do this for all your variables.


Q:

I receive: firebase.database is not a function error when trying to connect my form to the database

I'm trying to connect my contact form to a firebase database and i keep getting the firebase.database is not a function error continuously.
I'm also using parcel-bundler for this project and also getting these errors:
at Object.parcelRequire.firebase.js (firebase.js:44)
    at newRequire (firebase.js:44)
    at firebase.js:44
    at firebase.js:44

I really don't know what I'm doing wrong, after looking at similar problems none of them could provide a solution.
This is how I am linking my files:
<script src="https://www.gstatic.com/firebasejs/6.0.2/firebase-app.js"></script>
    <script src="./firebase.js"></script>
    <script src="./main.js"></script>
  </body>

This is the code from my firebase.js file:
// Your web app's Firebase configuration
var firebaseConfig = {
  apiKey: "AIzaS*************r48uEU",
  authDomain: "k********irebaseapp.com",
  databaseURL: "https://*******irebaseio.com",
  projectId: "k******",
  storageBucket: "k**********m",
  messagingSenderId: "984****903",
  appId: "1:9843179**********3734705af"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);

var messageRef = firebase.database().ref("messages");

//grab a form
document.querySelector(".contact-form").addEventListener("submit", submitForm);

function submitForm(e) {
  e.preventDefault();

  // get values
  var name = getInputVal("name");
  var email = getInputVal("email");
  var number = getInputVal("phone");
  var message = getInputVal("message");

  saveMessage(name, email, number, message);
}

function getInputVal(id) {
  return document.getElementById(id).value;
}

function saveMessage(name, email, number, message) {
  var newMessageRef = messageRef.push();

  newMessageRef.set({
    name: name,
    email: email,
    number: number,
    message: message
  });
}

Any help will be deeply appreciated, thanks guys.

A:

You're currently only including this for Firebase:
<script src="https://www.gstatic.com/firebasejs/6.0.2/firebase-app.js"></script>

This only contains the definition of FirebaseApp, and doesn't include Firebase Authentication (firebase.auth()) or Firebase Realtime Database (firebase.database()). To include those, be sure to include the correct scripts for that too:
<script src="https://www.gstatic.com/firebasejs/6.0.2/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/6.0.2/firebase-database.js"></script>


Q:

SharePoint REST API Document Library - filter by folder name

I'm running a JavaScript script that updates permissions on folders in lists and document libraries.  To do this I need to get the ID of the item I want to update.  The folders all have unique names so I want to filter by the folder name.  For list items this is relatively easy:
siteUrl + "/api/Web/Lists/getByTitle(' + listName + ')/items?$filter=Title eq '" + folderName + "'";

However for document libraries I am having trouble.  The name of the folder isn't stored in the title field.  I can't find the right way to filter the document library so that the only items it returns are the items I need to update.  I have tried the following (neither work):
siteUrl + "/api/Web/Lists/getByTitle(' + listName + ')/items?$filter=Folder/Name eq '" + folderName + "'";

siteUrl + "/api/Web/Lists/getByTitle(' + listName + ')/items?$filter=BaseName eq '" + folderName + "'";

Does anyone know whether it is possible to filter based on the name of a folder?
My backup is to request all items and then loop over the items to find the right one.

A:

The name of the folder is stored in the Name field i.e FileLeafRef field value.
Also, to optimize the request, you should specify only the fields that you want using the $select param.
So, you can filter based on the value stored in it and create your REST endpoint as :
siteUrl + "/api/Web/Lists/getByTitle(' + listName + ')/items?
$select=ID&$filter=FileLeafRef eq '" + folderName + "'";


Q:

Best method of getting Javascript data from a simple 3-row CSV

I have a simple CSV (imported using JQuery's $.ajax from the /data/league.csv on the same site) with three lines in this exact format:
"Kimberlin Library","Queen's Building","Innovation Centre","etc etc"
8,2,0,-2
1,0,-1,0

which I'd like to get into this format (to use building and percent as data for the x-y axes in Highcharts, and also to populate a list with all three):
var leaguetable = {
    building: ["Kimberlin Library","Queen's Building","Innovation Centre","etc etc"],
    percent: [8,2,0,-2],
    change: [1,0,-1,0]
};

embarrassingly trivial, but I keep drawing a blank, despite trying other people's methods (including split(/\r\n|\n|r/), searching for /^(.*)$/m), and this question), so prepared to start from scratch. I need something as simple as possible, either JQuery or pure Javascript. For a similar problem I ended up converting the file to JSON, but I'd like to avoid that if possible.

A:

Try this. It will handle simple CSV, and single- or double-quoted CSV, all via the regex pattern in the code below. You'll have to adjust the end of processCSV() to do what you want, since I'm just returning the object into thin air.
$(document).ready(function() {
    $.ajax({
        type: "GET",
        url: "my_csv.txt",
        dataType: "text",
        success: function(data) {processCSV(data);}
     });
 });

function processCSV(allLines) {
    var allLinesArray = allLines.split(/\r\n|\n/);
    var leaguetable = { 'building': [], 'percent': [], 'change': [] };
    var pattern = /([^,'"]*"[^"]*"[^,'"]*)|([^,'"]*'[^']*'[^,'"]*)|([^,"']*)/ig;
    var fieldValues;

    for (var i=0; i<allLinesArray.length; i++) {
        fieldValues = allLinesArray[i].match(pattern);
        if (fieldValues) {
            for (var j=0; j<fieldValues.length; j++) {
                // if begins with single- or double-quote, strip specified quotes
                if (fieldValues[j].charAt(0) === '"' || fieldValues[j].charAt(0) === "'") {
                    fieldValues[j] = fieldValues[j].replace(fieldValues[j].substr(0,1), "");
                }
            }
            // I'll trust your CSV to have the right number of fields, but...
            // you may want to build some validation in before doing the next 3 lines
            leaguetable.building.push(fieldValues[1]);
            leaguetable.percent.push(fieldValues[2]);
            leaguetable.change.push(fieldValues[3]);
        }
    }
    return leaguetable;
}


Q:

clicking on everything except

I want to create an effect like in facebook when you have opened a menu with options, help and logout. It works this way.
wherever you click on the page except of that menu, it closes.
I have tried this
$("body").not("#myMenu").click(function() {
   // hide menu
});

but this fails, because it hides hides menu when I am clicking it. What can be the problem and how to solve it?
May be there are other ideas how to handle that?

A:

I think this post should help you out:
How do I detect a click outside an element?
The key is stopPropagation().


Q:

php if && || OR statement returning nothing ... but does separately

I'm truly puzzled and need someone to shed some light on this matter for me please.
When I use those 2 statements separately they get results:
$ads->where('country_to', '=', $_COOKIE['country_from'])

$ads->where('country_from', '=', $_COOKIE['country_from']);

... but once I tried to use the OR statement then I get no results, just wondering why?
$ads->where('country_to', '=', $_COOKIE['country_from']) || $ads->where('country_from', '=', $_COOKIE['country_from']);

I also tried this way, no results either:
$ads->where('country_to', '=', $_COOKIE['country_from'] || 'country_from', '=', $_COOKIE['country_from']);

Can someone tell me what I'm doing wrong here? Thanks all ;-)

A:

It seems like you are using Codeignitor,if yes then use orWhere()
$ads->where('country_to', '=', $_COOKIE['country_from']);

$ads->orwhere('country_from', '=', $_COOKIE['country_from']);// or try or_where

Or
$select = "country_to = '".$_COOKIE['country_from']."' OR country_from = '".$_COOKIE['country_from']."'";

$ads->where($select);

Or
$country_from = $_COOKIE['country_from'];

$select = "country_to = $country_from OR country_from = $country_from";

$ads->where($select);


Q:

In PHP would this be deemed correct?

I already wrote a post about an issue I had before about this but I had that issue taken care of. Like my last post I have a form, text-box and a button. I have everything done with this including Printing the original word, Printing the number of characters in the word, Printing the word in all caps and Printing the word in reverse order. My only issue I'm having is trying to get whatever text I enter and then click the button to output to Print the first letter of the word and Print the last letter of the word. I've been doing a lot of looking around of PHP.net and I found that substr is used to return a part of a string that I could use. The only issue is when I write the code for it and try to execute my program it errors out on that specific line. I'm not looking for the answer but could someone just take a look and see what I'm doing wrong because I understand everything completely but this is the only thing I'm hung up on.
$first = substr($_POST['entertext']);
echo "The first letter of the word is " . $first. "
\n";

$last = substr($_POST['entertext']);
echo "The first letter of the word is " . $last. "
\n";

A:

Try this:
$first = substr($_POST['entertext'], 0, 1);
echo "The first letter of the word is " . $first. "
\n";

$last = substr($_POST['entertext'], sizeof($_POST['entertext'])-2, 1);
echo "The first letter of the word is " . $last. "
\n";


Q:

Space in like in MySQL search AWS python

Trying to query AWS database (newbie to this). Query is as below:
dfHealthData = pd.read_sql("SELECT YearStart, LocationDesc, Topic, Question, DataValue "
                               "FROM HealthData WHERE YearStart = '2018' AND DataValueType = 'Crude Prevalence' AND Question LIKE '%18 years'" , connection_string)

Want to get string which ends in ' 18 years' (or ideally '>=18 years', but the former will do).
Error is as below.
Error retrieving from AWS: unsupported format character ' ' (0x20) at index 161

A:

% has a special meaning in python. Try to escape it:
dfHealthData = pd.read_sql("SELECT YearStart, LocationDesc, Topic, Question, DataValue FROM HealthData WHERE YearStart = '2018' AND DataValueType = 'Crude Prevalence' AND Question LIKE '%%18 years'" , connection_string)


Q:

Algorithm to check availability with two time frames

What would be the best algorithm to check the availability of a device for rental with two time frames?
I have the timeframe of the device and the existing rental (start & end date) and the timeframe of the "new" rental.
Example:
New rental: 18 April 2013 - 25 April 2013

In this cases I'd like to return false:
a) Existing rental: 20 April 2013 - 24 April 2013
b) Existing rental: 16 April 2013 - 24 April 2013
c) Existing rental: 20 April 2013 - 28 April 2013
d) Existing rental: 16 April 2013 - 28 April 2013

There could be even more cases but I think it's clear what I want.

A:

I think what you need is a good Data Structure or some logics. Hope the logic below can filter out all overlapping time frames.
 var overlappingIntervals = intervals
                    .Where(r =>
                        (r.Start <= toCheck.Start && r.End >= toCheck.End) //inside a timeframe
                    || (r.Start >= toCheck.Start && r.End <= toCheck.End) //other is inside our timeframe
                    || (r.Start >= toCheck.Start && r.End >= toCheck.End && r.Start <=toCheck.End) //end overlap
                    || (r.Start <= toCheck.Start && r.End <= toCheck.End && r.End >= toCheck.Start)// start overlap

                    ).ToList();

I have also placed commnets to detect conditions.
class Program
    {
        static void Main(string[] args)
        {
            List<DateInterval> intervals = new List<DateInterval>();
            intervals.Add(new DateInterval(Convert.ToDateTime("26 April 2013"), Convert.ToDateTime("27 April 2013")));
            intervals.Add(new DateInterval(Convert.ToDateTime("16 April 2013"), Convert.ToDateTime("24 April 2013")));
            intervals.Add(new DateInterval(Convert.ToDateTime("20 April 2013"), Convert.ToDateTime("28 April 2013")));
            intervals.Add(new DateInterval(Convert.ToDateTime("16 April 2013"), Convert.ToDateTime("28 April 2013")));

            DateInterval toCheck = new DateInterval(Convert.ToDateTime("16 April 2013"),
                                                    Convert.ToDateTime("25 April 2013"));

            var overlappingIntervals = intervals
                .Where(r =>
                    (r.Start <= toCheck.Start && r.End >= toCheck.End) //inside a timeframe
                || (r.Start >= toCheck.Start && r.End <= toCheck.End) //other is inside our timeframe
                || (r.Start >= toCheck.Start && r.End >= toCheck.End && r.Start <=toCheck.End) //end overlap
                || (r.Start <= toCheck.Start && r.End <= toCheck.End && r.End >= toCheck.Start)// start overlap

                ).ToList();
            Console.Write(overlappingIntervals.Count);

        }
    }

    public class DateInterval
    {

        public DateInterval(DateTime Start, DateTime End)
        {
            this.Start = Start;
            this.End = End;
        }
        public DateTime Start { get; set; }
        public DateTime End { get; set; }
    }


Q:

Tag merge request: [webstart] and [java-web-start]

There are two Java Web Start tags:
webstart: x 239
java-web-start: x 320

Both tags refer to the same technology
webstart's wiki refers to java-web-start's wiki
both wiki point to this page
all questions tagged with webstart clearly relate to Java Web Start

I suggest they be merged into java-web-start (which appears in the auto-complete list if one types "webstart" in the Tags box when asking a new question).

A:

I deleted the suggested jnlp ← java-web-start synonym. At minimum, if the two really are that related, that synonym should be reversed.
I also added the requested java-web-start ← webstart synonym and approved the suggested javaws synonym. Should be all good to go now.


Q:

Python - Disable nested for loop according to boolean value

What is the best way to rewrite nested for-loops like this:
for i in my_generator_function(args...):
    #do stuff...

    for j in another_generator_function(args...):
        #do more stuff

if i want to disable the first for-loop, according to a boolan value, but always keep the inner one? Of course I could use an if/else around it, and put a duplicate of the inner loop in the else block. but is there a better way?

A:

If I understood correctly you want to loop 100 or 0 times through something and keep the inner 10.
If that is what you want, try this:
my_value = False

checker = lambda x, y: y if x else range(1)

def somefunc():
    return range(100)

for i in checker(my_value, somefunc()):
    if my_value:
        #do stuff
    for j in range(10):
        #do stuff


Q:

How to have EMRFS consistent view on S3 buckets with retention policy?

I am using an AWS EMR compute cluster (version 5.27.0) , which uses S3 for data persistence.
This cluster both reads and writes to S3.
S3 has an issue of eventual consistency, because of which after writing data, it cannot be immediately listed. Due to this I use EMRFS with DynamoDB to store newly written paths for immediate listing.
Problem now is that I have to set a retention policy on S3, because of which data more than a month old will get deleted from S3. However, in doing so , the data does not get deleted from EMRFS DynamoDB table, leading to consistency issues.
My question is , how can I ensure that on setting the retention policy in S3, the same paths get deleted from the DynamoDB table?
One naive solution I have come up with is to define a Lambda, which fires periodically, and sets TTL of say 1 day on the DynamoDB records manually. Is there a better approach than this ?

A:

You can configure DynamoDB with same expiration policy as your S3 objects have
https://aws.amazon.com/blogs/aws/new-manage-dynamodb-items-using-time-to-live-ttl/
and in this case, you ensure both DynamoDB and S3 have the same existing objects


Q:

Loading speed vs memory: how to efficiently load large arrays from h5 file

I have been facing the following issue: I have to loop over num_objects = 897 objects, for every single one of which I have to use num_files = 2120 h5 files. The files are very large, each being 1.48 GB and the content of interest to me is 3 arrays of floats of size 256 x 256 x 256 contained in every file (v1,v2 and v3). This is to say, the loop looks like:
for i in range(num_objects):
    ...
    for j in range(num_files):
       some operation with the three 256 x 256 x 256 arrays in each file

and my current way of loading them is by doing the following in the innermost loop:
f = h5py.File('output_'+str(q)+'.h5','r')
key1 = np.array(f['key1'])
v1=key1[:,:,:,0]
v2=key2[:,:,:,1]
v3=key3[:,:,:,2]

The above option of loading the files every time for every object is obviously very slow. On the other hand, loading all files at once and importing them in a dictionary results in excessive use of memory and my job gets killed. Some diagnostics:

The above way takes 0.48 seconds per file, per object, resulting in a total of 10.5 days (!) spent only on this operation.
I tried exporting key1 to npz files, but it was actually slower by 0.7 seconds per file.
I exported v1,v2 and v3 individually for every file to npz files (i.e. 3 npz files for each h5 file), but that saved me only 1.5 day in total.

Does anyone have some other idea/suggestion I could try to be fast and at the same time not limited by excessive memory usage?

A:

If I understand, you have 2120 .h5 files. Do you only read the 3 arrays in dataset f['key1'] for each file? (or are there other datasets?) If you only/always read f['key1'], that's a bottleneck you can't program around. Using a SSD will help (because I/O is faster than HDD). Otherwise, you will have to reorganize your data. The amount of RAM on your system will determine the number of arrays you can read simultaneously. How much RAM do you have?
You might gain a little speed with a small code change. v1=key1[:,:,:,0] returns v1 as an array (same for v2 and v3).  There's no need to read dataset f['key1'] into an array. Doing that doubles your memory footprint. (BTW, Is there a reason to convert your arrays to a dictionary?)
The process below only creates 3 arrays by slicing v1,v2,v3 from the h5py f['key1']object. It will reduce your memory footprint for each loop by 50%.
f = h5py.File('output_'+str(q)+'.h5','r')
key1 = f['key1']
## key1 is returned as a h5py dataset OBJECT, not an array
v1=key1[:,:,:,0]
v2=key2[:,:,:,1]
v3=key3[:,:,:,2]

On the HDF5 side, since you always slice out the last axis, your chunk parameters might improve I/O. However, if you want to change the chunk shape, you will have to recreate the .h5 files. So, that will probably not save time (at least in the short-term).


Q:

Undefined method error with Rails has_one association (Rails 5)

I am attempting to access the methods of an associated model in the view, but getting an undefined method error

undefined method `cpt_code' for Procedure:0x007fe7b55518e8

.  Thanks for your help!
index view:
<% @actuals.each do |actual| %>
  <% if actual.procedures.present? %>
    <% actual.procedures.each do |procedure| %>

       <%= procedure.cpt_code.id %>
       <%= procedure.description %>

    <% end %>
  <% end %>
<% end %>

Controller:
  def index
    @actuals = Actual.all
  end

Models:
class Actual < ApplicationRecord
  has_many :actual_procedures, :dependent => :destroy
  has_many :procedures, through: :actual_procedures

class ActualProcedure < ApplicationRecord
  belongs_to :procedure
  belongs_to :actual
end

class Procedure < ApplicationRecord
  has_many :actual_procedures
  has_many :actuals, through: :actual_procedures
end

class CptCode < ApplicationRecord
  has_one :procedure

Procedures in schema:
  create_table "procedures", force: :cascade do |t|
    t.bigint "cpt_code_id"
    t.string "code"
    t.string "description"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["cpt_code_id"], name: "index_procedures_on_cpt_code_id"
  end

A:

undefined method `cpt_code' for Procedure:0x007fe7b55518e8

You don't have cpt_code in procedures table. Perhaps you meant cpt_code_id.
Update:
Actual reason is you didn't defined association for cpt_code in Procedure model
class Procedure < ApplicationRecord
  has_many :actual_procedures
  has_many :actuals, through: :actual_procedures
  belongs_to :cpt_code # you should have this
end


Q:

Slide transition between html files using JQuery and AJAX to navigate

I'd like to know if there's an easy way to implement the slide transition effect between many separate html files in my website.  I've been searching for hours but I can't find an example for what I'm trying to do without having redesign the website.  I'm using JQuery and AJAX to validate the selections on the pages and then move to the selected ones after some server side validation.  Is this possible with my current design? Thanks
//JavaScript function
function getValue(aval) {

    $.ajax({
        url: 'Services.aspx/getSelection',
        type: "POST",
        dataType: "json",
        data: '{"aSelection":"' + aval + '"}',
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            //alert(data.d);
            if (data.d == 1) {
                window.location.href = "InsuredReason.html";
            }
            if (data.d == 2) {
                window.location.href = "AgentInfo.html";
            }
            if (data.d == 3) {
                window.location.href = "ContratistaInfo.html";
            }
            if (data.d == 4) {
                window.location.href = "VisitorInfo.html";
            }
        },
        error: function (er) {
            //alert(er.d);
        }
    });

  }

A:

You don't need to redirect, better update some area of the page with content of html files.
HTML could be:

And javascript would not redirect, but update the content:
function getValue(aval) {
    if (aval == 1) {
        filename = "InsuredReason.html";
    }
    if (aval == 2) {
        filename  = "AgentInfo.html";
    }
    if (aval == 3) {
        filename  = "ContratistaInfo.html";
    }
    if (aval == 4) {
        filename  = "VisitorInfo.html";
    }
    $.ajax({
        url: 'Services.aspx/'+filename,
        type: "GET",
        success: function (data) {
            //alert(data);
            $('#content').html(data);//where data is content of html file
        },
        error: function (er) {
            //alert(er.d);
        }
   });

}


Q:

Getting an ArrayIndexOutOfBoundsException

I have this code :
public class OddSum1 {
   public OddSum1() {
   }
   public static void main(String[] args) {

   int OddLimit = Integer.parseInt(args[0]);
   int sum = 0;

   for (int i = 1; i <= OddLimit; i += 2) {
     sum += i;
   }

   System.out.println("The sum of odd numbers from 1 to " + OddLimit + " is " + sum);

   }
}

Whenever I run it I get this error:
java.lang.ArrayIndexOutOfBoundsException: 0
    at OddSum1.main(OddSum1.java:7)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)

It's supposed to prompt user for a number and then sums the odd number from 1 to the number entered, I'm guessing it's a problem with this int OddLimit = Integer.parseInt(args[0]);
but I just don't know how to fix it, any help would be awesome.

A:

It's supposed to prompt user for a

You need to pass arguments to main, Command line argument and then change index to 0
for example:
$java YourMainClass 5

A:

You can take either of the two approaches from below :
Approach 1 : You can specify the oddLimit by passing it as an argument to the main method as :
Code :
public class OddSum1 {
public OddSum1() {
}
public static void main(String[] args) {
int OddLimit = Integer.parseInt(args[0]);
int sum = 0;
for (int i = 1; i <= OddLimit; i += 2)
sum += i;
System.out.println("The sum of odd numbers from 1 to " + OddLimit + " is " + sum);
}
}

To compile and run the code :
javac OddSum1.java
java OddSum1 20
Approach 2 : Read the OddLimit interactively from the prompt
Code:
public class OddSum1 {
public OddSum1() {
}
public static void main(String[] args) {

int OddLimit = Integer.parseInt(System.console().readLine());
int sum = 0;

for (int i = 1; i <= OddLimit; i += 2)
sum += i;

System.out.println("The sum of odd numbers from 1 to " + OddLimit + " is " + sum);

}
}


Q:

Activity jumps out when open (Android). Any error on code?

Activity closed itself when open. What's the error here? I'm still not very familiar with Android. Someone please help me out, thanks.
public class EditProfileActivity extends AppCompatActivity {

    EditText nameET = (EditText) findViewById(R.id.txtCPName);
    String name = nameET.getText().toString();

    EditText ICET = (EditText) findViewById(R.id.txtCPIC);
    String IC = ICET.getText().toString();

    RadioGroup genderRG = (RadioGroup) findViewById(R.id.rgpCPGender);
    Integer genderID = genderRG.getCheckedRadioButtonId();
    RadioButton genderRB = (RadioButton) findViewById(genderID);
    String gender = (String)genderRB.getText();

    EditText emailET = (EditText) findViewById(R.id.txtCPEmail);
    String email = emailET.getText().toString();

    EditText addressET = (EditText) findViewById(R.id.txtCPAddress);
    String address = addressET.getText().toString();

    EditText contactET = (EditText) findViewById(R.id.txtCPContact);
    String contact = contactET.getText().toString();

    EditText oldPassET = (EditText) findViewById(R.id.txtCPOldPass);
    String oldPass = oldPassET.getText().toString();

    EditText newPassET = (EditText) findViewById(R.id.txtCPNewPass);
    String newPass = newPassET.getText().toString();

    EditText confirmPassET = (EditText) findViewById(R.id.txtCPRetypeNewPass);
    String confirmPass = confirmPassET.getText().toString();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_profile);
        setTitle("Edit Profile");
    }

    public void SaveChanges(View view){
        if(name.matches("")) {
            AlertDialog alertDialog = new AlertDialog.Builder(EditProfileActivity.this).create();
            alertDialog.setTitle("Error");
            alertDialog.setMessage("Please make sure all information are keyed in correctly.");
            alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
            alertDialog.show();
        } else {
            AlertDialog alertDialog = new AlertDialog.Builder(EditProfileActivity.this).create();
            alertDialog.setTitle("Success");
            alertDialog.setMessage("Profile has been successfully updated.");
            alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            Intent intent = new Intent(EditProfileActivity.this, MainActivity.class);
                            startActivity(intent);
                        }
                    });
            alertDialog.show();
        }
    }

    public void ChangePassword(View view){

        if(newPass.matches(confirmPass)) {
            AlertDialog alertDialog = new AlertDialog.Builder(EditProfileActivity.this).create();
            alertDialog.setTitle("Success");
            alertDialog.setMessage("Your password has been changed successfully.");
            alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            Intent intent = new Intent(EditProfileActivity.this, MainActivity.class);
                            startActivity(intent);
                        }
                    });
            alertDialog.show();
        } else if (oldPass.matches("") || newPass.matches("") || confirmPass.matches("")) {
            AlertDialog alertDialog = new AlertDialog.Builder(EditProfileActivity.this).create();
            alertDialog.setTitle("Error");
            alertDialog.setMessage("Please key in all the password fields");
            alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
            alertDialog.show();
        }
    }
}

A:

Your problem is you cannot initialize variable outside of onCreate(),and you cannot write findViewById() outside of onCreate or any other parent Method in android,we have write the all initialization statements inside the onCreate() method,
so you can declare the the global variables outside of onCreate() and initialiize them to onCreate().
Try This.
    EditText nameET, ICET, emailET, addressET, contactET, oldPassET, newPassET, confirmPassET;
    RadioGroup genderRG, genderRB;
    String name, IC, gender, email, address, contact, oldPass, newPass, confirmPass;
    Integer genderID,

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_profile);
        setTitle("Edit Profile");

        nameET = (EditText) findViewById(R.id.txtCPName);
        name = nameET.getText().toString();

        ICET = (EditText) findViewById(R.id.txtCPIC);
        ICET.getText().toString();

        genderRG = (RadioGroup) findViewById(R.id.rgpCPGender);
        genderID = genderRG.getCheckedRadioButtonId();
        genderRB = (RadioButton) findViewById(genderID);
        gender = (String) genderRB.getText();

        emailET = (EditText) findViewById(R.id.txtCPEmail);
        email = emailET.getText().toString();

        addressET = (EditText) findViewById(R.id.txtCPAddress);
        address = addressET.getText().toString();

        contactET = (EditText) findViewById(R.id.txtCPContact);
        contact = contactET.getText().toString();

        oldPassET = (EditText) findViewById(R.id.txtCPOldPass);
        oldPass = oldPassET.getText().toString();

        newPassET = (EditText) findViewById(R.id.txtCPNewPass);
        newPass = newPassET.getText().toString();

        confirmPassET = (EditText) findViewById(R.id.txtCPRetypeNewPass);
        confirmPass = confirmPassET.getText().toString();

    }


Q:

Using Chrome with `--headless` switch to measure user page load times

I'm trying to improve the performances of my web server and would like to get an accurate measure on how long it takes the user to load the page. The way I imagined this would be to simulate concurrent requests from users and track how page load times change as I fine-tune various settings to get optimal results.
I'd like to use the latest snapshot of Chromium with the --headless switch to measure how long it would take the user to load the page, but since this is a relatively new feature and I'm not familar with all the possible switches, I'd appreciate if someone can share what they would run to get accurate results.
The only limitation I have is that I can't inject scripts or modify the response content in some other way that would be helpful for such a test.

A:

This seems to be ok-ish. Taking a screenshot shows the page seems to be loaded and getting similar results between the first and subsequent requests, so I'm assuming caching is indeed disabled.
time chromium \
  --headless \
  --disk-cache-dir=/dev/null \
  --disable-gpu \
  --download-whole-document \
  --deterministic-fetch \
  https://www.stackoverflow.com

Notes

this doesn't warm up the DNS entries on the initial request, so it'd probably be best to discard the first result
the --disable-gpu flag isn't necessary, but there is a reported error with the current build
opening up a remote debugging port could probably be useful to remove references to 3rd party sources that skew results or to have more control over what's considered a fully loaded page, say wait for some scripts to fetch additional resources, but it's a bit way over my head


Q:

how to rewrite media folders using htaccess

I'm trying to redirect
/media/subfolder/filename to index
the subfolders are named like 12345 or 54321 and i'd like NOT to redirect subfolders that does not have this name structure.
how could i do this?

A:

So something like this?
RedirectMatch ^/media/[0-9]+/.+ /index.html

Assuming by "index" you mean "/index.html"


Q:

Format the LaTeX code of an array

Is there any editor that can nicely format the LaTeX code for an array? By nicely format I mostly have in mind aligning the &, as in the examples below:

Example 1:
\begin{array}{lcl}
z & = & a \\
& = & a \\
f(x,y,z) & = & x + y + z
\end{array}

could be formatted to:
\begin{array}{lcl}
z        & = & a         \\
         & = & a         \\
f(x,y,z) & = & x + y + z
\end{array}

Example 2:
\begin{bmatrix*}[r]
  {1}&{ 2}  &{ \mathbf M}  \\
  {48941} & {-3} &  { \mathbf M}  \\
  {11} & { 6}  & {-\mathbf M}
\end{bmatrix*}

could be formatted to:
\begin{bmatrix*}[r]
  {1} & { 2}  & { \mathbf M}  \\
  {1} & {-3}  & { \mathbf M}  \\
  {1} & { 6}  & {-\mathbf M}
\end{bmatrix*}

A:

Independent of the editor being used, we have latexindent by Chris (cmhughes). This should do a good job in beautifying the latex code by indenting everything.
On the other hand there is a Align Columns option in texstudio (which a cousin of texmaker) where you select
1 &  2  &  \mathbf M  \\
1 & -3  &  \mathbf M  \\
1 &  6  & -\mathbf M

and then click the tab to align them.

Aside there is no need to enclose the entries within braces since the entries are already inside a group here.


Q:

Restar días a fecha datetime (SQL y PHP)

Quiero que me muestre una serie de solicitudes de la base de datos y el usuario tiene que introducir de hace cuántos días quiere el informe (X días).
El problema que tengo es que me resta bien las fechas, pero si no coinciden las horas no saca resultados. Me gustaría que descarte las horas y solo se quede con la fecha, pero no sé cómo modificar lo que ya tengo...
private static function exportaInforme($numDias = null)
{
    $db = JFactory::getDBO();
    $query = $db->getQuery(true);
    $query->select(array('s.*'));
    $query->from('solicitudes AS s');
    $query->where("(s.estado='6' AND s.fecha = DATE_SUB(CURDATE(), INTERVAL '".$numDias."' DAY))");
    $db->setQuery((string) $query);
    $result = $db->loadObjectList();

    return $result;
}

¿Cómo resto X días a una fecha de la base de datos y que solo tenga en cuenta la fecha pero no las horas?

A:

El Problema es que estas comparando una fecha con marca de tiempo y otra sin marca de tiempo para poder realizar tu cunsulta correctamente debes eliminar la marca de tiempo de ambas fechas, ya que DATE_SUB(CURDATE() es '2017-10-19' s.fecha debe tener el mismo formato.
private static function exportaInforme($numDias = null)
{
    $db = JFactory::getDBO();
    $query = $db->getQuery(true);
    $query->select(array('s.*'));
    $query->from('solicitudes AS s');
    $query->where("(s.estado='6' AND DATE(s.fecha) = DATE_SUB(CURDATE(), INTERVAL '".$numDias."' DAY))");
    $db->setQuery((string) $query);
    $result = $db->loadObjectList();

    return $result;
}

También puedes usar la funcion DATEDIFF() que solo compara las dos fecha y devuelve el resultado en días.
private static function exportaInforme($numDias = null)
{
    $db = JFactory::getDBO();
    $query = $db->getQuery(true);
    $query->select(array('s.*'));
    $query->from('solicitudes AS s');
    $query->where("(s.estado='6' AND DATEDIFF(s.fecha ,CURDATE()) = 1)");
    $db->setQuery((string) $query);
    $result = $db->loadObjectList();

    return $result;
}


Q:

How to scan tokens only within context using Flex?

I want to create a parser of template engine using Flex & Bison. The thing is that I would like to parse only expressions within {{..}} and ${..}.
The template can be any arbitrary text with embedded tokens with code like this:
        </table:table-row>
        {{$(/report/row.xml).embed()}}
        {{$(//Accreditation/AccreditationDocument/Report).each(fragment(row) """
            <table:row>
                <table:table-cell office:value-type="string" office:string-value="${row["name"]}" />
            </table:row>
        """)}}
        <table:table-row table:number-rows-repeated="1048574" table:style-name="ro1">
            <table:table-cell table:number-columns-repeated="16384"/>
        </table:table-row>
    </table:table>

A:

I have found the solution myself. Flex has a feature called Start Conditions.
Below is the lexer.l code which returns tokens only from {{ }}. Other text is returned as GENERAL_BODY.
%{
#include "bisondef.h"
%}

%option reentrant noyywrap never-interactive nounistd
%option bison-bridge

WS [ \t\n]+
ID [A-z_][[:alnum:]]*

%x stmt

%%
    int stmt_level = 0;

"{{"    { stmt_level = 0; BEGIN(stmt); }

<stmt>{
    "{{"    { stmt_level++; printf("stmt {{\n"); }
    "}}"    {
        if (0 == stmt_level) BEGIN(INITIAL);
        else stmt_level--;
    }
    {WS}    {}
    [0-9]+  { yylval->num = atoi(yytext); return NUM; }
    "+"|"-"|"*"|"/"|"("|")" { return *yytext; }
    ";"     { return SEMICOLON; }
    {ID}    { yylval->str = strdup(yytext); return ID; }
}

.  {
    yylval->str = strdup(yytext);
    return GENERAL_BODY;
}

%%

int yyerror(const char *msg) { fprintf(stderr,"Error: %s\n",msg); return 0; }


Q:

Anyone tried to brush mud/snow in rear-wheel while on ride?

I ride my bike in the snow. And I think my bike can be a lot cleaner if I had a snow catcher in my rear-wheel.
There is possibility because the rear wheel fork comes with extra holes in it. I think we can hook a fork there to hold a brush at the back of the tire.
I think it will keep the gear and derailleur cleaner. I guess it will also reduce the skidding.

A:

I prefer not using anything in the snow to block the snow. You risk the snow packing in the snow blocker (e.g. fenders) and freezing, which can be dangerous. A brush against the tire (depending on the stiffness of the bristles) could also damage your tire.
If you want to use something, a seatpost fender and a downtube mudguard are probalby the safest options.
If you want to keep your bike clean in winter, good luck (especially if you ride on salted roads). The best course of action is to bring it in when you have time (e.g. 24 hours), clean the bike indoors, let it be completely dry then take it back out. Or, if theres a warm day, do a quick (light) wipe down and dry the bike off as you go. You could also try a stiff brush which may get rid of some of the salt.  Or just deal with a dirty bike, and clean it in the spring.

A:

I thought I've seen something like this before... so I googled a bit and found traces of this design, apparently deceased.

While it looks clever, I have some doubts that it will work efficiently for any real rain. As soon as the brush is "saturated" with water, incoming drops will cause some of already collected water to detach and continue its way up.
It will definitely not work for snow, the reason being the snow is hard not liquid. I had my rear wheel fully blocked many times when a build-up of snow formed in the chainstay-seattube-bottom bracket area of my bikes. Even a rear fender placed too low once caused such snow accumulation resulting in inability to rotate the rear wheel. Placing another hinder somewhere can only shift the position of such build-up or even provoke it.
Maybe some oil on tires might help to repel snow sticking to the tire, but obviously the same oil will hurt your braking capabilities to the extent that it will be safer to leave the bike home. However, you may try to use some bike  polish on the frame and on the drivetrain parts. It is told to help with preventing mud sticking to the frame; however, I used it and did not notice any measurable effects.
Solutions that I consider to work are:

having another bicycle with a different braking system, preferably internal (say, drum) or even disk will work better;
wider clearance between tires and the frame — if you can move your rear wheel in the dropouts further back;
gnarlier tires, possibly spiked if you need to deal with plenty of ice; if not, just go with regular non-completely slick tires.
just dealing with the fact that riding in the winter has to be done more carefully and slowly;
just dealing with the fact that you will not be able to pass on your bike to your descendants; or maybe you actually will — bikes are survival tools and may last surprisingly long.


Q:

django-nvd3 does not show any graph

I'm still newbie to python 3.4 and django 1.7. I tried to draw a chart using django-nvd3. I tried to run something like:
class Report(TemplateView):
    def report_page(request):
        extra_serie = {}
        xdata = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
        ydata = [3, 5, 7, 8, 3, 5, 3, 5, 7, 6, 3, 1]
        chartdata = {
            'x': xdata,
            'name1': 'series 1', 'y1': ydata, 'extra1': extra_serie,
        }
        charttype = "lineChart"
        chartcontainer = 'linechart_container' # container name
        data = {
            'charttype': charttype,
            'chartdata': chartdata,
            'chartcontainer': chartcontainer,
            'extra': {
                'x_is_date': False,
                'x_axis_format': '',
                'tag_script_js': True,
                'jquery_on_ready': False,
            }
        }
        return render_to_response('Report.html', data)

where Report.html is as follows:

     {% load nvd3_tags %}

        {% include_container chartcontainer 400 600 %}

but no chart does appear. I read somewhere from areski that: "We use include the Javascript and CSS code for D3/NVD3." So I added these statements to my template:
<link href="{% static "nvd3-master/build/nv.d3.css" %}" rel="stylesheet" type="text/css" media="screen" />

but still no chart is drawn on my web page!
Here is the output HTML:

    <link href="/static/nvd3-master/build/nv.d3.css" rel="stylesheet" type="text/css" media="screen" />

    </script>

<svg style="width:600px;height:400px;"></svg>

A:

Thanks a lot from Areski Belaid (@areski) that helped me to find the issue. I changed:

to:
    {% load_chart charttype chartdata chartcontainer extra %}

And now it works. :))


Q:

$F(f)\subset F(x)$ is an algebraic extension of degree $\max(p,q)$ if $f$ is non constant quotient polynomial

Let $F$ be a field, with $f=a/b\in F(x)$ the quotient of coprime polynomials $a,b\in F[x]$ of degree $p$ and $q$ respectively.

How do I prove that if $f$ is not constant, then $F(f)\subset F(x)$ is an algebraic extension of degree $\max(p,q)$?

I honestly have no idea how to approach this problem, maybe someone can give me a push in the right direction?

A:

Let $f(x) = t$. Then you can think of your extension as $F(t) \subset F(t)[x]/(a(x)-tb(x))$. I can elaborate more but you should try finishing the proof from here on.


Q:

Referencing a cell in Excel using values from other cells

I would like to know if it is possible to reference a cell in Excel depending on the value of another cell.
Example

I have a cell, let's say A1 where I have the row number that I want to use (e.g., the content of A1 is 42)
I want to compute the sum of column B from row 1 to the row corresponding to the number given in A1. Something like =SUM( B1:B<NUMBER_IN_A1> )

Is there any way?

A:

Use & to create the cell coordinates, access them using INDIRECT().
=SUM(INDIRECT("B1:B" & A1))

A:

INDEX is normally preferable to INDIRECT, where possible. You don't have to "hardcode" the column, and it's not (as) volatile.
=SUM(B1:INDEX(B:B,A1))

See the documentation for more details on usage.


Q:

How do I see which LLVM library have to link with to resolve PassManagerBuilder::addGlobalExtension()?

How do I see which LLVM library have to link with to resolve PassManagerBuilder::addGlobalExtension()?
I've already included llvm_map_components_to_libnames(llvm_libs support core irreader) in the CMakeLists.txt.
However, I still get a link error for the symbol above.
In general, how to I look up which libraries I need to include to resolve certain symbols?

A:

The method PassManagerBuilder::addGlobalExtension() declared and defined in
include/llvm/Transforms/IPO/PassManagerBuilder.h and lib/Transforms/IPO/PassManagerBuilder.cpp respectively. Live it in library libLLVMipo.a, hence you need add to llvm_map_components_to_libnames the string ipo:
llvm_map_components_to_libnames(llvm_libs ipo ...)


Q:

Java IFSFile on Iseries testing over PC

I'm trying to develop a Java Class that will be used on a RPG program on iSeries. This Class will manage files with IFSFile. The problem is that I don't know how can I test this (if possible) on my PC.
My code would be something like:
import java.io.BufferedReader;
import java.io.IOException;

import com.ibm.as400.access.AS400;
import com.ibm.as400.access.AS400SecurityException;
import com.ibm.as400.access.IFSFile;
import com.ibm.as400.access.IFSFileReader;
(...)

        AS400 system = new AS400("AS400SystemName");
        IFSFile file = new IFSFile(system, "/File1");
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new IFSFileReader(file));
        } catch (AS400SecurityException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // Read one line of the file
        String line1 = null;
        try {
            line1 = reader.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // Print line
        System.out.println(line1);

        // Close reader
        try {
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }</pre>

I don't know well iSeries and I have some doubts:

If I try to run this code on my PC it asks me to a user/password, when the class will be used on iSeries, it will ask also, or it will take the user that is running the application?
Is there any way in which I can test this part on my PC, in order to know if it will work on production? My idea is first use a mock for Unit testing, but later I would like to have some functional tests that don't use the mock, maybe some kind of emulator or similar...

Thanks in advance.

A:

In answer to question 1, the user id and password issue, be sure to use the JT400Native.jar instead of JT400.jar in your classpath on the iSeries side.  When using JT400Native.jar, it should take the user id and password of the currently running job when using the com.ibm.as400.access classes.
In answer to question 2, you cannot test your program without an iSeries to talk to. Optionally, you can read from a normal file input stream or write to a normal file output stream instead of the IFSFile. This will, at least, let you test the business logic of your code.  But when it's time to test the com.ibm.as400.access classes, you just can't do it without access to a real iSeries.  An emulator would be nice, but the architecture is just so different, I don't know of anyone who made one.


Q:

Custom Glide ModelLoader for base64 images

I have images from some SOAP API that are encoded in base64. To load them directly with Glide I decided to wrote custom ModelLoader.
Glide Version: 4.3.1
Glide load line:
GlideApp.with(activity)
        .load(Data().apply { code = licensePlateData.licensePlateImgId })
        .into(view.imageLicense)

GlideModule:
@GlideModule
class MyAppGlideModule : AppGlideModule() {

    override fun registerComponents(context: Context, glide: Glide, registry: Registry) {
        super.registerComponents(context, glide, registry)
        val app = context.applicationContext as MyApplication
        registry.append(Data::class.java, ByteArray::class.java, MyImageLoaderFactory(app.api))
    }
}

Loader:
class MyImageLoaderFactory(private val api: Api) : ModelLoaderFactory<Data, ByteArray> {

    override fun teardown() {

    }

    override fun build(multiFactory: MultiModelLoaderFactory): ModelLoader<Data, ByteArray> {
        return MyImageLoader(api)
    }
}

class MyImageLoader(private val api: Api) : ModelLoader<Data, ByteArray> {

    override fun buildLoadData(model: Data, width: Int, height: Int, options: Options): ModelLoader.LoadData<ByteArray> {
        val key = "code:${model.code};width:$width;height:$height"
        return ModelLoader.LoadData<ByteArray>(ObjectKey(key), MyImageDataFetcher(api, GetImageRequest().apply { data = model }))
    }

    override fun handles(model: Data): Boolean {
        return true
    }
}

class MyImageDataFetcher(private val api: Api, private val request: GetImageRequest) : DataFetcher<ByteArray> {

    private val disposables = CompositeDisposable()

    override fun cleanup() {
        disposables.clear()
    }

    override fun loadData(priority: Priority, callback: DataFetcher.DataCallback<in ByteArray>) {
        api.getImage(request) //soap request
                .map { it.image.decodeBase64() } //translate String to ByteArray
                .subscribe({ callback.onDataReady(it) }, {
                    if (it is Exception) {
                        callback.onLoadFailed(it)
                    } else {
                        callback.onLoadFailed(MyException(it))
                    }
                })
                .addTo(disposables)
    }

    override fun cancel() {
        disposables.clear()
    }

    override fun getDataClass(): Class<ByteArray> {
        return ByteArray::class.java
    }

    override fun getDataSource(): DataSource {
        return DataSource.REMOTE
    }

}

Stack trace / LogCat:
com.bumptech.glide.Registry$NoSourceEncoderAvailableException: Failed to find source encoder for data class: class [B
    at com.bumptech.glide.Registry.getSourceEncoder(Registry.java:534)
    at com.bumptech.glide.load.engine.DecodeHelper.getSourceEncoder(DecodeHelper.java:232)
    at com.bumptech.glide.load.engine.SourceGenerator.cacheData(SourceGenerator.java:74)
    at com.bumptech.glide.load.engine.SourceGenerator.startNext(SourceGenerator.java:45)
    at com.bumptech.glide.load.engine.DecodeJob.runGenerators(DecodeJob.java:298)
    at com.bumptech.glide.load.engine.DecodeJob.runWrapped(DecodeJob.java:268)
    at com.bumptech.glide.load.engine.DecodeJob.run(DecodeJob.java:229)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
    at java.lang.Thread.run(Thread.java:764)
    at com.bumptech.glide.load.engine.executor.GlideExecutor$DefaultThreadFactory$1.run(GlideExecutor.java:413)

I think that I'm missing something to make it work.

A:

Thanks to comment from https://github.com/bumptech/glide/issues/2677 I found the solution.
@GlideModule
class MyAppGlideModule : AppGlideModule() {

    override fun registerComponents(context: Context, glide: Glide, registry: Registry) {
        super.registerComponents(context, glide, registry)
        val app = context.applicationContext as MyApplication
        registry.append(Data::class.java, ByteBuffer::class.java, MyImageLoaderFactory(app.api))
    }
}

class MyImageLoaderFactory(private val api: Api) : ModelLoaderFactory<Data, ByteBuffer> {

    override fun teardown() {

    }

    override fun build(multiFactory: MultiModelLoaderFactory): ModelLoader<Data, ByteBuffer> {
        return MyImageLoader(api)
    }
}

class MyImageLoader(private val api: Api) : ModelLoader<Data, ByteBuffer> {

    override fun buildLoadData(model: Data, width: Int, height: Int, options: Options): ModelLoader.LoadData<ByteBuffer> {
        val key = "code:${model.code};width:$width;height:$height"
        return ModelLoader.LoadData<ByteBuffer>(ObjectKey(key), MyImageDataFetcher(api, GetImageRequest().apply { data = model }))
    }

    override fun handles(model: Data): Boolean {
        return true
    }
}

class ClmImageDataFetcher(private val api: Api, private val request: GetImageRequest) : DataFetcher<ByteBuffer> {

    private val disposables = CompositeDisposable()

    override fun cleanup() {
        disposables.clear()
    }

    override fun loadData(priority: Priority, callback: DataFetcher.DataCallback<in ByteBuffer>) {
        api.getImage(request)
                .map { it.image.decodeBase64() }
                .subscribe({ callback.onDataReady(ByteBuffer.wrap(it)) }, {
                    if (it is Exception) {
                        callback.onLoadFailed(it)
                    } else {
                        callback.onLoadFailed(MyException(it))
                    }
                })
                .addTo(disposables)
    }

    override fun cancel() {
        disposables.clear()
    }

    override fun getDataClass(): Class<ByteBuffer> {
        return ByteBuffer::class.java
    }

    override fun getDataSource(): DataSource {
        return DataSource.REMOTE
    }

}


Q:

How can I make log4j reopen log files periodically (logrotate)

My sysadmin has been "encouraging" me to fix our web application logs to play nicely with logrotate.  The problem is that after logrotate works on a file the application stops logging.  Is there a way to configure log4j to reopen log files after this happens?
This comment explains the general problem but doesn't provide a solution for log4j: https://stackoverflow.com/a/6514233/201748

A:

I have still to test it, but the copytruncate option of logrotate should do.


Q:

Too many query rows: 50001 in process builder?

I am getting a Limitexception from the processbuilder, when updating a single Opportunity. The only thing which happens in my Process is that the Owner and one field is being updated by values of the Account.
I have no idea where this error comes from, the result in the E-Mail just says "records, which met the criteria, could not be updated".
Does anyone have an idea what I could do to resolve this?

A:

I think you should look further than the update of 1 opportunity. Potentially the update of your oppy triggers an update on other (related) records.
Check if you find any workflows/triggers that could execute when updating your oppy.


Q:

Do I need to download Play Framework for each project?

The following link mentions that I need to download examples or templates to download play (basically I cannot download latest Play framework)
https://www.playframework.com/download#alternatives
I tried the example and notice that sbt in downloading loads of components including play sdk. Do I have to do this everytime I need to create a Play project?

A:

no, you don't need to download if don't want. theoretically if you create a simple sbt project by hand and add play as a dependency sbt will download every required libs and dependencies. and, if you upgrade your application to a newer play version, it will automatically download newer dependencies. sbt is a build tool, manages everything.
using templates is a plus, to speed up new project creation (and, if you new in play framework, templates and examples can help you to shorten the learning curve)


Q:

Is there GUI Scala Console that I can download and run from command line?

Groovy has a nice GUI Console in which I can enter any java/groovy code and run.
This is distributed with groovy.
As for as I know Scala does not have anything like that except for REPL.
Is there any third party Scala GUI Console that I can download and install and run from command line and not from a JNLP file using webstart?
One use case:
Suppose I have Scala program:
val lineWidth = 2.5
val axisWidth = 1.5
val white = ConstVec3(1)
val background = white
val axisColor = ConstVec3(0)

drawFunction("Plot") { (dims, pixel) =>
  val mid = dims/2.0
  val p = pixel - mid

  val color: Vec3 = background

  color *= {
    val shade = clamp(abs(p.x)/axisWidth, 0, 1)
    mix(axisColor, background, shade)
  }
  color *= {
    val shade = clamp(abs(p.y)/axisWidth, 0, 1)
    mix(axisColor, background, shade)
  }

  color *= {
    val scale = 2/mid.x

    val x = p.x*scale
    val y = p.y*scale

    val f = smoothstep(-1, 1, x)
    val shade = clamp(abs(f - y)/(scale*lineWidth), 0, 1)
    mix(Vec3(1, 0, 0), Vec3(1), shade)
  }

  color
}

In Groovy Console (which is a full blown GUI) I can easily copy and paste above program. I can easily modify the program in GUI and quickly hit the run button and quickly see the result. I can even easily copy and paste the results and post it somewhere else. I can easily copy lines of Scala code from somewhere else and copy into GUI Console and hit the run button and I can also copy certain jars into a location that is in the classpath of Groovy Console and so on and on long list of lot more features.
Can you do that in REPL or is there another tool you can use?

A:

For the kind of exploratory coding that you're talking about, you should check out Kojo.  Just ignore the parts designed for teaching children how to program (e.g. drag the border between the turtle window and the rest until it's as small as it can get), and you find that you have a full-fledged GUI with syntax highlighting and everything that lets you run code with a press of a button (or two presses of the keyboard).  Or maybe you want to use the turtle to do the drawing, given the example you gave.
You might also be interested in ScalaConsole or Scalide.


Q:

Kubernetes - Container image already present on machine

So I have 2 similar deployments on k8s that pulls the same image from GitLab. Apparently this resulted in my second deployment to go on a CrashLoopBackOff error and I can't seem to connect to the port to check on the /healthz of my pod. Logging the pod shows that the pod received an interrupt signal while describing the pod shows the following message.
 FirstSeen  LastSeen    Count   From            SubObjectPath                   Type        Reason          Message
  --------- --------    -----   ----            -------------                   --------    ------          -------
  29m       29m     1   default-scheduler                           Normal      Scheduled       Successfully assigned java-kafka-rest-kafka-data-2-development-5c6f7f597-5t2mr to 172.18.14.110
  29m       29m     1   kubelet, 172.18.14.110                          Normal      SuccessfulMountVolume   MountVolume.SetUp succeeded for volume "default-token-m4m55"
  29m       29m     1   kubelet, 172.18.14.110  spec.containers{consul}             Normal      Pulled          Container image "..../consul-image:0.0.10" already present on machine
  29m       29m     1   kubelet, 172.18.14.110  spec.containers{consul}             Normal      Created         Created container
  29m       29m     1   kubelet, 172.18.14.110  spec.containers{consul}             Normal      Started         Started container
  28m       28m     1   kubelet, 172.18.14.110  spec.containers{java-kafka-rest-development}    Normal      Killing         Killing container with id docker://java-kafka-rest-development:Container failed liveness probe.. Container will be killed and recreated.
  29m       28m     2   kubelet, 172.18.14.110  spec.containers{java-kafka-rest-development}    Normal      Created         Created container
  29m       28m     2   kubelet, 172.18.14.110  spec.containers{java-kafka-rest-development}    Normal      Started         Started container
  29m       27m     10  kubelet, 172.18.14.110  spec.containers{java-kafka-rest-development}    Warning     Unhealthy       Readiness probe failed: Get http://10.5.59.35:7533/healthz: dial tcp 10.5.59.35:7533: getsockopt: connection refused
  28m       24m     13  kubelet, 172.18.14.110  spec.containers{java-kafka-rest-development}    Warning     Unhealthy       Liveness probe failed: Get http://10.5.59.35:7533/healthz: dial tcp 10.5.59.35:7533: getsockopt: connection refused
  29m       19m     8   kubelet, 172.18.14.110  spec.containers{java-kafka-rest-development}    Normal      Pulled          Container image "r..../java-kafka-rest:0.3.2-dev" already present on machine
  24m       4m      73  kubelet, 172.18.14.110  spec.containers{java-kafka-rest-development}    Warning     BackOff         Back-off restarting failed container

I have tried to redeploy the deployments under different images and it seems to work just fine. However I don't think this will be efficient as the images are the same throughout. How do I go on about this?
Here's what my deployment file looks like:
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: "java-kafka-rest-kafka-data-2-development"
  labels:
    repository: "java-kafka-rest"
    project: "java-kafka-rest"
    service: "java-kafka-rest-kafka-data-2"
    env: "development"
spec:
  replicas: 1
  selector:
    matchLabels:
      repository: "java-kafka-rest"
      project: "java-kafka-rest"
      service: "java-kafka-rest-kafka-data-2"
      env: "development"
  template:
    metadata:
      labels:
        repository: "java-kafka-rest"
        project: "java-kafka-rest"
        service: "java-kafka-rest-kafka-data-2"
        env: "development"
        release: "0.3.2-dev"
    spec:
      imagePullSecrets:
      - name: ...
      containers:
      - name: java-kafka-rest-development
        image: registry...../java-kafka-rest:0.3.2-dev
        env:
        - name: DEPLOYMENT_COMMIT_HASH
          value: "0.3.2-dev"
        - name: DEPLOYMENT_PORT
          value: "7533"
        livenessProbe:
          httpGet:
            path: /healthz
            port: 7533
          initialDelaySeconds: 30
          timeoutSeconds: 1
        readinessProbe:
          httpGet:
            path: /healthz
            port: 7533
          timeoutSeconds: 1
        ports:
        - containerPort: 7533
        resources:
          requests:
            cpu: 0.5
            memory: 6Gi
          limits:
            cpu: 3
            memory: 10Gi
        command:
          - /envconsul
          - -consul=127.0.0.1:8500
          - -sanitize
          - -upcase
          - -prefix=java-kafka-rest/
          - -prefix=java-kafka-rest/kafka-data-2
          - java
          - -jar
          - /build/libs/java-kafka-rest-0.3.2-dev.jar
        securityContext:
          readOnlyRootFilesystem: true
      - name: consul
        image: registry.../consul-image:0.0.10
        env:
        - name: SERVICE_NAME
          value: java-kafka-rest-kafka-data-2
        - name: SERVICE_ENVIRONMENT
          value: development
        - name: SERVICE_PORT
          value: "7533"
        - name: CONSUL1
          valueFrom:
            configMapKeyRef:
              name: consul-config-...
              key: node1
        - name: CONSUL2
          valueFrom:
            configMapKeyRef:
              name: consul-config-...
              key: node2
        - name: CONSUL3
          valueFrom:
            configMapKeyRef:
              name: consul-config-...
              key: node3
        - name: CONSUL_ENCRYPT
          valueFrom:
            configMapKeyRef:
              name: consul-config-...
              key: encrypt
        ports:
        - containerPort: 8300
        - containerPort: 8301
        - containerPort: 8302
        - containerPort: 8400
        - containerPort: 8500
        - containerPort: 8600
        command: [ entrypoint, agent, -config-dir=/config, -join=$(CONSUL1), -join=$(CONSUL2), -join=$(CONSUL3), -encrypt=$(CONSUL_ENCRYPT) ]
      terminationGracePeriodSeconds: 30
      nodeSelector:
        env: ...

A:

To those having this problem, I've discovered the problem and solution to my question. Apparently the problem lies with my service.yml where my targetPort was aimed to a port different than the one I opened in my docker image. Make sure the port that's opened in the docker image connects to the right port.
Hope this helps.


Q:

Tensorflow: reading the entire contents of a file exactly once into a single tensor

I'm working with about ~300MB of word embedding data (currently an .npz but I'm willing to do the work to translate into any format) and I'd like to know if there is a way to get that data into tensorflow that doesn't involve initializing it in python (i.e. initializing a tf.Variable from a numpy array).
My reason for wanting to avoid this is that doing so causes tensorflow to dump my embeddings along with the graph definition when writing summaries. See https://github.com/tensorflow/tensorflow/issues/1444.
For my training data, I use the normal tensorflow reader pipeline (TFRecordReader, filename queues, tf.train.shuffle_batch). That's very good at reading fixed sized batches of examples for a predefined number of epochs. What I have no idea how to do is read the entire contents of a file into a single tensor.  I could solve this pretty easily by just reading a single batch that is the full size of my embeddings, but I'd like a more general solution that doesn't rely on knowing the number of records, just the individual record format.

A:

The easiest way to achieve this would be to create a tf.Variable of the appropriate type and shape by initializing it from a tf.placeholder(), then use the feed mechanism to pass in the value. As a result, the actual value will never appear in the graph itself.
Let's say your embedding matrix is 1000 x 100:
embedding_init = tf.placeholder(tf.float32, shape=[1000, 100])
embedding = tf.Variable(embedding_init)

You can then initialize the variable with the value from your .npz file:
datafile = numpy.load("data.npz")
embedding_value = datafile["embedding"]

sess = tf.Session()
sess.run(tf.initialize_all_variables(),
         feed_dict={embedding_init: embedding_value})

datafile.close()


Q:

Laravel 5 get relation data

I've made application with Laravel 5.5 and I use MySQL  database. I have 2 tables
people: id, name, homeplanet_id
planets: id, name
And foreign key people.homeplanet_id references planets id
I also have 2 models: Person and Planet, and PersonController.
I can get Person's data in controller by using
Person::find($id)->getAttributes()

but it is like
[
    id => 1
    name => Name
    homeplanet_id => 1
]

How can I get data look like next
[
    id => 1
    name => Name
    homeplanet_id => Planet_name
]

A:

Use with() method,
Something like
$person = Person::where(array())->with('planet')->get(); //You can fetch all related data by passing multiple values for method with()
To print
{{$person->planet->name}} //where planet indicated the relation on person model as follows

Where planet indicated the relation on Person model.
In our case
Getting data
$person = Person::where(array('id'=>$id))->with('planet')->get();
And in Person model do something like following to fetch planet using with() method:
Person extends model{
   public function panet(){
      //your relation one to one, one to many etc.....whatever
   }
}

Try exploring eager loading in Laravel (eloquent)  and scoped query too.
Visit the link for Eager loading and everything will be done by the ORM itself.Link


Q:

How do I get the current keyboard (current IME) being used via ADB

Currently, I know how to set the keyboard to use using the command adb shell ime set [keyboard IME]. But the question is how do I get the current keyboard being used?
I'm planning to use it using the madb C# library which fortunately has a ExecuteRemoteCommand method which allows me to execute shell commands (sort of like adb shell).

A:

adb shell settings get secure default_input_method


Q:

setLatestEventInfo cannot be resolved

I am trying to do a notification on api level 10 and below is my code but im getting a syntax error setLatestEventInfo cannot be resolved. I am guessing its something to do with the API level
 public static void sendNotification(Context caller, Class<?> activityToLaunch, String title, String msg, int numberOfEvents, boolean sound, boolean flashLed, boolean vibrate, int iconID) {
    NotificationManager notifier = (NotificationManager) caller.getSystemService(Context.NOTIFICATION_SERVICE);

    final Notification notify = new Notification(iconID, "", System.currentTimeMillis());

    notify.icon = iconID;
    notify.tickerText = title;
    notify.when = System.currentTimeMillis();
    notify.number = numberOfEvents;
    notify.flags |= Notification.FLAG_AUTO_CANCEL;
    if (sound) notify.defaults |= Notification.DEFAULT_SOUND;

    if (flashLed) {
        // add lights
        notify.flags |= Notification.FLAG_SHOW_LIGHTS;
        notify.ledARGB = Color.BLUE;
        notify.ledOnMS = 500;
        notify.ledOffMS = 500;
    }

    if (vibrate) {
        notify.vibrate = new long[]{100, 200, 300};
    }

    Intent toLaunch = new Intent(caller, activityToLaunch);
    toLaunch.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
    toLaunch.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    PendingIntent intentBack = PendingIntent.getActivity(caller, notify.number, toLaunch, 0);
    notify.setLatestEventInfo(caller, title, msg, intentBack);
    notifier.notify(notify.number, notify);
    notify.number = notify.number + 1;
}

A:

If your compile SDK version is set to api 23+ you'll see this issue. This method was removed in M (api 23).
To do notifications for api 4 onwards you can use the NotificationCompat.Builder which was added in the Android Support Library. The Android Documentation has a decent example:
 Notification noti = new Notification.Builder(mContext)
         .setContentTitle("New mail from " + sender.toString())
         .setContentText(subject)
         .setSmallIcon(R.drawable.new_mail)
         .setLargeIcon(aBitmap)
         .build();

You can replace "Notification.Builder" for "NotificationCompat" if need to support older api versions.


Q:

JQuery Filer post files on submit

Trying to use jquery.filer to upload images to my controller in asp.net mvc. Everything works as expected if I simply use the HTML file input type but once I enable the plugin it stops populating HttpPostedFileBase property.
After reading the documentation I couldn't find anyway of simply attaching the files to the input and uploading them on submit.
CONTROLLER
[HttpPost]
    public ActionResult Create(IEnumerable<HttpPostedFileBase> files, ListingModel model)
    {
        return View(model);
    }

JS
    $("#filer_input").filer({
    limit: 6,
    maxSize: 5,
    extensions: null,
    changeInput: '

Drag&Drop files here
 or
Browse Files

',
    showThumbs: true,
    theme: "dragdropbox",
    templates: {
        box: '

',
        item: '
\

\

\

\

\

\
                                    {{fi-name | limitTo: 25}}\
                                    {{fi-size2}}\

\
                                {{fi-image}}\

\

\

\

{{fi-progressBar}}
\

\

\

\

\

\

\

\

',
        itemAppend: '
\

\

\

\

\

\
                                        {{fi-name | limitTo: 25}}\
                                        {{fi-size2}}\

\
                                    {{fi-image}}\

\

\

\

{{fi-icon}}
\

\

\

\

\

\

\

\

',
        progressBar: '

',
        itemAppendToEnd: true,
        removeConfirmation: true,
        _selectors: {
            list: '.jFiler-items-list',
            item: '.jFiler-item',
            progressBar: '.bar',
            remove: '.jFiler-item-trash-action'
        }
    },
    dragDrop: {
        dragEnter: null,
        dragLeave: null,
        drop: null
    },
    //uploadFile: {
    //    url: "./php/upload.php",
    //    data: null,
    //    type: 'POST',
    //    enctype: 'multipart/form-data',
    //    beforeSend: function(){},
    //    success: function(data, el){
    //        var parent = el.find(".jFiler-jProgressBar").parent();
    //        el.find(".jFiler-jProgressBar").fadeOut("slow", function(){
    //            $("
 Success
").hide().appendTo(parent).fadeIn("slow");
    //        });
    //    },
    //    error: function(el){
    //        var parent = el.find(".jFiler-jProgressBar").parent();
    //        el.find(".jFiler-jProgressBar").fadeOut("slow", function(){
    //            $("
 Error
").hide().appendTo(parent).fadeIn("slow");
    //        });
    //    },
    //    statusCode: null,
    //    onProgress: null,
    //    onComplete: null
    //},
    addMore: false,
    clipBoardPaste: true,
    excludeName: null,
    beforeRender: null,
    afterRender: null,
    beforeShow: null,
    beforeSelect: null,
    onSelect: null,
    afterShow: null,
    //onRemove: function(itemEl, file, id, listEl, boxEl, newInputEl, inputEl){
    //    var file = file.name;
    //    $.post('./php/remove_file.php', {file: file});
    //},
    onEmpty: null,
    options: null,
    captions: {
        button: "Choose Files",
        feedback: "Choose files To Upload",
        feedback2: "files were chosen",
        drop: "Drop file here to Upload",
        removeConfirmation: "Are you sure you want to remove this file?",
        errors: {
            filesLimit: "Only {{fi-limit}} files are allowed to be uploaded.",
            filesType: "Only Images are allowed to be uploaded.",
            filesSize: "{{fi-name}} is too large! Please upload file up to {{fi-maxSize}} MB.",
            filesSizeAll: "Files you've choosed are too large! Please upload files up to {{fi-maxSize}} MB."
        }
    }
});

HTML

                            <input type="file" name="files" id="filer_input2" multiple="multiple">

A:

It will not work if you are using drag&drop and uploadFile feature. If you want to get the files from <input type="file"> you will need to disable this 2 options in your jQuery.filer


Q:

Changing Android Device Admin Settings

If you go into your android device to Settings-> Security, under the Device Administration section there are some settings for Verify Apps.
While working on AOSP, I am trying to get some testing software to work. So part of that requires I enable and disable this feature. I already have code to disable some other features, they look like this:
    //Allow mock locations
    Settings.Secure.putInt(getContentResolver(),
            Settings.Secure.ALLOW_MOCK_LOCATION,
            1);

    //Stay on while plugged in
    Settings.Global.putInt(getContentResolver(),
            Settings.Global.STAY_ON_WHILE_PLUGGED_IN,
            BatteryManager.BATTERY_PLUGGED_USB);

Note* I am running as root so I can change these settings. So to clarify, my question is how to change the settings Verify Apps, where is that located?

A:

You're looking for Settings.Global.PACKAGE_VERIFIER_ENABLE. It doesn't seem to be up on the documentation site, but you can see it in the source.
Definition:

android.provider.Settings.java

Example usage by the default settings app:

com.android.settings.SecuritySettings.java


Q:

Amazon RDS Aurora vs RDS MySQL vs MySQL on EC2?

I've been looking around for best practices when setting up your database on the cloud but it still isn't clear to me which of the following solutions should we be going for?

Amazon RDS Aurora
Amazon RDS MySQL
MySQL on EC2 instances

I see Amazon Aurora being marketed as the better alternative however after some research it doesn't seem like people are using it. Is there a problem with it?

A:

You should benchmark Aurora carefully before you consider it. Launch an instance and set up a test instance of your application and your database. Generate as high of load as you can. I did at my last company, and I found that despite Amazon's claims of high performance, Aurora failed spectacularly. Two orders of magnitude slower than RDS. Our app had a high rate of write traffic.
Our conclusion: if you have secondary indexes and have high write traffic, Aurora is not suitable. I bet it's good for read-only traffic though.
(Edit: the testing I'm describing was done in Q1 of 2017. As with most AWS services, I expect Aurora to improve over time. Amazon has an explicit strategy of "Release ideas at 70% and then iterate." From this, we should conclude that a new product from AWS is worth testing, but probably not production-ready for at least a few years after it's introduced).
At that company, I recommended RDS. They had no dedicated DBA staff, and the automation that RDS gives you for DB operations like upgrades and backups was very helpful. You sacrifice a little bit of flexibility on tuning options, but that shouldn't be a problem.
The worst inconvenience of RDS is that you can't have a MySQL user with SUPER privilege, but RDS provides stored procs for most common tasks you would need SUPER privilege for.
I compared a multi-AZ RDS instance versus a replica set of EC2 instances, managed by Orchestrator. Because Orchestrator requires three nodes so you can have quorum, RDS was the clear winner on cost here, as well as ease of setup and operations.

A:

I don't use Aurora personally, but I can HIGHLY recommend RDS over running your own on EC2. Having the failover happen automatically and also the backups is just worth every penny. Especially since RDS isn't that much more expensive.
Aurara looks really good on paper, but the more flexible choice of instances has kept me at PostGreSQL until now. We're looking at migrating to Aurora though, mainly because of the autoscaling storage provisioning and the higher performance.

A:

AWS RDS is the managed database solution which provides support for multiple database options Amazon Aurora, PostgreSQL, MySQL, MariaDB, Oracle, and Microsoft SQL Server. When you go with RDS it will provide inbuilt configuration options such as.

Database Replication for High Availability
Read Replicas for Scalability
Backups & Restore
Operating system and software patches & etc.

This simplifies the overhead of database administration. However the flexibility is limited to the RDS offerings.
Alternatively if you host your database in EC2 instance, you can install the required versions of the database engines, install needed extensions & etc. which provides more flexibility but also requires expertise & adds administration overhead.
When you consider Amazon Aurora in RDS, it differs from the rest of the engines because, its new and fully implemented by Amazon from ground up and offers higher performance, reliability out of the box (As marketed by Amazon) with reasonable pricing. However one limitation with Aurora is that its not included in AWS free-tier, where the smallest instance type it supports is "small".
Note: Some of the features offered by RDS and cost differs, based on the database option you select.


Q:

How can I get Cassini web hosting framework to work without adding it to GAC?

I am trying to use Cassini (from http://www.asp.net/Downloads/archived/cassini/) to host my old style asp.net web service in-process, ideally in a WCF style. However, when I run it, I get an exception that the Cassini.dll could not be found. The Readme.txt that comes with it says to add it to the GAC, but the whole point of using an inprocess hosting is to avoid installing stuff in global places. Any ideas how to make it work without the GAC? Or maybe some other alternatives?

A:

Extract the WebDev.WebHost DLL from your GAC. It has no other dependecies apart from the .NET Framework itself. You can then reference it locally, and instantiate a Server object from it which has a Start() and - hooray - a Stop() method.
I normally browse to the GAC folders at a command prompt and copy files out, but if you Google you'll find other approaches.

A:

Found the way to use the Cassini as well: I had to put Cassini.DLL in the Bin directory under the application root for the your web application.
Source: http://forums.asp.net/p/869425/869846.aspx


Q:

Where is the root morpheme in Modern English evacuate and vacuum?

They both are cognates (it can be easily proved by many etymological sources). The question is : Is it possible to consider VAC as a common root for evacuate and vacuum (we may go further - vacation, vacancy, vacuous etc.).

A:

Clearly they are related through Latin, from e- and vacare (out of and to empty) and from vacuus (empty), and in Latin the shared morpheme is vac-.
More interesting may be the relationships with vain, vast and waste which have similar origins in Latin or proto-Indo-European, but which have more specific meanings in modern English.


Q:

How to bind a key to issue two commands in visual mode?

This question is more general than the problem I am currently faced with, and may not have a solution. But my real problem may have a solution if there is no general solution.
What I want to do is if I use y from visual mode, I want Vim to yank both to the + register and to the regular " register.
I don't care about clobbering the system clipboard, because there are tools I use to record past clipboard entries. I just want a way to yank to clipboard which is easy enough to perform that I may actually make use of it.
Possible approaches

bind key to function which somehow hopefully can grab the range of the selection, and then stick it into both registers -- i think this can be done, i have a magic snippet in my vimrc that does this. I have no idea how it works. Looks like this: vnoremap <silent> x :<C-u>execute 'normal! vlF' . nr2char(getchar()) . 'of' . nr2char(getchar())<CR>
yank and then call function that explicitly copies " register to + register. Not sure how to do a yank and then call some function. might be easier
???
no direct profit likely

A:

set clipboard^=unnamedplus

See :help 'clipboard'.

I don't care about clobbering the system clipboard, because there are tools I use to record past clipboard entries. I just want a way to yank to clipboard which is easy enough to perform that I may actually make use of it.

Clobbering the system clipboard is precisely a rather big issue with synchronizing the unnamed register and the clipboard register when you use a system-wide clipboard manager. It becomes hard to find what you are looking for, which is probably buried below dozens upon dozens of meaningless entries. Think about that.
Another option could be to remap y in visual mode to yank to the system clipboard:
 xnoremap y "+y

Since all yanks are sent to the unnamed register no matter what, the command above will effectively yank the visual selection to the unnamed register and the clipboard register. This is in my opinion a much cleaner solution than using 'clipboard'.


Q:

Q:python: why is my char considered as a str?

I just started python and I'm stuck on a stupid error but I don't understand why it's not working
def encryption(str1):
    i = 0
    for x in str1:
        if (x >= 'a' and x <= 'z' or x >= 'A' and x <= 'Z'):
            str1[i] = str1[i] + 3 % 26 #str[i] = x + 3 % 26
        i+=1
    return str1

when I execute the program I got this error:

TypeError: string indices must be integers, not str.

Can someone explain me why str[i] - 23 is considered as a str ? To me I'm just modifying the ascii value of a char.

A:

Strings in python are not arrays like in C. They are immutable, ie
you can't make in place changes to the string. Your options are turn
the string into a list (similar to a c array) or make a new empty string
and concatenate each encrypted letter onto it (this will probably be faster). Ord converts string to ascii number and chr converts the inverse.
the isalpha method tests true iff the character is in {a-z A-Z}
str1 = 'this is a test string!@#$@#$@'

def encryption(str1):
    new_string = ''
    for character in str1:
        if character.isalpha():
            new_string += chr(ord(character) + 3 % 26)
        else:
            new_string += character
    return new_string

print(encryption(str1))


Q:

How to search a webpage using selenium by any of the keywords inputted?

I am new to selenium in python. I am searching the supreme website by keywords using Xpath as such:
WebDriverWait(driver, 5).until(EC.element_to_be_clickable(
    (By.XPATH, "//a[contains(text(),'Supreme Time Tee')]"))).click()

My question is how would I search keywords for any text and skip until it finds it? For example, I struggle to grab the t shirt labeled "Dragon Tee Heather Grey" that is split into two a href link tags "Dragon Tee" and "Heather Grey".
I want to be able to click either element but I am not sure how to construct this.

A:

can you try this xpath:
 //a[contains(text(),'Dragon Tee')] /parent::div/following-sibling::*/a[contains(text(),'Dusty')]


Q:

Prove that $\int_{\mathbb{R}} \frac{1}{(a^2+t^2)(b^2+t^2)} dt= \frac{\pi}{ab(a+b)}$

Prove that $\int_{\mathbb{R}} \frac{1}{(a^2+t^2)(b^2+t^2)} dt= \frac{\pi}{ab(a+b)}$

For $a,b>0$, the Fourier transform of $f(x) = e^{-a|x|}$ is $\widehat{f}(t) = \dfrac{2a}{a^2+t^2}$.
Otherwise, we have $\int_{\mathbb{R}}\dfrac{1}{(a^2+t^2)^2} dt= \dfrac{\pi}{2a^3} $.
I have to show that $\int_{\mathbb{R}} \dfrac{1}{(a^2+t^2)(b^2+t^2)} dt= \dfrac{\pi}{ab(a+b)}$ ?
I have no idea to do it. Could someone help me ?

A:

Hint:
$$\frac{1}{(a^2+t^2)(b^2+t^2)}=\frac{1}{b^2-a^2}\left(\frac{1}{a^2+t^2}-\frac{1}{b^2+t^2}\right).$$


Q:

PPTP VPN error: LCP terminated by peer

I cannot connect to my PPTP VPN server, even though the CHAP authentication succeeds.
This is from /var/log/syslog:
Jun 11 07:27:22 aspire pppd[32221]: CHAP authentication succeeded
Jun 11 07:27:22 aspire pppd[32221]: LCP terminated by peer (MPPE required but cannot negotiate MPPE key length)
Jun 11 07:27:22 aspire pptp[32232]: nm-pptp-service-32219 log[pptp_read_some:pptp_ctrl.c:544]: read returned zero, peer has closed

A:

I found the answer, I had to enable Point-to-Point encryption(MPPE) in the Advanced Settings dialog. Now it works.


Q:

Finding the limits for integration.

How do we get 0.5 <= u <= 1 and -u <= v <= u over here?

A:

We have a trapezoid $(x,y)\in\Box(1,0)(2,0)(2,0)(1,0)$, and choose to rotate and rescale using $u=(x+y)/2, v=(y-x)/2$.
After this transformation we have: $(u,v) \in\Box(\tfrac 12, -\tfrac 12)(1,-1)(1,1)(\tfrac 1 2, \tfrac 12)$
Hence this transformed region is: $\tfrac 12 \leq u\leq 1$ and $-u\leq v\leq u$
Sketching a diagram of that trapezoid might help you see why.