text:
Q: Architecture for a .NET platform with Rest API I have a .NET platform that I need to expose to different clients (ASP.NET MVC, iOS and Android), I will be developing these clients myself not a third party.
Currently I have a business layer which executes some logic and persists data using entity framework into a SQL DB, what I am thinking now is to have the ASP.NET MVC client access the business layer direct and have the other (non .NET) clients consume the business layer using a REST API, is this a good approach? or do I need to make all the client access biz functionality using the service layer.

A: First, very good question!, for me, I use ASP.NET MVC to access Service Layer, and this is not the layer that exposed to (non.NET) but this the layer that under that layer, I will describe to you why you will need service layer in MVC, one of the aspect of good design in MVC (Thin Controller) and to do this, you will need service layer, otherwise the Controller will be the victim, so you can use it for both.

A: You have some business logic, or functionality, that you want to offer to clients. These clients are: human users that will get access through a ASP.NET app (html/js/css UI) and other applications that will get access through an web API. Right?
The MVC part and the web API part are interfaces, this is translators, that transform clients' requests to business logic invocation and then transform back results to HTML/js/ccs for users or xml/json/whatever to client applications.
The real problem is in the way that you express the concepts, you are NOT making your ASP.NET MVC client access the business layer directly and have the other (non .NET) clients consuming the business layer using a REST API! What you are doing is providing two interfaces, one for human interaction and other for client applications interaction.
Your approach is okay.


text:
Q: How to resolve Exception LocalMemcacheService not found? I have a J2EE Web Appliation...
Built On: Eclipse JUNO (Google app hosting)
OS - Window 7 32_bit
JDK 1.7.0
I am very new to google app development.
I ran and terminated my application many times due to modifications in servlet classes.
But now I am facing a problem to run the app. I did not understand by this error but got is that it is related to  memcache which gae use to store frequently required data.
After googling found that It has limited space. And can erase if full from admin console.
But not got how to do it or is it neessary for the exception..
On running it showing exception...
    Aug 15, 2013 11:27:54 PM com.google.apphosting.utils.config.AppEngineWebXmlReader readAppEngineWebXml
    INFO: Successfully processed C:\Users\Atul Dwivedi\git\CareerYantra\war\WEB-INF/appengine-web.xml
    Aug 15, 2013 11:27:54 PM com.google.apphosting.utils.config.AbstractConfigXmlReader readConfigXml
    INFO: Successfully processed C:\Users\Atul Dwivedi\git\CareerYantra\war\WEB-INF/web.xml
    Aug 15, 2013 11:27:54 PM com.google.appengine.tools.development.SystemPropertiesManager setSystemProperties
    INFO: Overwriting system property key 'java.util.logging.config.file', value 'C:\eclipse\plugins\com.google.appengine.eclipse.sdkbundle_1.8.1.1\appengine-java-sdk-1.8.1.1\config\sdk\logging.properties' with value 'WEB-INF/logging.properties' from 'C:\Users\Atul Dwivedi\git\CareerYantra\war\WEB-INF\appengine-web.xml'
    Aug 15, 2013 11:27:55 PM com.google.apphosting.utils.jetty.JettyLogger info
    INFO: Logging to JettyLogger(null) via com.google.apphosting.utils.jetty.JettyLogger
    Exception in thread "main" java.util.ServiceConfigurationError: com.google.appengine.tools.development.LocalRpcService: Provider com.google.appengine.api.memcache.dev.LocalMemcacheService not found
at java.util.ServiceLoader.fail(ServiceLoader.java:231)
at java.util.ServiceLoader.access$300(ServiceLoader.java:181)
at java.util.ServiceLoader$LazyIterator.next(ServiceLoader.java:365)
at java.util.ServiceLoader$1.next(ServiceLoader.java:445)
at com.google.appengine.tools.development.ApiProxyLocalImpl.startServices(ApiProxyLocalImpl.java:595)
at com.google.appengine.tools.development.ApiProxyLocalImpl.access$700(ApiProxyLocalImpl.java:46)
at com.google.appengine.tools.development.ApiProxyLocalImpl$2.run(ApiProxyLocalImpl.java:584)
at com.google.appengine.tools.development.ApiProxyLocalImpl$2.run(ApiProxyLocalImpl.java:581)
at java.security.AccessController.doPrivileged(Native Method)
at com.google.appengine.tools.development.ApiProxyLocalImpl.getService(ApiProxyLocalImpl.java:580)
at com.google.appengine.tools.development.AbstractContainerService.installLoggingServiceHandler(AbstractContainerService.java:277)
at com.google.appengine.tools.development.AbstractContainerService.startup(AbstractContainerService.java:302)
at com.google.appengine.tools.development.AutomaticServerInstanceHolder.startUp(AutomaticServerInstanceHolder.java:26)
at com.google.appengine.tools.development.AbstractServer.startup(AbstractServer.java:80)
at com.google.appengine.tools.development.Servers.startup(Servers.java:82)
at com.google.appengine.tools.development.DevAppServerImpl.start(DevAppServerImpl.java:237)
at com.google.appengine.tools.development.DevAppServerMain$StartAction.apply(DevAppServerMain.java:339)
at com.google.appengine.tools.util.Parser$ParseResult.applyArgs(Parser.java:48)
at com.google.appengine.tools.development.DevAppServerMain.<init>(DevAppServerMain.java:274)
at com.google.appengine.tools.development.DevAppServerMain.main(DevAppServerMain.java:250)

Please help how to overcome from this ? And also suggest some useful resources to read more of read.

A: "project which is built".  It is not 100% clear what language you are using (you are hinting at java, but eclipse can be used to write in other languages), so I will assume the following:

*

*You are using eclipse to program in java

*Both machines have the same version of java OR the destination machine has a higher version of java than the source machine.

*the compiler compiled it using 32-bit java

If all of these conditions are true, then yes, it will work.  Some problems that can arise if one or more are not met:
If java is not the language you are using, then all of this is irrelevant, and you will need to specify what language you are using.
If the destination machine has an older version of java than what the compiler built the program in, then it will not be able to run.  This is because java is not forwards compatible (this is normal behavior).
This is the important one: IF the compiler built the code into a 64-bit program then NO, the program will not run.  This is because it is impossible for your 32-bit system to have 64-bit java installed.  64-bit machines can run 32-bit code (usually), but not the other way around. Aleroot is correct when he says that the platform and architecture are independent of the host machine, but you must still have a 64-bit JRE to run 64-bit java code, and that JRE cannot run on a 32-bit CPU.

A: Yes, if it is a Java project.
Java is platform and architecture independent, and the program should run without any problem.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to serve a static JSON file from Phoenix with charset utf-8 for Filestack I have a Phoenix app and on the javascript side I use the Filestack client. Filestack requests a JSON file from my server. I had put the file in my asset directory and it gets loaded but the Filestack Javascript client crashes with an error because it can't read the json do to german umlauts (öäü). I looked at the header and it gets served like this Content-type: application/json. I think what I need is Content-type: application/json; charset=utf-8. I also use webpack2 btw.
How do I accomplish this?

A: Plug.Static uses the mime package to set the content-type header. You can override the value for json as described in the mime package's README. Make sure your app is using mime version 1.1.0 or later because the builtin mime types were not overridable due to a bug that was fixed in 1.1.0.
Add this to config/config.exs:
config :mime, :types, %{"application/json; charset=utf-8" => ["json"]}

Then, force recompile mime:
mix deps.clean --build mime

and then start Phoenix:
mix phoenix.server

After this, the content-type of .json files served by Plug.Static should be application/json; charset=utf-8:
$ curl -I localhost:4000/js/foo.json
HTTP/1.1 200 OK
server: Cowboy
date: Sat, 18 Feb 2017 14:36:51 GMT
content-length: 3
cache-control: public
etag: 8EA91E
content-type: application/json; charset=utf-8


text:
Q: Is it possible to use Adobe CS5 with Java SE 7? I have Adobe CS5 installed (old version because it's what my institutional site license covers) on Mavericks.
Whenever I boot my system, I get the following dialog box:

However, I don't have Java SE 6 installed, only Java SE 7 (and JDK 7). I don't particularly want Java SE 6 on my system since it is now quite ancient and probably full of security holes by this point. If I try to launch any of the CS5 apps, I get the same prompt.
Is it possible to run CS5 without Java 6 SE on Mavericks?

A: I don't know if this works for CS5 and Mavericks, but for CS6 I have found a solution for Yosemite (more details there):

*

*Create a directory /System/Library/Java/JavaVirtualMachines/1.6.0.jdk.

*Create a symlink /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents to /Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents from your Java 7 / 8.

*If missing, create an empty directory /System/Library/Java/Support/Deploy.bundle.

Paths on Mavericks may differ a bit though.
Also, you'll probably need to be root to do this, so use sudo using an administrative account.

A: Some applications have expectations about the Java run time that are not compatible with more recent versions of Java; CS5 apps seem to be among those.
Apple has continued to maintain Java 6, addressing security flaws in their version.  The current most recent update for Apple's Java 6 was in May 2014. Oracle meanwhile has moved on to Java 7 and 8 for the platforms it supports, including OS X, and no longer provides free support for its Java 6.
You can have multiple Java 6, 7, and 8s installed at the same time on Mavericks (one JRE, multiple JDKs.) From a terminal window the command /usr/libexec/java_home -verbose will list all those that the system knows about. man java_home will explain how to select one or another.
If you want to run CS5 you will need to install Apple's Java 6.


text:
Q: Finding rows that match with an specific character I have a dataset that contains information about some online purchases made by customer, and I need to create a list of customers if their last name starts with a capital Z.
The dataset looks like this:

So far this is what I have achieved:
# Extracting last name from a sorted list of customers
customers_lastname = str([x.split(" ")[-1] for x in customers_sorted])

# Creating a list of customers that his last names starts with Z using list comprehension

lastname_z = [customer for customer in customers_sorted if customers_lastname[-1].startswith('Z')]

But after printing the results, I'm only getting an empty list : []
What am I doing wrong?


text:
Q: Files created with "sudo" only are accessible by user I have a sudo user, and whenever I use sudo to create, move, or copy a file to any destination (even user's home dir) the file is only accessible by root with the following permission:

-rw-------  1 root    root test.txt

I'd expect it to be readable by group members and others.
Where should I specify this? I don't want to change the permission manually.
Thanks,


text:
Q: Javascript - sort array based on another array Is it possible to sort and rearrange an array that looks like this:
itemsArray = [
    ['Anne', 'a'],
    ['Bob', 'b'],
    ['Henry', 'b'],
    ['Andrew', 'd'],
    ['Jason', 'c'],
    ['Thomas', 'b']
]

to match the arrangement of this array:
sortingArr = [ 'b', 'c', 'b', 'b', 'a', 'd' ]

Unfortunately, I don't have any IDs to keep track on. I would need to priority the items-array to match the sortingArr as close as possible.
Update:
Here is the output I'm looking for:
itemsArray = [
    ['Bob', 'b'],
    ['Jason', 'c'],
    ['Henry', 'b'],
    ['Thomas', 'b']
    ['Anne', 'a'],
    ['Andrew', 'd'],
]

Any idea how this can be done?

A: Something like:
items = [
    ['Anne', 'a'],
    ['Bob', 'b'],
    ['Henry', 'b'],
    ['Andrew', 'd'],
    ['Jason', 'c'],
    ['Thomas', 'b']
]

sorting = [ 'b', 'c', 'b', 'b', 'c', 'd' ];
result = []

sorting.forEach(function(key) {
    var found = false;
    items = items.filter(function(item) {
        if(!found && item[1] == key) {
            result.push(item);
            found = true;
            return false;
        } else
            return true;
    })
})

result.forEach(function(item) {
    document.writeln(item[0]) /// Bob Jason Henry Thomas Andrew
})

Here's a shorter code, but it destroys the sorting array:
result = items.map(function(item) {
    var n = sorting.indexOf(item[1]);
    sorting[n] = '';
    return [n, item]
}).sort().map(function(j) { return j[1] })

A: ES6
const arrayMap = itemsArray.reduce(
  (accumulator, currentValue) => ({
    ...accumulator,
    [currentValue[1]]: currentValue,
  }),
  {}
);
const result = sortingArr.map(key => arrayMap[key]);

More examples with different input arrays

A: I would use an intermediary object (itemsMap), thus avoiding quadratic complexity:
function createItemsMap(itemsArray) { // {"a": ["Anne"], "b": ["Bob", "Henry"], …}
  var itemsMap = {};
  for (var i = 0, item; (item = itemsArray[i]); ++i) {
    (itemsMap[item[1]] || (itemsMap[item[1]] = [])).push(item[0]);
  }
  return itemsMap;
}

function sortByKeys(itemsArray, sortingArr) {
  var itemsMap = createItemsMap(itemsArray), result = [];
  for (var i = 0; i < sortingArr.length; ++i) {
    var key = sortingArr[i];
    result.push([itemsMap[key].shift(), key]);
  }
  return result;
}

See http://jsfiddle.net/eUskE/

A: var sortedArray = [];
for(var i=0; i < sortingArr.length; i++) {
    var found = false;
    for(var j=0; j < itemsArray.length && !found; j++) {
        if(itemsArray[j][1] == sortingArr[i]) {
            sortedArray.push(itemsArray[j]);
            itemsArray.splice(j,1);
            found = true;
        }
    }
}

http://jsfiddle.net/s7b2P/
Resulting order: Bob,Jason,Henry,Thomas,Anne,Andrew

A: In case you get here needing to do this with an array of objects, here is an adaptation of @Durgpal Singh's awesome answer:
const itemsArray = [
  { name: 'Anne', id: 'a' },
  { name: 'Bob', id: 'b' },
  { name: 'Henry', id: 'b' },
  { name: 'Andrew', id: 'd' },
  { name: 'Jason', id: 'c' },
  { name: 'Thomas', id: 'b' }
]

const sortingArr = [ 'b', 'c', 'b', 'b', 'a', 'd' ]

Object.keys(itemsArray).sort((a, b) => {
  return sortingArr.indexOf(itemsArray[a].id) - sortingArr.indexOf(itemsArray[b].id);
})

A: One-Line answer.
itemsArray.sort(function(a, b){
  return sortingArr.indexOf(a) - sortingArr.indexOf(b);
});

Or even shorter:
itemsArray.sort((a, b) => sortingArr.indexOf(a) - sortingArr.indexOf(b));

A: If you use the native array sort function, you can pass in a custom comparator to be used when sorting the array. The comparator should return a negative number if the first value is less than the second, zero if they're equal, and a positive number if the first value is greater.
So if I understand the example you're giving correctly, you could do something like:
function sortFunc(a, b) {
  var sortingArr = [ 'b', 'c', 'b', 'b', 'c', 'd' ];
  return sortingArr.indexOf(a[1]) - sortingArr.indexOf(b[1]);
}

itemsArray.sort(sortFunc);

A: let a = ['A', 'B', 'C' ]

let b = [3, 2, 1]

let c = [1.0, 5.0, 2.0]

// these array can be sorted by sorting order of b

const zip = rows => rows[0].map((_, c) => rows.map(row => row[c]))

const sortBy = (a, b, c) => {
  const zippedArray = zip([a, b, c])
  const sortedZipped = zippedArray.sort((x, y) => x[1] - y[1])

  return zip(sortedZipped)
}

sortBy(a, b, c)

A: For getting a new ordered array, you could take a Map and collect all items with the wanted key in an array and map the wanted ordered keys by taking sifted element of the wanted group.

var itemsArray = [['Anne', 'a'], ['Bob', 'b'], ['Henry', 'b'], ['Andrew', 'd'], ['Jason', 'c'], ['Thomas', 'b']],
    sortingArr = [ 'b', 'c', 'b', 'b', 'a', 'd' ],
    map = itemsArray.reduce((m, a) => m.set(a[1], (m.get(a[1]) || []).concat([a])), new Map),
    result = sortingArr.map(k => (map.get(k) || []).shift());

console.log(result);

A: I hope that I am helping someone, but if you are trying to sort an array of objects by another array on the first array's key, for example, you want to sort this array of objects:
const foo = [
  {name: 'currency-question', key: 'value'},
  {name: 'phone-question', key: 'value'},
  {name: 'date-question', key: 'value'},
  {name: 'text-question', key: 'value'}
];

by this array:
const bar = ['text-question', 'phone-question', 'currency-question', 'date-question'];

you can do so by:
foo.sort((a, b) => bar.indexOf(a.name) - bar.indexOf(b.name));

A: Case 1: Original Question (No Libraries)
Plenty of other answers that work. :)
Case 2: Original Question (Lodash.js or Underscore.js)
var groups = _.groupBy(itemArray, 1);
var result = _.map(sortArray, function (i) { return groups[i].shift(); });

Case 3: Sort Array1 as if it were Array2
I'm guessing that most people came here looking for an equivalent to PHP's array_multisort (I did) so I thought I'd post that answer as well. There are a couple options:
1. There's an existing JS implementation of array_multisort(). Thanks to @Adnan for pointing it out in the comments. It is pretty large, though.
2. Write your own. (JSFiddle demo)
function refSort (targetData, refData) {
  // Create an array of indices [0, 1, 2, ...N].
  var indices = Object.keys(refData);

  // Sort array of indices according to the reference data.
  indices.sort(function(indexA, indexB) {
    if (refData[indexA] < refData[indexB]) {
      return -1;
    } else if (refData[indexA] > refData[indexB]) {
      return 1;
    }
    return 0;
  });

  // Map array of indices to corresponding values of the target array.
  return indices.map(function(index) {
    return targetData[index];
  });
}

3. Lodash.js or Underscore.js (both popular, smaller libraries that focus on performance) offer helper functions that allow you to do this:
    var result = _.chain(sortArray)
      .pairs()
      .sortBy(1)
      .map(function (i) { return itemArray[i[0]]; })
      .value();

...Which will (1) group the sortArray into [index, value] pairs, (2) sort them by the value (you can also provide a callback here), (3) replace each of the pairs with the item from the itemArray at the index the pair originated from.

A: This is what I was looking for and I did for sorting an Array of Arrays based on another Array:

It's On^3 and might not be the best practice(ES6)

function sortArray(arr, arr1){
      return arr.map(item => {
        let a = [];
        for(let i=0; i< arr1.length; i++){
          for (const el of item) {
            if(el == arr1[i]){
              a.push(el);
            }
            }
          }
          return a;
      });
    }

    const arr1 = ['fname', 'city', 'name'];
  const arr = [['fname', 'city', 'name'],
  ['fname', 'city', 'name', 'name', 'city','fname']];
  console.log(sortArray(arr,arr1));

It might help someone

A: this is probably too late but, you could also use some modified version of the code below in ES6 style. This code is for arrays like:
var arrayToBeSorted = [1,2,3,4,5];
var arrayWithReferenceOrder = [3,5,8,9];

The actual operation :
arrayToBeSorted = arrayWithReferenceOrder.filter(v => arrayToBeSorted.includes(v));

The actual operation in ES5 :
arrayToBeSorted = arrayWithReferenceOrder.filter(function(v) {
    return arrayToBeSorted.includes(v);
});

Should result in arrayToBeSorted = [3,5]
Does not destroy the reference array.

A: I had to do this for a JSON payload I receive from an API, but it wasn't in the order I wanted it.
Array to be the reference array, the one you want the second array sorted by:
var columns = [
    {last_name: "last_name"},
    {first_name: "first_name"},
    {book_description: "book_description"},
    {book_id: "book_id"},
    {book_number: "book_number"},
    {due_date: "due_date"},
    {loaned_out: "loaned_out"}
];

I did these as objects because these will have other properties eventually.
Created array:
 var referenceArray= [];
 for (var key in columns) {
     for (var j in columns[key]){
         referenceArray.push(j);
     }
  }

Used this with result set from database.  I don't know how efficient it is but with the few number of columns I used, it worked fine.
result.forEach((element, index, array) => {
    var tr = document.createElement('tr');
    for (var i = 0; i < referenceArray.length - 1; i++) {
        var td = document.createElement('td');
        td.innerHTML = element[referenceArray[i]];
        tr.appendChild(td);

    }
    tableBody.appendChild(tr);
});

A: let sortedOrder = [ 'b', 'c', 'b', 'b' ]
let itemsArray = [
    ['Anne', 'a'],
    ['Bob', 'b'],
    ['Henry', 'b'],
    ['Andrew', 'd'],
    ['Jason', 'c'],
    ['Thomas', 'b']
]
a.itemsArray(function (a, b) {
    let A = a[1]
    let B = b[1]

    if(A != undefined)
        A = A.toLowerCase()

    if(B != undefined)
        B = B.toLowerCase()

    let indA = sortedOrder.indexOf(A)
    let indB = sortedOrder.indexOf(B)

    if (indA == -1 )
        indA = sortedOrder.length-1
    if( indB == -1)
        indB = sortedOrder.length-1

    if (indA < indB ) {
        return -1;
    } else if (indA > indB) {
        return 1;
    }
    return 0;
})

This solution will append the objects at the end if the sorting key is not present in reference array

A:

function sortFunc(a, b) {
  var sortingArr = ["A", "B", "C"];
  return sortingArr.indexOf(a.type) - sortingArr.indexOf(b.type);
}

const itemsArray = [
  {
    type: "A",
  },
  {
    type: "C",
  },
  {
    type: "B",
  },
];
console.log(itemsArray);
itemsArray.sort(sortFunc);
console.log(itemsArray);

A: Why not something like
//array1: array of elements to be sorted
//array2: array with the indexes

array1 = array2.map((object, i) => array1[object]);

The map function may not be available on all versions of Javascript

A:   const result = sortingArr.map((i) => {
    const pos = itemsArray.findIndex(j => j[1] === i);
    const item = itemsArray[pos];
    itemsArray.splice(pos, 1);
    return item;
  });

A: this should works:
var i,search, itemsArraySorted = [];
while(sortingArr.length) {
    search = sortingArr.shift();
    for(i = 0; i<itemsArray.length; i++) {
        if(itemsArray[i][1] == search) {
            itemsArraySorted.push(itemsArray[i]);
            break;
        }
    }
}

itemsArray = itemsArraySorted;

A: You could try this method.
const sortListByRanking = (rankingList, listToSort) => {
  let result = []

  for (let id of rankingList) {
    for (let item of listToSort) {
      if (item && item[1] === id) {
        result.push(item)
      }
    }
  }

  return result
}

A: with numerical sortingArr:
itemsArray.sort(function(a, b){
  return sortingArr[itemsArray.indexOf(a)] - sortingArr[itemsArray.indexOf(b)];
});

A: This seems to work for me:
var outputArray=['10','6','8','10','4','6','2','10','4','0','2','10','0'];
var template=['0','2','4','6','8','10'];
var temp=[];

for(i=0;i<template.length;i++) {
  for(x=0;x<outputArray.length;x++){
    if(template[i] == outputArray[x]) temp.push(outputArray[x])
  };
}

outputArray = temp;
alert(outputArray)

A: You can do something like this:
function getSorted(itemsArray , sortingArr ) {
  var result = [];
  for(var i=0; i<arr.length; i++) {
    result[i] = arr[sortArr[i]];
  }
  return result;
}

You can test it out here.
Note: this assumes the arrays you pass in are equivalent in size, you'd need to add some additional checks if this may not be the case.
refer link
refer

A: Use the $.inArray() method from jQuery. You then could do something like this
var sortingArr = [ 'b', 'c', 'b', 'b', 'c', 'd' ];
var newSortedArray = new Array();

for(var i=sortingArr.length; i--;) {
 var foundIn = $.inArray(sortingArr[i], itemsArray);
 newSortedArray.push(itemsArray[foundIn]);
}

A: Use intersection of two arrays.
Ex:
var sortArray = ['a', 'b', 'c',  'd', 'e'];

var arrayToBeSort = ['z', 's', 'b',  'e', 'a'];

_.intersection(sortArray, arrayToBeSort)

=> ['a', 'b', 'e']
if 'z and 's' are out of range of first array,  append it at the end of result

A: this.arrToBeSorted =  this.arrToBeSorted.sort(function(a, b){
  return uppthis.sorrtingByArray.findIndex(x => x.Id == a.ByPramaeterSorted) - uppthis.sorrtingByArray.findIndex(x => x.Id == b.ByPramaeterSorted);
});


text:
Q: How to customize Date format in Exported CSV from Visualforce? I'm trying to build an export to CSV Visualforce page with dynamic fields that may include Date/Datetime fields in the output.
The trouble coming in my way is, if I don't format date/datetime fields, they get exported into a string with GMT text appended to it, which mostly is not what any external application would understand.
Next thing I tried was to use format() function in APEX and <apex:outputText> tag to output my Date and Datetime fields, but these also did not work, and they both are outputting Time component even for Date only fields.
Can anyone suggest what can I do to get my CSV file output to show Date in Date Only format and Datetime in Date and Time format?
One thing you would want to know is, I'm allowing user to select a Date Format before exporting, which may or may not have Time component in the format string. The Date format is a picklist so user can enter his preferred Date format string. The only issue is, if format has Date + Time component, then all Date values are also formatted with 12:00:00 as Time component value, which is not good.
VF Page:
<apex:page controller="ExportController" language="en-US" cache="true" contentType="text/csv#dataExport.csv" showHeader="false" sidebar="false">
<apex:repeat value="{!columnValues}" var="c">{!c.label}</apex:repeat>{!NewLine}
<apex:repeat value="{!ExportData}" var="e">
    <apex:repeat value="{!columnValues}" var="c">
        <apex:outputText rendered="{!(c.datatype=='DATE' || c.datatype=='DATETIME') && selectedTemplateRecord.Format_Date_As__c != ''}" value="{0,date,{!selectedTemplateRecord.Format_Date_As__c}}">
            <apex:param value="{!e[c.name]}" />
        </apex:outputText>
        <apex:outputPanel layout="none" rendered="{!(c.datatype!='DATE' && c.datatype!='DATETIME') || selectedTemplateRecord.Format_Date_As__c == ''}">{!e[c.name]}</apex:outputPanel>
    </apex:repeat>
    {!NewLine}
</apex:repeat>
</apex:page>

In APEX Class the data is fetch like this:
public list<sObject> getExportData()
{
    String qry = 'select ' + fieldNames + ' from ' + objectName + ' where ID IN: recordIds';
    list<sObject> records = database.query( qry );
    return records;
}


text:
Q: UITableViewController Background Color I'm struggling getting the color behind the UITableView to be the gray I want.  The background of the UITableView seems to be working fine, but the area behind it still remains white?

here is the end of my view.  There is only one cell in this and its not a cropped image.  I'm using a UITableViewController so I've set the background of the table view and all the cells.  But still the area above (when you pull to refresh) and the area below are white.

A: Actually you have to set the gray you want as the background color of the UITableViewCell.
Set the backgroundColor property:
cell.backgroundColor = [UIColor grayColor];

Note that the backgroundColor must be set in the tableView:willDisplayCell:forRowAtIndexPath: method.

A: Its hard to judge with whatever you have mentioned in your question. If the background color of tableView is working fine as per your expectation then could you please try setting clear color for your cells for them to use tableView's color. I hope this should work and if not then could you please share the code of your view controller for us to have a closure look on whats happening.
cell.backgroundColor = [UIColor clearColor];


text:
Q: Filtering special characters in ng-repeat with AngularJS? I would like to get the same result when I search Éric or Eric in an object. But I can't get Eric if I type "Éric" (Like it works with mySQL)
with something like this:
Object : { idEmployee=12710, firstName ="Eric", lastName="Tremblay", more...}
<input type="text" ng-model="modelFilter">

        {{friend.firstName}} {{friend.lastName}}

A: I believe there exists no built-in method to convert text from "Éric" to "Eric", so you should manually create a simple function which replaces special characters with their standard equivalents. Then, create a method for replacement in your controller:
$scope.modelFilterNormalized = function(){
    if($scope.modelFilter)
        return $scope.modelFilter.replace('É','E').replace(/* ... */);
    else return '';
};

...and use it instead of modelFilter:


text:
Q: Project Structure using MVC 4 As the subject says...this question is about setting up the correct structure for my project only. if you think there is a better place to ask this question then please advise.
I have a MVC 4 project using ET & repository pattern. I have DAL & UI layer at this point.
Currently i am using my DAL for data access and I created my Interfaces &  ViewModels within my Data Access Layer. i have a feeling i am doing it wrong. here is my Sample Set up.
MY DAL LAYER (Which contains below Interface, Repo & ViewModel)
DAL.ViewModel
Public Class ProductSummaryViewModel
    Property productGUID As Integer
    Property productName As String
End Class

DAL.Interface (For Repostiory Pattern)
Public Interface IProductRepository
    Property ProductIdentityID As Integer
    Property ImageMainPath As String
End Interface

DAL.Products Repository
Public Class productsRepository
    Implements IProductRepository

    Private _db As websolutionsEntities = New websolutionsEntities()

Public Function AddProduct(ByVal prdSummary As ProductSummaryViewModel) As Boolean Implements IProductRepository.AddProduct

       _db.AddProduct(prdSummary )
       Return true

  End Function

And here is my Controller
Private ProductRepoitory As DAL.IProductRepository
    Sub New()
        Me.new(New DAL.productsRepository())
    End Sub

    Sub New(ByVal repo As DAL.IProductRepository)
        repo = ProductRepoitory
    End Sub

Public Function AddItem(ByVal prd As DAL.ProductSummaryViewModel) As ActionResult
        Dim test as boolean = DAL.ProductRepoitory.AddItem(prd)
End Function

My project will grow in near future, so I want to set it up properly, however I don't want to make it too complicated as well for others and myself. Please advise with your suggestions.

A: Your can divide your project like this:
CORE

*

*Interfaces(Ex: IProductRepository)

*Domain(Ex: Product)

DAL

*

*ProductRepository

MVC

*

*ViewModels or Models(Ex: ProductsSummaryViewModel)

*Controllers(Ex: ProductsController)

Make folders like Interfaces, Domain under CORE. You probably already have a controller folder in MVC frontend project. You also probably already have a folder called Models, just use that for ViewModels. Any thing used just for display purposes like the ViewModel classes should just exist in the front end.


text:
Q: Error while updating SiteLogoUrl with Powershell I am trying to update the Site Logo Url for all the sites in my web application with powershell. The script executes correctly in my dev environment but fails to execute in production and gives an error
Exception calling "Update" with "0" argument(s): "Object reference not set to an instance of an object."
At D:\Set-WebAppLogoUrl.ps1:28 char:11
+     $_.Update <<<< ();
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

I logged in the system with a farm account but still get the error. Any help would be appreciated. Below is my PS Script I am trying to execute:
$siteUrl = "http://mysite/sites/it"
$rootSite = New-Object Microsoft.SharePoint.SPSite($siteUrl)
$spWebApp = $rootSite.WebApplication

foreach($site in $spWebApp.Sites) {
    $site.AllWebs | foreach {
        $_.SiteLogoUrl = "/PublishingImages/companylogo.gif";
        $_.Update();
    }
}
$rootSite.Dispose()

A: Have  you looked at Ravi script.
http://social.msdn.microsoft.com/Forums/en/sharepoint2010general/thread/67f901e9-b4d7-4bee-87c9-0a585e61405e

A: My guess would be that you have a site collection which is in a state where it doesn't have any sites.
I'd change the scipt to :
$siteUrl = "http://mysite/sites/it"
$rootSite = New-Object Microsoft.SharePoint.SPSite($siteUrl)
$spWebApp = $rootSite.WebApplication

foreach($site in $spWebApp.Sites) {
    $site.AllWebs | foreach {
        if ($_ -ne $null) {
            $_.SiteLogoUrl = "/PublishingImages/companylogo.gif";
            $_.Update();
        }
    }
}
$rootSite.Dispose()


text:
Q: Matching words with spaces regex in java This one is so simple, but seems to be stumping me.
I have the following text line:
for        months to

I am trying to match it with the following regex:
for\s*months\s*to

I read this regex as:

*

*Must have the word "for"

*Followed by any amount of space

*Followed by the word "months"

*Followed by any amount of space

*Followed by the word "to"

And to me, this should match, but it doesnt. Can anyone see where I might have gone wrong.

A: It's because of the trailing spaces.
Try this:
    Pattern p = Pattern.compile("for\\s*months\\s*to\\s*");
    Matcher m = p.matcher("for        months to   ");
    System.out.println(m.matches());

A: You most likely have preceding or succeeding whitespace. Using String.matches(String regex) you must match the entire string.
Try "\\s*for\\s+months\\s+to\\s*"


text:
Q: What happens to the ViewState when I click back on the browser? I'm curious to know what happens to the ViewState on the browse back button.
Does it stay or does the page make a new request?

A: Viewstate remains no more .NET implementation once it render to html , they become the normal hidden field sitting in the html of the page. So when you do the browse back button , in most of the time we get the page from the Cache of the browser , there will be no request to server. There is no way only ViewState will update itself without refreshing the page , because at the end of the day Viewstate nothing but some hidden field .


text:
Q: Create a Responsive Div with 900px width? i am not a web developer, i do it for fun, so i have a question...
How to turn a div with 900px into a responsive when i lower screen resolution?
Here is my code (i am new at coding):

.container
{
  width: 900px;
  background-color: #fda2a2;
}

.headline
{
  padding: 5px 30px;
  font-size: 20px;
  font-family: Helvetica;
}
.text
{
  padding: 5px 30px;
  font-size: 15px;
  font-family: Helvetica;
}

Column title

Cras justo odio, dapibus ac facilisis in, egestas eget quam. Donec id elit non mi porta gravida at eget metus. Nullam id dolor id nibh ultricies vehicula ut id elit.

I don't want to put a percentage at width (.container)... Anyone know how to do this? :)

A: You should use max-width instead of width.

.container {
    max-width: 900px;
    margin: 0 auto;
    background-color: #fda2a2;
}

.headline {
    padding: 5px 30px;
    font-size: 20px;
    font-family: Helvetica;
}
.text {
    padding: 5px 30px;
    font-size: 15px;
    font-family: Helvetica;
}

Column title

Cras justo odio, dapibus ac facilisis in, egestas eget quam. Donec id elit non mi porta gravida at eget metus. Nullam id dolor id nibh ultricies vehicula ut id elit.

A: You should use a combination of width and max-width. No need for media queries
.container {
  max-width: 100%;
  width: 900px;
  background-color: #fda2a2;
}

or
.container {
  max-width: 900px;
  width: 100%;
  background-color: #fda2a2;
}

This way the .container will never be bigger than the screen width, and can't become bigger than 900px

A: If you are using px its hard to manage it in responsive. So either go with percentage. If you need to use px itself, then you can use media query and mention the respective px using media query for various sizes.
Refer this, http://www.w3schools.com/css/css_rwd_mediaqueries.asp

A: You can use media query.

The @media rule is used to define different style rules for different media types/devices.

.container
{
  width: 900px;
  background-color: #fda2a2;
}

.headline
{
  padding: 5px 30px;
  font-size: 20px;
  font-family: Helvetica;
}
.text
{
  padding: 5px 30px;
  font-size: 15px;
  font-family: Helvetica;
}

@media (max-width: 600px) {
    .container {
      width:100%;
    }
}

Column title

Cras justo odio, dapibus ac facilisis in, egestas eget quam. Donec id elit non mi porta gravida at eget metus. Nullam id dolor id nibh ultricies vehicula ut id elit.

A: You can accomplish this by using media queries for like

/* Make sure your standard css is always on top of media queries */

    .container
    {
      width: 900px;
      background-color: #fda2a2;
    }

    .headline
    {
      padding: 5px 30px;
      font-size: 20px;
      font-family: Helvetica;
    }
    .text
    {
      padding: 5px 30px;
      font-size: 15px;
      font-family: Helvetica;
    }

    Then below you need to set the style for each screen size and behaviour e.g

    /* Portrait and Landscape */
    @media only screen
      and (min-device-width: 320px)
      and (max-device-width: 480px)
      and (-webkit-min-device-pixel-ratio: 2) {
      .container{
        background-color:red;
    }

    /* Portrait */
    @media only screen
      and (min-device-width: 320px)
      and (max-device-width: 480px)
      and (-webkit-min-device-pixel-ratio: 2)
      and (orientation: portrait) {
.container{
        background-color:yellow;
    }
    }

    /* Landscape */
    @media only screen
      and (min-device-width: 320px)
      and (max-device-width: 480px)
      and (-webkit-min-device-pixel-ratio: 2)
      and (orientation: landscape) {
    .container{
        background-color:black;
    }
    }

for different types of media queries that supports different devices check here CSS-tricks


text:
Q: How to change the button text EDIT to UPDATE? Here i use this code to enable and disalbe text box on clicking on edit button.
but here what i want is on click of EDIT button the text of the button should change to UPDATE
    **CODE**
    <input type="text" input-disabled="editableInput" />
    <button ng-click="editableInput = !editableInput">EDIT</button>

     app.controller("myController", function(){
     $scope.editableInput = false;
     });

    app.directive("inputDisabled", function(){
    return function(scope, element, attrs){
    scope.$watch(attrs.inputDisabled, function(val){
    if(val)
     element.removeAttr("disabled");
    else
     element.attr("disabled", "disabled");
      });
     }
    });

I tried as much i can, some one help me out in this.

A: How about:
<button ng-click="editableInput = !editableInput">
    UPDATE
    EDIT
</button>


text:
Q: ASP.NET Role Provider vs Membership Provider Please refer to this post.
I have become able to configure my web.config file so that when an unauthenticated user requests a page, he is redirected to the Login.aspx page.
I have been able to do that by configuring web.config file and the following few lines of code:
protected void btnLogin_Click(object sender, EventArgs e)
        {
            string username = this.usernameTextBox.Text;
            string password = this.passwordTextBox.Text;

            bool success = Membership.ValidateUser(username.Trim(), password.Trim());

            if (success)
            {
                FormsAuthentication.SetAuthCookie(username, true);

                Ice_Web_Portal.BO.User user = Ice_Web_Portal.BO.User.GetUserByUserName(username);

                Ice_Web_Portal.BO.UserTypeEnum loginUserType = user.UserTypeEnum;

                if (loginUserType == UserTypeEnum.Student)
                {
                    Response.Redirect("~/Student/StudentControlPanel.aspx?username=" + username);
                }
                else if (loginUserType == UserTypeEnum.Teacher)
                {
                    Response.Redirect("~/Teacher/TeacherControlPanel.aspx?username=" + username);
                }
                else if(loginUserType == UserTypeEnum.Webmaster)
                {
                    Response.Redirect(@"~/Webmaster/WebmasterControlPanel.aspx");
                }
                else
                {
                    labLoginMessage.Text = "Sorry! Type of user couldn't be determined!";
                }
            }
            else
            {
                labLoginMessage.Text = Ice_Web_Portal.BO.User.LoginMessage;
            }
        }

But the problem I am having with this is that, once a user is Authenticated, he can access all pages in the entire web application.
But I need to restrict their area of page access according to their roles. I.e. when a user with a different role requests a page, he should be automatically redirected to the Login.aspx page.
There may be a technique in which I can check for specific user-roles in the Page_Load()-event and then redirect the user to the Login.aspx page if he is not in that role. But I don't want to do it in that way. I want to happen that automatically. I need to use only Role Provider framework and web.config file (as that was in the case of membership. I.e. I don't need to check membership in the Page_Load event. Web.config file is automatically blocking the access).
Can anyone tell me how can I incorporate Role feature in this so that specific users are confined within their specific Role-area?
What is the Code for generating the Authorization Ticket?

A: add sections to web.config
  <location path="page-only-allowed-to-be-accessed-by-admin.aspx">
      <system.web>
         <authorization>
           <allow roles="admin"/>
           <deny users="*" />
         </authorization>
      </system.web>
   </location>

You may find this article interesting - the web.config demystified
EDIT:
The code for generating the Authorization ticket is in your code.
FormsAuthentication.SetAuthCookie(username, true);

which is implemented like so (using Red Gate's Reflector)
public static void SetAuthCookie(string userName, bool createPersistentCookie, string strCookiePath)
{
    Initialize();
    HttpContext current = HttpContext.Current;
    if (!current.Request.IsSecureConnection && RequireSSL)
    {
        throw new HttpException(SR.GetString("Connection_not_secure_creating_secure_cookie"));
    }
    bool flag = CookielessHelperClass.UseCookieless(current, false, CookieMode);
    HttpCookie cookie = GetAuthCookie(userName, createPersistentCookie, flag ? "/" : strCookiePath, !flag);
    if (!flag)
    {
        HttpContext.Current.Response.Cookies.Add(cookie);
        current.CookielessHelper.SetCookieValue('F', null);
    }
    else
    {
        current.CookielessHelper.SetCookieValue('F', cookie.Value);
    }
}

The RoleProvider will get the roles for a given user, so when the web.config is inspected for allowed or denied roles/users for a given section of your application, the RoleProvider will get the roles for the user and then check against the allowed/denied roles and authorize if appropriate.

A: Use the Role Provider.
Once you have setup the role provider, and assigned roles to your users, you can use the <authorization> section of Web.config to restrict access to your various resources based on role membership.
I suggest you use the SqlRoleProvider if you have an SQL Server available. It is very flexible in that it can assign roles to user names without the users having to be registered first - specifically, you don't need to also use the SqlMembershipProvider (or in fact any membership provider). Ie. if you add the role "Student" to the user name "John", the SqlRoleProvider will simply associate that role with that user name, and everything just works.
Good luck!

A: If you have a set of restricted files in a folder you can resitrict the Roles to that folder in the web.config:
eg:
<location path="TeacherAdmin" allowOverride="false">
  <system.web>
    <authorization>
      <allow roles="Teacher"/>
      <deny users="*,?"/>
    </authorization>
  </system.web>
</location>

Note: The path attribute can also point to a specific aspx page


text:
Q: Mapping user/group from host to docker container I want to develop some php and use docker for php containers. What I'm interested in running php code & tailing php log. Looking at docker hub I found php image https://hub.docker.com/_/php/ which is pretty much what I want.
However I entered in file permissions problems when using this image with mapped volumes (-v option in docker run).
In my local development folder file permissions are set up 1000:100 while in docker image it's accessed with 33:33 what is with www-data user and group. The www-data:www-data is default one for apache web server to access the data.
One possibility is tell apache to run as new user, however this option have shortcoming since I'm working in a team and hardcoding userid's would complicate things further.
How can I make this transition seamless, that is map file permissions accordingly?
I want to map permissions 1000:100 (UID:GID) from my local user to www-data:www-data in container space.
I run following command as reference:
docker run -d --name server -p 8080:80 -v $(PWD):/var/www/html php:7-apache

A: Got it to work with modified httpd.conf and mount that to the run cmd:
docker run -dit --name h2 -p 8082:80 -v /home/core/my-www:/usr/local/apache2/htdocs/:ro -v /home/core/myConf/httpd.conf:/usr/local/apache2/conf/httpd.conf:ro httpd:latest

Could not get this to work: https://github.com/docker-library/php/issues/14
My httpd.conf

#User daemon
#Group daemon
###Tilo MOD
User #1000
Group #100


text:
Q: Bash - How to store a list of directories sorted by timestamp of directory creation I have a list of directories that I am iterating over to save into a list like so
dirs=''
for d in */ ; do
  dir_name=${d%/}

  tag="foobar:${dir_name}-${sha1}"

  dirs+="{\"app_image\":\"${tag}\",\"dir_name\":\"${dir_name}\"},"
done

but instead of */ is it possible to iterate over a list of directories sorted by the directory creation timestamp? I'd like this list to always have new directories appended to the end of the list, rather than the list being sorted alphabetically
EDIT: As pointed out in the comments, directory creation time may not be available. The repository is version controlled through git so I'll check out git commands in the mean time to see if that helps otherwise I'll look into a hackier workaround

A: This would output a JSON reassembling your output but entirely in jq:
It builds arguments to jq with dirs
jq -n '
# Start a JSON array
[
  # Handle each positional argument
  # remove trailing slash /
  $ARGS.positional[] | rtrimstr("/") | {
    # Starting a new Object with app_image and dir_name
    # Compose app_image tag using dir name and sha1 argument
    "app_image": ( "foobar:" + . + "-" + $sha1 ),
    # same with dire_name
    "dir_name": . }
]' \
--arg sha1 "aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d" \
--args */


text:
Q: Can an event be dispatched to Activity after onDestroy? Consider that activity is destroyed and onDestroy was fired. Can I be sure that no other messages will be dispatched into this activity handlers like onKeyDown?

A: According to the docs, no.
"OnDestroy
The final call you receive before your activity is destroyed"
http://developer.android.com/reference/android/app/Activity.html


text:
Q: Check What Letters are in a String I am making a Hangman Game in C# in WPF, and I am wondering if there is a way to check what letters are in a string so that if a letter is choosen the program can determine if the letter is in the chosen word or not.
Ex.
String StackOverFlow; //Sample String

//If Letter "A" is chosen,
private void AButt_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
//What Would I Put Here?
}

A: You could use Contains(), but that is going to be case sensitive. Hangman is not.
The easiest way to handle that is to use IndexOf() instead:
if(StackOverFlow.IndexOf("A", StringComparison.CurrentCultureIgnoreCase) > -1)
{
    // Found
}
else
{
    // Not Found
}

A: Use Contains:
StackOverFlow.Contains("A");

If you also want to know where in the word the letter first appears, you can use IndexOf:
StackOverFlow = "EXAMPLE"
StackOverFlow.IndexOf("A"); //returns 2
StackOverFlow.IndexOf("B"); //returns -1 because it is not present

A: You could use the String.Contais method. And don't create one event handler for each letter - create only one which checks what letter was input, then do something according to it existing in the string or not.

A: You can use ToLower() first to tackle case-sensitivity:
    StackOverflow.ToLower().Contains("a")


text:
Q: Cannot read property in ionic cordova build android --prod --release Im trying to build my apk for deploying the application in the playstore. Here is the error. Im really out of time and I have to fix this error as soon as possible. Any reference about this is much appreciated.
ionic cordova build android --prod --release
Running app-scripts build: --prod --platform android --target cordova
[09:25:34]  build prod started ...
[09:25:35]  clean started ...
[09:25:35]  clean finished in 12 ms
[09:25:35]  copy started ...
[09:25:36]  deeplinks started ...
[09:25:37]  deeplinks finished in 601 ms
[09:25:37]  ngc started ...
Warning: Can't resolve all parameters for AngularFirestore in E:/sdg-biz-mobile/node_modules/angularfire2/firestore/index.d.ts: ([object Object], ?). This will become an error in Angular v6.x
Warning: Can't resolve all parameters for AngularFirestore in E:/sdg-biz-mobile/node_modules/angularfire2/firestore/index.d.ts: ([object Object], ?). This will become an error in Angular v6.x
TypeError: Cannot read property 'flags' of undefined
    at checkUnreachable (E:\sdg-biz-mobile\node_modules\typescript\lib\typescript.js:24905:31)
    at bindChildrenWorker (E:\sdg-biz-mobile\node_modules\typescript\lib\typescript.js:23111:17)
    at bindChildren (E:\sdg-biz-mobile\node_modules\typescript\lib\typescript.js:23055:17)
    at bind (E:\sdg-biz-mobile\node_modules\typescript\lib\typescript.js:24319:21)
    at bindSourceFile (E:\sdg-biz-mobile\node_modules\typescript\lib\typescript.js:22689:17)
    at Object.bindSourceFile (E:\sdg-biz-mobile\node_modules\typescript\lib\typescript.js:22640:9)
    at initializeTypeChecker (E:\sdg-biz-mobile\node_modules\typescript\lib\typescript.js:47988:20)
    at Object.createTypeChecker (E:\sdg-biz-mobile\node_modules\typescript\lib\typescript.js:27142:9)
    at getDiagnosticsProducingTypeChecker (E:\sdg-biz-mobile\node_modules\typescript\lib\typescript.js:69678:93)
    at emitWorker (E:\sdg-biz-mobile\node_modules\typescript\lib\typescript.js:69722:32)
[09:25:50]  copy finished in 14.73 s

A: I faced this type of errors.Below solution is helped me.
Step1:
rm -rf node_modules

Step2:
npm cache clean --force

Step3:
Delete package_lock.json

Step4:
npm install

I hope it will help you.


text:
Q: Android checkbox with custom selector inside recyclerview I made recyclerview with checkbox so you can select each item and button on bottom of the screen when pressed return selected items from list.The problem is that no matter what i do button always return that 0 items were selected.I found that checkbox status is always false even thought icon from checkbox change when i click checkbox. I use custom selector to change icon inside checkbox but i can't find the way to change checkbox status inside program.
This is the fragment that contain recyclerview
    @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_main, container, false);
    Resources res = getResources();
    titles = res.getStringArray(R.array.muscle_titles);

    recyclerMain = (RecyclerView) rootView.findViewById(R.id.MainList);
    adapter = new MainAdapter(getActivity(), getData(getActivity()));
    recyclerMain.setAdapter(adapter);
    recyclerMain.setLayoutManager(new LinearLayoutManager(getActivity()));
    return rootView;
}

public static List<MainRowInformation> getData(Context context){
    List<MainRowInformation> data = new ArrayList<>();

    for(int i=0;i<titles.length;i++){

        final MainRowInformation current = new MainRowInformation();
        current.title = titles[i];
        current.checkBox = new CheckBox(context);
        current.checkBox.setChecked(false);

        data.add(current);
    }

    return data;
}

This is recyclerview adapter
    private LayoutInflater inflater;
private List<MainRowInformation> data = Collections.emptyList();

public MainAdapter(Context context, List<MainRowInformation> data) {
    this.data = data;
    inflater = LayoutInflater.from(context);
}

@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = inflater.inflate(R.layout.row_main, parent, false);
    MyViewHolder holder = new MyViewHolder(view);
    return holder;
}

@Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
    MainRowInformation current = data.get(position);
    holder.title.setText(current.title);
    //mozda je krivo sljedeca linija
    holder.checkbox = current.checkBox;

}

@Override
public int getItemCount() {
    return data.size();
}

class MyViewHolder extends RecyclerView.ViewHolder{

    TextView title;
    CheckBox checkbox;

    public MyViewHolder(View itemView) {
        super(itemView);
        title = (TextView) itemView.findViewById(R.id.MainListText);
        checkbox = (CheckBox) itemView.findViewById(R.id.MainListCheckBox);

    }
}

Checkbox
    <CheckBox
    android:id="@+id/MainListCheckBox"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:button="@drawable/main_list_button_icon"/>

Checkbox Selector
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@mipmap/ic_list_uncheck"
    android:state_checked="false" />
<item android:drawable="@mipmap/ic_list_check"
    android:state_checked="true"/>

the button return 0 but 3 items were selected

A: Found the solution all i had to do was to make checkbox onClickListener inside MyViewHolder. I did that previously but it wasn't working for some reason.
    class MyViewHolder extends RecyclerView.ViewHolder{

    TextView title;
    CheckBox checkbox;

    public MyViewHolder(final View itemView) {
        super(itemView);
        title = (TextView) itemView.findViewById(R.id.MainListText);
        checkbox = (CheckBox) itemView.findViewById(R.id.MainListCheckBox);
        checkbox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            if(checkbox.isChecked()){
                checkbox.setChecked(false);
            }else{
                checkbox.setChecked(true);
            }
            }
        });

    }
}


text:
Q: Probability / Mean of two randomly drawn sequences? Let's say I have a real valued random variable $X$ distributed according to a continuous non normal cdf $G(x)$ with mean $\mu$, standard deviation $\sigma$ and pdf $g(x)$. Furthermore I have a set of natural number $[k]$ where $\{k \in \mathbb{N} : 0 < k < 30\}$. Now I go on as follows:

*

*From $[k]$ I randomly sample one number $K$

*From $X$, I sample my first random sequence of size $K$: $S_1=\{x_{1,1}, x_{1,2}, ..., x_{1,K}\}$ with sample mean $\bar{S_1}=\frac{1}{K}\sum_{k=1}^K x_{1,k}$.

*From $X$, I sample my second random sequence of size $K$: $S_2=\{x_{2,1}, x_{2,2}, ..., x_{2,K}\}$ with sample mean $\bar{S_2}=\frac{1}{K}\sum_{k=1}^K x_{2,k}$
What is now the probability that $\bar{S_2} < \bar{S_1}$?

A: Take my answer with a grain of salt, but wouldn't it be $ \frac{1}{2} $? I assume that the sampling is an independent event in your case. In that case, since $ \overline{S}_1 $ and $ \overline{S}_2 $ are i.i.d., the chance that $ P(\overline{S}_2 < \overline{S}_1) = P(\overline{S}_2 > \overline{S}_1) = P(\overline{S}_2 \geq \overline{S}_2) $, where the last equation holds since $ \overline{S}_1, \overline{S}_2 $ are continuously distributed (at least I assume you meant that with "real valued random variable X"). Since $ 1 = P(\overline{S}_2 < \overline{S}_1) + P(\overline{S}_2 \geq \overline{S}_2) $, it follows in total that $ P(\overline{S}_2 < \overline{S}_1) = P(\overline{S}_2 \geq \overline{S}_2) = P(\overline{S}_2 > \overline{S}_2) = 0.5 $


text:
Q: Stop Users Concurrently Signing In Via Different Machines - Identity Server 4 I am using Identity Server 4 with the quickstart UI and a client using Cookie Authentication.
Lets say I have user A on machine A who is currently logged in via the browser.  Then user A decides to go on machine B and logs into that one.  As it stands, a new session cookie will be issued for user A on machine B as well as machine A.
This is fine, but I want the option to mark particular users with a flag e.g. IsConcurrent and if it is set to true, they will be given the option to either keep their existing session on machine A, or terminate it and start a new session on machine B.
I have done some reading and found references here to updating the security stamp for a user and setting the interval to zero, so it checks the security stamp in the cookie against the stored version.  However, this code didn't seem to be inline with Identity Server's code.  Also, it it a valid option in this case?
I also found here which mentions storing and checking the value of session IDs, but I'm not sure if this is valid either?
An initial idea was to implement some middleware that obtained the Machine ID and stored it in a table along with the user, but then I was unsure how to take something like this any further.
Any help or advice would be much appreciated.

A: Assuming cookie based authentication, you can extend the client to validate the user session provided that the client keeps track of user sessions.
For that you can create a session manager where you add a session for the user (sub) after login, this also includes automatic login sessions (SSO). Remove one or all sessions on logout, which should also be updated on back channel logout (LogoutCallback).
Assuming you use middleware, you can consult the session manager there and decide what to do. Make sure that the current session isn't already activated after login. It has to step through the middleware at least once. Some pseudo code to illustrate the idea:
public Task Invoke(HttpContext context, SessionManager sessionManager)
{
    if (context.Principal.Identity.IsAuthenticated)
    {
        var sub = context.Principal.FindFirst("sub")?.Value;
        var sid = context.Principal.FindFirst("sid")?.Value;

        // User is allowed when the current session is active.
        if (!sessionManager.CurrentSessionIsActive(sub, sid))
        {
            // Rewrite path if user needs and is allowed to choose: redirect to session selector or
            // Activate the current session and deactivate other sessions, if any.
            if (sessionManager.HasMultipleSessions(sub) && sessionManager.CanSelectSession(sub))
                context.Request.Path = new PathString("/SelectSession");
            else
                sessionManager.ActivateCurrentSession(sub, sid);
        }
    }
    return _next(context);
}

On post of the SelectSession form you can mark in the session manager which sessions are active. If the old session should be preserved, then ignore the old session (remains active) and mark the current session as active.
Make sure to add the middleware after authenticating the user.
Please note that for access tokens you'll need a different strategy.


text:
Q: Getting Facebook video ID using jQuery I've made a script that gets the ID for YouTube and Vimeo, but I am not sure how to get the ID from the Facebook embed URL.
Example embed:

I need to get the ID which in this case is: 1261009690594307
How can I it with YouTube? I am new to JS so not sure how to replicate but getting the ID for this one.
$.each($('iframe[src*="youtube.com"]'), function() {
    var player = $('
');
    var id = $(this).attr('src');
    id = id.substr(id.lastIndexOf("/")+1);
    player.attr('data-id', id);
    player.html(videoThumbYT(id));
    player.on('click', videoIframeYT);

    var videoContainer = $('
');
    videoContainer.append(player);
    $(this).replaceWith(videoContainer);
});

A: Fastest using the Regular Expressions.
function fbvideoID(frame) {
  var myRegexp = /2F(\d+)%/g;
  var match = myRegexp.exec(frame);
  return match[1];
}

var facebookVideo = '';

document.write(fbvideoID(myString)); //returns ID 1261009690594307

Explanation
Regular Expression
/2F(\d+)%/g

Selects the ID. Test it here!
var match = myRegexp.exec(frame);

Returns array of two elements. Documentation here.
0: "2F1261009690594307%"
1: "1261009690594307"

The 0 index is always the whole expression. The 1 is only the (\d+) - braces. Which contains our ID.
Hope I helped you!

A: Here's one approach, could be refined a bit.

$.each($('iframe[src*="facebook.com/plugins/video"]'), function() {

    var url = decodeURIComponent($(this).attr('src'));
    var id = url.match(/\/\d+\//);
    if (id) {
        id = id.slice(1,-1);
        console.log(id);
        //do your player stuff here.
    }
});


text:
Q: Isn't MVC anti OOP? The main idea behind OOP is to unify data and behavior in a single entity - the object. In procedural programming there is data and separately algorithms modifying the data.
In the Model-View-Controller pattern the data and the logic/algorithms are placed in distinct entities, the model and the controller respectively. In an equivalent OOP approach shouldn't the model and the controller be placed in the same logical entity?

A: MVC works at a much higher level of abstraction than single objects, and in fact each of the three (model, view and controller) will typically consists of many objects that each have both data and behavior.
That objects which encapsulate data and behavior are a good fundamental building block for programs in general doesn't mean it's the best pattern at all levels of abstraction and for all purposes.

A: OOP does not restrict interactions among objects that each have their own data and their own behavior.
Think of an ant and an ant colony analogy: behavior of an individual ant (run around all day, bringing food) is different from behavior of the overall colony (find the most desirable place, make more ants). The MVC pattern describes the desired social structure of an ant colony, while OOP guides the design of individual ants.

A: MVC is an exercise in Separation of Concerns, a UI architecture.  It is a way to corral the complexity that can occur in user interfaces due to the presentation not being separated from the content.
In theory, all objects can have behavior that operate on the data they contain, and that data and behavior remain encapsulated.  In practice, a given OOP object may or may not have logic that corresponds to its data, or may not have any logic at all (a Data Transfer Object, for example).
In MVC, the business logic goes in the model, not the controller. The controller is really just a go-between to glue together the View and the Model. So in the model, you can have data and behavior in the same place.
But even that arrangement does not guarantee strict data/behavior fusion.  Objects containing only data can be operated on by other classes containing only logic, and this is a perfectly acceptable use of OOP.

I'll give you a specific example. This is a bit contrived, but let's say you have a Currency object, and that object has the ability to represent itself in any available currency, pegged to the dollar.  So you would have methods like:
public decimal Yen { get { return // dollars to yen; } }
public decimal Sterling { get { return // dollars to sterling; } }
public decimal Euro { get { return // dollars to euro; } }

...and that behavior would be encapsulated with the Currency object.
But what if I wanted to transfer the currency from one account to another, or deposit some currency?  Would that behavior also be encapsulated in the Currency object?  No, it wouldn't.  The money in your wallet cannot transfer itself out of your wallet into your bank account; you need one or more agents (a teller or ATM) to assist in getting that money into your account.
So that behavior would be encapsulated into a Teller object, and it would accept Currency and Account objects as inputs, but it would not contain any data itself, except maybe a bit of local state (or maybe a Transaction object) to help process the input objects.

A: MVC is a pattern which describes a sensible way for objects to interact; it is not itself a meta-class. At that, OO is about describing behaviours and data of entities, and how said entities interact. It isn't about unifying the entire system into one massive object.

A: Controller does not represent the behavior of a model. Controllers altogether represent the behavior of the whole application _ what a user can do and what a user can see.
It is wrong to view controllers and models as one. They have different purposes, different semantics and thus shouldn't be unified in one object.

A: The model layer is not merely data any more than the controller layer is merely logic.
The controller layer will have a complete collection of objects for its purposes. There will be objects for receiving input from the view, and from transforming that input into a form the model can process. The Struts Java framework has a good example of this in its Action/Form model. The Form is populated with input from the user, and then passed to the Action. The Action takes that data and uses it to manipulate the model.
In the same way, the Model layer doesn't consist entirely of data. Take a User object, for example - you may need code that gets a user from a database, or code to associate a User with an Order, or to validate that the User's address is within the area your company services...you get the picture. This is not controller logic. It's business logic, and it's led many to split their Model layer into several layers such as Service or Manager layers for business logic, a DAO (Database Access Object) layer for database access, and others.
MVC isn't a method for organizing individual Model operations. It works at a higher level than that - it's a method for organizing how the application is accessed. View is for presenting data and human actions for manipulating it, Controller is for translation between user actions and the various views, and the Model is where business data and the business reasons for it to exist reside.

A: The point of OOP is to group together data and functionality that belong together. A calculation that is based on some piece of data does not always belong with that data.
In MVC the functionality to display a piece of data (view) is kept separate from the data (model). Why is that? It's specifically so that the display logic can be changed without having to change the underlying data. It makes it easy to change the view whenever you need to make a different presentation of the same data: or when the characteristics of the display hardware change: or when you switch from Windows to Linux; or when you want two people to have two different ways of looking at the same data.
MVC isn't in conflict with OOP - it is actually derived from a correct application of Object Oriented Principles.

A: OOP is also about Separation of concerns, that is to separate different roles/responsabilities in different objects.
MVC separates into these components :

*

*Model : the data and its business logic

*View : representation of the data

*Controller : coordination between the model and the view.

So these responsabilities are clearly distinct and should indeed be separated into multiple entities.

A:
In the Model-View-Controller pattern the data and the logic/algorithms
  are placed in distinct entities, the model and the controller
  respectively.

Model and controller are two distinct roles. A model has both state and logic, and a controller has both state and logic. The fact that they communicate doesn't break the encapsulation of either one -- the controller doesn't know or care how the model stores its data, or what it does to the data when the controller retrieves or updates some part of it. The model doesn't know or care what the controller does with data that the model provides.
Think of it this way: if objects couldn't pass data back and forth without breaking encapsulation, you could really only have one object!

In an equivalent OOP approach shouldn't the model and the controller
  be placed in the same logical entity?

MVC is an OOP approach -- specifically, it's a recipe for deciding how to use objects to organize a program effectively. And no, the model and controller shouldn't be the same entity. A controller allows separation between model and view. Keeping model and view independent of each other makes them both more testable and more reusable.

A: As I understand it; The argument is component based architecture vs OOP. And without getting into the religious war, I think that they are both describing the same thing; just looking at it from different angles.
For example, the whole point of OOP/OOD is to make your code more modular and reusable. Yes?
Which is exactly the goal of component based architecture. So they are more alike than anything else.
I think that MVC is just the natural evolution of OOP and dare I say it; a better way to organize your objects, separation of concerns and code reuse.

A: I believe you're confusing persistent data bound to a model object with the application data from the databases the model interacts with. A model contains business logic and rules for working with databases and conducting transactions. It might set and check internal state flags like whether there's a sale today, whether the user qualifies for VIP status and then branch logic accordingly when it comes time to access, set, or manipulate data or conduct a purchase. It's those flags we're talking about when we discuss objects in terms of encapsulation of a set of methods and persistent values or data.
Just as the model object maintains data for establishing what business rules are in play, a controller should, IMO, hold on to more general application state data pertinent to how the app should behave, like whether the user is logged in or they have valid credit card data in place. Model methods would determine the state of these things in the first place but it makes sense for the controller to maintain flags pertinent to general app flow if they don't apply to how the business is run or data transactions are conducted. Once you've determined they're not logged in, don't even bother the model with user state checks until it's clear another log-in attempt is being made.
Likewise with a proper view object vs. the more typical HTML templates you see in most server-side web frameworks. Once the user's color preferences are loaded up, it should be the view that holds on to that data and executes on it. Loading, validating and changing settings are all model problems but they should only be model problems once until changes happen.
IMO, nothing says controllers can't be composite objects with views and models as internal aggregate objects. This actually makes sense if you apply MVC on a smaller scale like a UI widget factory since the controller is the ideal place to expose an interface to higher level app objects while burying the data and logic details of how the View and Model interact. It doesn't really make sense for monolothic app objects where the controller is really the highest level object though.

A: In my Opinion OOPs has a drawback that since the (data and behavior) are moulded as one entity(Class) this shows more coupling effect than cohesion.
Whereas on the other hand MVC it has Model containing...(Beans, DAOs, Other Logic classes),
Controller that specifies how the control must travel and Views to determine how the data should be shown are given in a seperated fashion.
Based on this no matter if the project is Too big to prepare can be easily made as seperate entity other than getting mixed unlike OOPs.
The problem is solved in logical pattern just like divide n conquer strategy and MVC follows this atmost.

A: I am late to this party, and considering all the answers before mine, I admit I don't have much new to offer. But it seems to me that the question isn't about the pattern itself but about the implementation. MVC in and of itself does not lend itself to any particular methodology. In fact, I can easily envision procedure oriented code in an MVC pattern (which is what I felt like you were implying).
So, I think the real question is; are we more prone to procedural code when using the MVC pattern.
(and maybe I'll just get some down votes?)

A: Not anti, but also OOP is not required for MVC.
Because controllers, which are usually represented by classess hold no data.
For which pure functions would suffice.
If you go further and separate data from behaviour, for example let's say that models work only on database data, which they fetch every time their function (that is responsible for data manipulation) is called (instead for storing some kind of data in the instance fields) - then you can say the same for the models.
Going further, if you take the view layer of an application and divide it in similar fashion, you will actually end with conclusion that MVC has nothing to do with OOP, and it is completely possible to write MVC implementation without any pain using only procedurall approach.


text:
Q: past tense vs present perfect vs past perfect These are the words spoken by a cinema hero, about fight sequences in a newspaper interview

But I have done riskier action scenes in my prime.

Why "have done (present perfect format)" is used here? Can we use past tense or past perfect formats as given below? If so, what is the difference in meaning in these three forms?

But I had done riskier action scenes in  my prime
But I did riskier action scenes in my prime


text:
Q: MySQL Best approach for recording last update timestamp for every column and every row This question is about possible approaches for time stamping every column of every row in a table.
I have a table with a small number of rows (fewer than 200 and not likely to grow much larger). Each row refers to an individual entity and each column corresponds to piece of data about that entity. The columns will be updated whenever new information becomes available, and I need to record when that happens.
For example, think in terms of a contacts table:
CREATE TABLE `contacts` (
    `id` INT NOT NULL AUTO_INCREMENT,
    `name` VARCHAR(100),
    `address` VARCHAR(100),
    `phone_number` VARCHAR(100),
    `email_address` VARCHAR(100),
    `updated` TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    PRIMARY KEY (`id`)
);

If the phone number is updated this month, we might be inclined to believe that the `email_address` was updated as well, even though it may be severely outdated.
I can think of three approaches:
1. Create an additional timestamp column for each column:
CREATE TABLE `contacts` (
    `id` INT NOT NULL AUTO_INCREMENT,
    `name` VARCHAR(100),
    `name_updated` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    `address` VARCHAR(100),
    `address_updated` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    `phone_number` VARCHAR(100),
    `phone_number_updated` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    `email_address` VARCHAR(100),
    `email_address_updated` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (`id`)
);

2. Or, I could created a secondary table that contains the same information:
CREATE TABLE `contacts_updated` (
    `id` INT,
    `name` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    `address` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    `phone_number` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    `email_address` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (`id`),
    CONSTRAINT `fk_contacts_updated_contacts_id`
        FOREIGN KEY (id)
        REFERENCES contacts (id));

In which case, is there an easy way to duplicate a table and automatically change the column types to timestamps? And use triggers to update the secondary table?
3. Or, I could create an Entity-Attribute-Value table:
CREATE TABLE `contacts_updated` (
    `id` INT,
    `column_name` VARCHAR(15),
    `updated` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (`id`)
);

...but this seems like it would be more difficult to query the information.
Are there other options that would be better? And I also assume that the answer will be different for a small dataset vs. a large one, so I'd love to know your opinion on both cases.

A: COMMENTARY
I love this question because I answered another question like it 7 years ago

*

*June 30, 2013 : Get the Time of Last update of a column
You actually wrote the SQL I had suggested. I am impressed.
YOUR ACTUAL QUESTION
IMHO I would go with Suggestion #3 because its implementation is as normalized as you are going to get. The retrieval of the deltas for any column would consume the least amount of memory in the InnoDB Buffer Pool, memory within the DB Connection, and the smallest footprint on disk.
The other suggestions would have so much redundant data that retrieving the delta info would most likely push your working dataset out of the InnoDB Buffer Pool frequently.
CAPTAIN'S LOG : SUPPLEMENTAL
Surprisingly, there is an alternative.
MariaDB has implemented all the above suggestions into a table metadata framework called a Temporal Table. What you are going to implement falls under the category "System-Versioned", which tracks the Change History of all table rows. The best part about "System-Versioned Temporal Tables" is that you do not need to explicitly create and track timestamps. That's done for you.
The only drawbacks I can think of are the following:

*

*Small Learning Curve in Understanding MariaDB's SQL Dialect for Temporal Tables.

*The timestamps are for the row not the column. This means a column may change or not from one iteration of a row's point-in-time to the next. You may need write some fancy SQL GROUP BY or DISTINCT aggregation to go through each row and stare at the column you wish to track or audit.


text:
Q: Unable to understand algorithm for Longest Increasing Sub-sequence I have been through many online resources to understand how the problem has the optimal sub-structure, but all in vain, I am unable to comprehend how the solution is obtained by solving smaller sub-problems in this case.
I would be thankful if any explanation helps in understanding the solution.
so far, I understand the optimal sub-structure property as follows:
Example Factorial:
So for a factorial of 40 ,fact(40), we can achieve the solution by calculating fact(39)*40, and so on for 39,38....2 ans as we know that fact(2) is 2 we can build it up from 2 to 40 in the same way.
But I am not able to relate in terms of LIS, please help
A full explanation of the solution would be nice, excluding the overlapping subproblems issue, as that can be handled later on.
Thanks.

A: LIS for the sequence (problem) can be solved by using LIS for the smaller sequences (sub-problem)and that's why it is known to have the optimal sub-structure.
Let me try to explain how this works with the example. Let's take a random sequence of 10 numbers:
[21, 24, 13, 48, -3, 41, 36, 8, -10, 22]
We will use smaller problems (smaller sequence) to solve this problem. The definition of the subproblem is this case is 'What is the longest increasing sequence of numbers that ends at a given element?'
It is important to understand that this subproblem is NOT the same as LIS- the subproblem has a stricter definition that the original problem (LIS doesn't need to end at the last element).
For readability purposes, I'll call the 'longest increasing subsequence that ends at given element': LIS*.
The relationship between LIS* and LIS is that LIS takes Max of LIS*
Let's start with just one number.
[21]
What is the longest increasing subsequence that ends at 21? It is simply '21'. Therefore the length of our sequence is 1.
Sequence: [21]
LIS*: 1
LIS:  1
Now, for the second element (24), according to the definition, we need to use the solution for the problem we already solved. We will use LIS for the first element, check whether second element is bigger (a[i] > a[j) and whether LIS[j]+1 > LIS[i]. The longest increasing sequence that ends at 24 is '21, 24' and has the length of 2.
Sequence: [21, 24]
LIS*: 2
LIS:  2
Let's take 3rd element (13). What is the longest increasing subsequence that ends at 13? Well, 13 is smaller than 21 and smaller than 24 so the condition a[i] > a[j] is not fulfilled for any of the previous elements.The longest increasing subsequence that ends at 13 is therefore just '13' and has the length of 1. LIS for sequence 21,24,13 is still 2.
Sequence: [21, 24, 13]
LIS*: 1
LIS:  2
Let's look at 4th element (48). We know that the solution for the 3-length sequence was 2. We can find previous element (24) that fulfils criteria a[i] > a[j] and LIS[j]+1 > LIS[i]. We know that solution for the previous element (smaller problem) was 2, therefore the solution here will be 2+1=3.
Sequence: [21, 24, 13, 48]
LIS*: 3
LIS:  3
We repeat the logic for all subsequent elements.
Sequence: [21, 24, 13, 48, -3, 41, 36, 8, -10, 22]
LIS*:            1    2    1    3    1    3    3    2    1    3
LIS:             1    2    2    3    3    3    3    3    3    3
As you can see, the solution to the original problem (long sequence) can be obtained by looking at sub-problem (smaller sequences) and therefore this problem is known to have the optimal sub-structure.

A: Before considering optimal substructure, you need to decide what are subproblems in the case of LIS. Let's use this definition:

In an array a[N] of length N a subproblem LIS[k] is to find the length of a longest increasing subsequence from the initial index, which ends precisely at the element a[k].

It is important to understand the difference here: LIS[k] is not a solution to LIS on the first k elements; that would be Max(LIS[i]) for all is up to k. It is the length of the longest increasing subsequence that ends at the particular element.
With this definition in hand, it is easy to construct a solution to LIS:

*

*For each i up to N:

*Set LIS[i] to 1 (in the worst case, a number is a subsequence of one)

*Search LIS[j] from the initial element up to i-1, inclusive, for js such that a[i] > a[j], and LIS[j]+1 > LIS[i].

It is easy to see that the above algorithm constructs a solution to LIS[i] given solutions to subproblems LIS[j] for all js below i in O(i). Since we can construct a solution to a k problem from solutions to k-1 sub-problems, the problem has optimal substructure.
Note: The above can be further optimized by using binary search. The reasoning about subproblem and optimal substructure remains the same, though.


text:
Q: Show comon custom field results? There is custom field "color" in posts with set of hex color codes (all in one custom field, separated with one space). Examples of custom field values for 5 posts:
"000000 f0f0f0 c0c0c0 202020 404040 "
"0000ee 555333 cc0000 602040 003399 "
"9999cc 0000cc 0099ff 204010 552299 "
"406040 ffffff ffcccc 000000 202020 "
"cc0000 99ffcc cc9900 ff9999 000000 "

Posts 1, 4 and 5 have same color "000000"
posts 1 and 4 have same color "202020", and
posts 2 and 5 have same color "cc0000".
In my example most used single colors would be: "000000", "202020" and "cc0000".
How to show most used single colors (not whole set of colors), for example 20 most used single colors?

A:     //Your color codes
        $str1 = "000000 f0f0f0 c0c0c0 202020 404040 ";
        $str2 = "0000ee 555333 cc0000 602040 003399 ";
        $str3 = "9999cc 0000cc 0099ff 204010 552299 ";
        $str4 = "406040 ffffff ffcccc 000000 202020 ";
        $str5 = "cc0000 99ffcc cc9900 ff9999 000000 ";

    //creating an array and merging all codes
        $final_arr = array_merge( explode(" ",$str1),explode(" ",$str2),explode(" ",$str3),explode(" ",$str4),explode(" ",$str5) );

    //removing all empty elements
        $final_arr = array_filter($final_arr);

        //echo '
'; print_r($final_arr); echo '
';

    //Getting count of each element
        $vals = array_count_values($final_arr);

        //echo '
'; print_r($vals); echo '
';

    //Sorting array in high to low order
        arsort($vals);

//Getting first 3 elements with highest count
        $first_n = array_slice($vals, 0, 3,true);

        echo '
'; print_r($first_n); echo '
';

    //Output
    Array
    (
        [000000] => 3
        [cc0000] => 2
        [202020] => 2
    )


text:
Q: What is the meaning of "@" in relation to PowerShell and HTML code as a variable? I saw a code snippet here some time ago that dealt with PowerShell and HTML.
An HTML code was passed into a variable. The beginning and the end were delimited with @" and "@.
In a response, the @ delimiter was labelled with a specific term.
Unfortunately, I did not save the post.
Can someone tell me what this '@' delimitation is called and how exactly it is used?

A: See this article for more info on here strings which are what that is called. You can use a here string in that manner to define some html.
$html = @"

Header 1

Paragraph

@"

If you didn't use the here string you could run into errors parsing the html in various libraries because of the / that close tags.

A: The syntax element you describe is a here-string expression:
@"
your string content goes here
...

and can span multiple lines!
"@

Like any other double-quoted string it's expandable (that is, you can embed variables and subexpressions):
@"
1 + 2 = $(1 + 2)!

... and the Process ID of this host application is ${PID}
"@

They can also be useful for single-line strings containing mixed verbatim quotation marks:
# no need to escape quotation marks
@"
The movie was titled "Jennifer's body"
"@

as opposed to escaping the quotation marks inline, which can become quite unreadable:
"The movie was titled `"Jennifer's body`""
"The movie was titled ""Jennifer's body"""  # this many double-quotes makes me dizzy
'The movie was titled "Jennifer''s body"'

Here-strings are documented in the about_Quoting_Rules help topic


text:
Q: Flask Response download doesn't work for large csv files My current flow is that the user posts a form, I fetch a DataFrame using their input, and I try to start a download for a csv containing the DataFrame's  data.
Current code:
return Response(
    df.to_csv(),
    mimetype="text/csv",
    headers={"Content-disposition": "attachment; filename=output.csv",
                         'Content-Type': 'application/octet-stream'})

This correctly starts a download for smaller amounts of data, but if I across some unknown size threshold, no download starts. I am printing the head of the DataFrame each time, so I know that operation is working.
My guess is that it is somehow timing out, or not accepting the Response because of the file size.
I added the octet stream header from another similar thread.
Edit: it may have been Chrome's automatic download blocking. Not sure how to get around that, i.e. make a regular download that Chrome doesn't find suspicious.

A: I'm running a Flask app and have been suffering from similar symptoms since the beginning of this year.
I generated xlsx and let download the file with send_file(). This was all working until last year. I have multiple pages within the app that have the same functionality and some continue to work correctly.
I thought that send_file() might be the cause, so I started using response(), but the download stopped halfway through.
Checked with Chrome, safari, firefox.
However, this does not reproduce locally, it occurs when operating on EC2.


text:
Q: importing compressed (lzo) data from s3 to hive I export my DynamoDB tables to s3 as a means of backup (via EMR). When I export, I store the data as lzo compressed file.  My hive query is below, but essentially I followed the "To export an Amazon DynamoDB table to an Amazon S3 bucket using data compression" at http://docs.amazonwebservices.com/amazondynamodb/latest/developerguide/EMR_Hive_Commands.html
I now want to do the reverse - take my LZO file(s) and get them back into a hive table.  How do you do this? I was expecting to see some hive configuration property for input, but there is not.  I've googled and found some hints, but nothing definitive and nothing that works.
Files in s3 are in the format: s3://[mybucket]/backup/year=2012/month=08/day=01/000000.lzo
Here is my HQL that does the export:
SET dynamodb.throughput.read.percent=1.0;
SET hive.exec.compress.output=true;
SET io.seqfile.compression.type=BLOCK;
SET mapred.output.compression.codec = com.hadoop.compression.lzo.LzopCodec;

CREATE EXTERNAL TABLE hiveSBackup (id bigint, periodStart string, allotted bigint, remaining bigint, created string, seconds bigint, served bigint, modified string)
STORED BY 'org.apache.hadoop.hive.dynamodb.DynamoDBStorageHandler'
TBLPROPERTIES ("dynamodb.table.name" = "${DYNAMOTABLENAME}",
"dynamodb.column.mapping" = "id:id,periodStart:periodStart,allotted:allotted,remaining:remaining,created:created,seconds:seconds,served:served,modified:modified");

CREATE EXTERNAL TABLE s3_export (id bigint, periodStart string, allotted bigint, remaining bigint, created string, seconds bigint, served bigint, modified string)
 PARTITIONED BY (year string, month string, day string)
 ROW FORMAT DELIMITED FIELDS TERMINATED BY ','
 LOCATION 's3://<mybucket>/backup';

INSERT OVERWRITE TABLE s3_export
 PARTITION (year="${PARTITIONYEAR}", month="${PARTITIONMONTH}", day="${PARTITIONDAY}")
 SELECT * from hiveSBackup;

Any ideas how to get it from s3, decompress, and into hive table??

A: Hive on EMR can natively read data directly from S3, you don't need to import anything. You just have to create an external table and tell it where the data is.
It also has lzo support setup. Hive will automatically decompress using lzo if the files end with a .lzo extension.
So to "import" your lzo data in s3 into hive, you just create an external table pointing to your lzo compressed data s3, and hive will decompress it whenever it runs a query over it. Pretty much exactly what you did when you "exported" data. That s3_export table, you can also read from.
If you want to import it to a non-external table, just insert overwrite into a new table and select from the external table.
Unless I misunderstood your question and you meant to ask about importing to dynamo, not just a hive table?
This is what I've been doing
SET hive.exec.compress.output=true;
SET io.seqfile.compression.type=BLOCK;
SET mapred.output.compression.codec = com.hadoop.compression.lzo.LzopCodec;

CREATE EXTERNAL TABLE users
(id int, username string, firstname string, surname string, email string, birth_date string)
ROW FORMAT DELIMITED FIELDS TERMINATED BY '\t' LINES TERMINATED BY '\n'
STORED AS TEXTFILE
LOCATION 's3://bucket/someusers';

INSERT OVERWRITE TABLE users
SELECT * FROM someothertable;

I end up with a bunch of files under s3://bucket/someusers with .lzo extensions which are readable by hive.
You only need to SET the codec when trying to write compressed data, reading it the compression is detected automatically.


text:
Q: Execute a JavaScript method, when a p:outputLabel is rendered I am rendering a <p:outputLabel>, when validation failed like this.
<p:outputLabel value="Validation Failed"
               styleClass="validation-error"
               rendered="#{facesContext.validationFailed}"
               onfocus="myMethod();"/>

I want to execute a JavaScript function namely myMethod(), when this label is rendered. I also used onfocus attribute but it doesn't work.

A: Ignoring potential design problems (perhaps you actually need a document event listener?), you can achieve this by simply nesting a <script> (or <h:outputScript>) in the component.
<p:outputLabel ...><script>myFunction()</script></p:outputLabel>

I only renamed "myMethod" to "myFunction" conform JavaScript terminology.


text:
Q: How can I create a view that does a joins a table to itself and gives a means to select based on a key value I have the following table DDL:
CREATE TABLE [dbo].[Test] (
    [UserId]                  NVARCHAR (128) NOT NULL,
    [TestId]                  INT            IDENTITY (1, 1) NOT NULL,
    [ExamId]                  INT            NOT NULL,
    [Title]                   NVARCHAR (100) NULL,
    [Status]                  INT            NOT NULL,
    [CurrentQuestion]         INT            DEFAULT ((999)) NOT NULL,
    CONSTRAINT [PK_Test] PRIMARY KEY CLUSTERED ([TestId] ASC)
);

This table contains:

*

*A list of ALL Exams and Tests that are available. These rows have a UserId = 0

*A list of Exam and Test that are in progress for a particular user (UserId != 0)

*A user may have one or may have multiple rows in this table.

Is there a way that I can create a view that shows a list of all the tests and where it exists the additional information for a user if that user has started a test. I'm really not sure if this needs to be a view or a stored procedure as it would need to take as input a UserId.
For the UserId = 1 who in this example has started two of the available tests:
ExamId  TestId   Title      Status

1       1        Exam1Test1 Started
1       2        Exam1Test2
2       3        Exam1Test3 Started
2       4        Exam1Test4

or for the UserId = 2 who in this example has started three of the available tests:
1       1        Exam1Test1 Started
1       2        Exam1Test2
2       3        Exam1Test3 Started
2       4        Exam1Test4 Started

A: Your schema implies that any given test may be taken by at most one user at a time.
The query that will return the results you want is:
select
  ExamId,
  TestId,
  Title,
  case when userId = ? then "Started" else "" end as Status
from Tests

Of course you would replace the ? in the query with the actual user you're interested in.


text:
Q: Referening chunked Dataframe - Pandas I have broken a large dataframe into small chunks. I am now trying to pass the data from these chunks into a loop but I am not sure how to call each of these chunked dataframes.
I have broken the Dataframe into 4 chunks as shown below. But I am not sure how to call each of these chunked Dataframe and pass them in a loop
n = 4
chunks = [df[i:i+n] for i in range(0,df.shape[0],n)]

A: *

*you describe a bigdf that is chunked into a list of data frames.  I have simulated this

*if you want a list comprehension of rows in subset of data frame list it's a simple case of effectively looping over both lists

import pandas as pd
import numpy as np
bigdf = pd.DataFrame({"chunk":np.random.choice(range(10),1000),"value":np.random.uniform(2,3,1000)})
# list of dataframes that are chunks from bigdf
df = [bigdf.loc[bigdf["chunk"].eq(i)] for i in range(10)]
n = 4
# list comprehension of required chucks and array of each row in chunk
[v for chunk in range(n) for v in df[chunk].values ]


text:
Q: TFS 2015 running vNext build and test on same machine Are there any issues with running a vNext build agent on the same machine that is running Functional Tests?  My plan is to have an agent pool that consists primarily of test machines where each build agent has a one-to-one relationship to running functional tests on each respective machine.

A: Yes, you have the ability to run some Unit Tests both on a machine different from that one is running the build and on the same machine.
To select build agent in a pool which include multiple agents:

You can add a User Capability to that specific build agent then in the
  build definition you put that capability as a demand (General tab)

How to specify a build agent in vNext build
About how to configure build pipeline and deploy test agent, you could refer below tutorials:

*

*Running Automated Test on agent machine using vNext Build

*TFS — Setup CI/CD pipeline for automated functional tests
Hope this helps.


text:
Q: heroku cedar console I've been trying to get a heroku console session going on cedar and am having no joy.
The old way was:
heroku console

I understand the new way involves 2 steps:
heroku run bash

then
$ rails console

but at the heroku run bash stage i keep geting:
heroku run bash
Running `bash` attached to terminal... up, run.1
 !
 !    Timeout awaiting process

so i checked there isn't a port blocking issue and
telnet rendezvous.heroku.com 5000

gives
Trying 50.19.103.36...
Connected to ec2-50-19-103-36.compute-1.amazonaws.com.
Escape character is '^]'.

which is as expected i think
what am i doing wrong and what do i need to do to get this console up and running?
Thanks!
PS I have tried - heroku run console - also, and that times out too.

A: In cedar every command that needs to be attached to terminal uses run.
ex:
heroku run console
heroku run rake db:migrate

When its not necessary to be attached don't use the run:
ex: heroku logs

A: The new way is heroku run console

A: Ok - it was obvious after a few hours of sleep. Simply had to update the heroku gem that had got corrupted somehow on my mac. If you have something like this problem, then do that first...


text:
Q: How to configure windows 7 to use Centos as DNS server? I have a CentOS VM that I have configured as a DNS server and a windows 7 VM that is a client. I have configured that TCP/IP settings and specified centos as DNS server and changed primary DNS suffix in windows as well.
Problem is I can ping using IP,but using FQDN doesn't work. When I do nslookup in windows I get this:

Here are DNS configuration:

A: Your windows machine cannot connect to the DNS server.

*

*Ensure you have the correct address configured on the windows system.

*Ensure that the DNS server process is listening on 192.168.1.1.

*Ensure that the CentOS firewall is allowing inbound connections on port 53 to 192.168.1.1.