text:
Q: comma in coffee script / framerjs When do we use a comma after function declaration in coffee script?
For eg, in the code below why is there a comma after Events.DragStart?
layerA.on Events.DragStart, ->
    print layerA.draggable.layerCursorOffset

A: The comma is not after the function declaration but after the first argument. Coffeescript is just a syntax for Javascript, so you can always compile it to Javascript to see what it does.
E.g. pasting your code snippet into the js2.coffee web service yields this Javascript:
layerA.on(Events.DragStart, function() {
  return print(layerA.draggable.layerCursorOffset);
});


text:
Q: Problem with Identity scaffolding in ASP.NET Core MVC I made a MVC project, that includes 2 projects.

*

*class library (.NET Core) - i have my models and services/options here

*ASP.NET Core Web Application - Controllers, views here

I want to add identity to my project. So i found the following NuGet Packages

*

*Microsoft.AspNetCore.Identity.EntityFrameworkCore

*Microsoft.AspNetCore.Identity.UI

*Microsoft.Extensions.Identity.Stores

I used public class NameDbContext : IdentityDbContext<IdentityUser> in my DbContext class.
I clicked Add on the Web-project -> choose "New Scaffolded Item" -> pictures below
What i want to choose
The Error i get
Any ideas?
EDIT:
i can see in my database that the tables are created, after the NuGet Packages and the add-migration & update-database commands that followed.
I also tried my DbContext class without the <IdentityUser> like this
public class NameDbContext : IdentityDbContext

A: You can try to updated all NuGet packages from Tools->Nuget Package Manager -> Manage NuGet Packages for Solution -> Updates tab -> Update All.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Strange behavior with array as static class property Can I have an associative array as a property of a class?
I have been trying but I get very strange results on something like this:
class MyClass {
  public static $quality = array('blue' => 20, 'green' => 30, 'yellow' => 40);
  public $car = array();
  public $bus = array();

  function __construct() {
     foreach(self::$quality as $key => $value) {
         $this->car[$key] = $value;
         $this->bus[$key] = $value;
         echo $this->car[$key] . '
';
         echo $this->bus[$key] . '
';
     }
     foreach(self::$quality as $key => $value) {
         echo $this->car[$key] . ' - ' . $this->bus[$key] . '
';
     }
  }
}

I am expecting this output:
20
20
30
30
40
40
40 - 40
30 - 30
20 - 20

but instead, I'm getting:
20
20
30
3
40
4
20 - 4
30 - 4
40 - 4

That's it. Only green and yellow bus miss the second digit...
And in a different point in my class, when I have something like this:
$attrib = 'bus';
$index = 'blue';
echo $this->$attrib[$index];

I get

Undefined Property MyClass::$b

Any hints on what I'm doing wrong?
Or PHP doesn't accept associative arrays as properties of classes? Any help will be greatly appreciated.

Here is the code I isolated. If you run this PHP by itself you should get the strange behavior...
<?php
    ini_set('display_errors',1);
    error_reporting(E_ALL);

    class Session
    {
        public static $per_page_count = array('photo' => 8 ,'book' => 20, 'road' => 30, 'lodge' => 30, 'tag' => 50);
        public $current_page = array();
        public $per_page = array();
        public $total_count = array();

        function __construct()
        {
            foreach (self::$per_page_count as $page_key => $page_count)
            {
                if (isset($this->per_page[$page_key]))
                {
                    if ($this->per_page[$page_key] == '') $this->per_page[$page_key] = $page_count;
                }
                else  $this->per_page[$page_key] = $page_count;
                if (isset($this->current_page[$page_key]))
                {
                    if ($this->current_page[$page_key] == '') $this->current_page[$page_key] = 1;
                }
                else $this->current_page[$page_key] = 1;
                $this->total_count[$page_key] = 1;
            }
        }

        public function get_set($attribute,$index='',$value='')
        {
            echo '
before - '.$attribute.'-'.$index.'-'.$value.'
';
            if (trim($value) != '')
            {
                if (property_exists($this,$attribute))
                {
                    $this->$attribute['aaa'] = 50;
                    if ($index != '')
                    {
                        $_SESSION[$attribute][$index] = $value;
                        $this->$attribute[$index] = $value;
                    }
                    else
                        $_SESSION[$attribute] = $this->$attribute = $value;

                    $arraykey = array_keys($this->$attribute);
                }
            }
            else
            {
                if ($index != '')
                    return $this->$attribute[$index];
                else
                    return $this->$attribute;
            }
            echo '
';
            print_r($this);
            echo '
';
            echo '
after - '.$attribute.'-'.$index.'-'.$value.'
';
            echo '
variable - '.$this->$attribute[$index].'-'.$value.'
';
        }
    }

    $session = new Session();
    $session->get_set('current_page','photo',4);
    $session->get_set('total_count','photo',150);
?>

At the bottom, you see that I call get_set() twice and each time, instead of setting the property inside the class, it creates a new property.
What am I doing wrong? A appreciate any help.

A: Wrong:
$attrib = 'bus';
$index = 'blue';
echo $this->$attrib[$index];

Correct:
$attrib = 'bus';
$index = 'blue';
$hash = $this->$attrib
echo $hash[$index];

What's happening in the wrong version? First, it's possible to lookup a character in a string by position. For instance:
$str = 'abcdefg';
echo $str[1];  // outputs 'b'

$attrib[$index] is being evaluated first. PHP is treating $index as a numeric index for the $attrib string, with $index being cast to a number (in PHP 'blue' == 0). Since $attrib[0] == 'b', PHP is looking for $this->b hence the Undefined property error.


text:
Q: print number of digits of an integer How to print just for example 3 last digits of a signed integer as hexadecimal number?
int num = -5;
printf("%03X\n", num);
prints FFFFFFFB
I need it to print just FFB

A: I believe the best and clearest way to do this would be a bitmask to hide everything except the last few digits. In your case, this would be printf("%X\n", num & 0xfff);:
0xfffffffb
0x00000fff
  -----|||
0x00000ffb

You can adapt this to work with higher bits too. So if you want to extract 0xadb from 0xdeadbeef, it would look like this:
(0xdeadbeef & 0xfff000) >> 12 // gives 0xadb

(0xdeadbeef & 0xfff000) will mask out the bits you want, leaving 0xadb000. To remove these zeroes, right shift by 12 (each hex digit can represent 4 bits, and we need to remove 3 digits, so 4*3 = 12).

A: How about:
void printLastThreeHex(int num)
{
    size_t len = 0;
    char tmp[sizeof(int)*2 + 1]; // two hex chars for each byte + null char
    char* str = tmp;

    sprintf(tmp, "%03x", num);
    len = strlen(tmp);
    if (len > 3)
    {
        str = tmp + len - 3;
    }

    printf("%s\n", str);
}


text:
Q: C# automatic property deserialization of JSON I need to deserialize some JavaScript object represented in JSON to an appropriate C# class. Given the nice features of automatic properties, I would prefer having them in these classes as opposed to just having fields. Unfortunately, the .NET serialization engine (at least, by default) totally ignores automatic properties on deserialization and only cares about the backing field, which is obviously not present in the JavaScript object.
Given that there's no standard way to name backing fields and to be honest I don't even want to bother with the "let's create a JavaScript object that looks like it had C# backing fields" approach as it sounds a bit dirty, the only way I could serialize JavaScript fields to C# auto-properties if I could force the serialization engine to somehow ignore the backing field and use the property directly. Unfortunately, I can't figure out how this is done or if this can be done at all. Any ideas would be appreciated.
EDIT: Here's an example:
Javascript:
function Cat()
{
    this.Name = "Whiskers";
    this.Breed = "Tabby";
}
var cat = new Cat();

This is then serialized to "{Name: 'Whiskers'}".
The C# class:
[Serializable()]
public class Cat
{
    public string Name { get; set; }
    public string Breed { get; set; }
}

And the deserialization code, that fails:
new DataContractJsonSerializer(typeof(Cat)).ReadObject(inputStream);

And it is apparent from the exception that it fails because it is looking for the backing field.
EDIT2: Here's the exception, if that helps (no inner exceptions):

System.Runtime.Serialization.SerializationException
"The data contract type 'Test.Cat'
  cannot be deserialized because the
  required data members
  '<Name>k__BackingField, <Breed>k__BackingField' were not
  found."

A: What's happening here is the deserializer is trying to guess the name of your backing fields.
You can solve this by adding explicit mappings (DataContract/DataMember attributes) like this:
[DataContract]
public class Cat
{
    [DataMember]
    public string Name { get; set; }

    [DataMember]
    public string Breed { get; set; }
}

A: baretta's answer solved the k__BackingField bloat for me. Just a tiny addendum that you can decorate this class to auto serialize into either XML or JSON in a similar way:
[Serializable, XmlRoot, DataContract]
public class Cat
{
  [XmlElement]
  [DataMember]
  public string Name { get; set; }
  [XmlElement]
  [DataMember]
  public string Breed { get; set; }
}

... and then use a DataContractJsonSerializer or XmlSerializer to prepare it for your endpoint.

A: You can do this with JavaScriptSerializer found in the System.Web.Script.Serialization namespace:
JavaScriptSerializer serializer = new JavaScriptSerializer();
Cat c = serializer.Deserialize<Cat>(jsonString);

I have POCO objects with automatic properties and this works just fine.
EDIT: I wrote about JSON Serializers in .NET which compares this serializer with DataContractJsonSerializer.

A: I'm assuming you are passing data via a web service.  If you are using the WebService class with the ScriptMethod attribute uncommented-out, the web service methods can read JSON natively.  They even use the same JavaScriptSerializer that was mentioned above.  If you are using WCF I'm a little more fuzzy on the logic.
But make sure your JSON object are returning data for EVERY property in your class.  In your error, there is mention of a Breed property that is not in your example.
Also, on the JavaScript side, do to the dynamic nature of JavaScript it is easy to add new properties to your objects.  This can sometimes lead to circular references.  You should remove any extra data that you might have added (just as you are sending data via the web method, then add it again once you are done).


text:
Q: Angular custom form element directive before ngSubmit validation? so suppose I have a form:
<form ng-submit="submitForm()">
    <custom-form-element><custom-form-element>
    <button name="submit">Submit<button>
<form>

Is there anyway to do something with the data the customFormElement is containing (assume it's some sort of custom field) in the link (or somewhere else, if appropriate?) part of the directive definition to validate / sanitize the data there before the form submission?
I don't want to do this in the submitForm() function because there could be multiple of this same element there.
EDIT: might be helpful to say that what I'm doing isn't validation per se, but more like...customFormElement modifies a specific property on scope. e.g.
$scope.customFormElementData = {};

Then right before submission it'll look like:
$scope.customFormElementData = {
    foo: 'bar',
    baz: 'quuz'
};

But what I want to do is in the case that:
$scope.customFormElementData = {
    foo: '',
    baz: ''
}

I want to omit both foo and bar.

A: Without getting into whether or not what you are trying to accomplish is the best approach, you can do what you have in mind by broadcasting events.
So in your SubmitForm() function:
$rootScope.$broadcast('aboutToSubmitForm');
$rootScope.$broadcast('submittingForm');

In the controller:
$scope.$on('submittingForm', function() { //form submittal logic here });

Then, in your directive's linking function:
$scope.$on('aboutToSubmitForm', function(){ //your pre form submission logic here });


text:
Q: Selecting an option and automatically selecting by default multi-options from another forms I'm very bad at explaining myself. So i'm going to set what i'm looking for by steps.

*

*First select what you want.

*In the background, when you select the additional options which for example is organize 1 bedroom and 1 bathroom to grab that and by default select it to the other forms. So when you insert know my price, it shows you the cost for weekly, biweekly, and monthly services.

I'm not sure what to look for since I myself can't even explain it directly. I Hope the example i gave helped you understand what i'm looking for?

.button {
    background-color: #4CAF50; /* Green */
    border: none;
    color: white;
    padding: 15px 32px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;
    margin: 4px 2px;
    cursor: pointer;
    width: 100%;
}
<fieldset>

    <legend>On going service</legend>
      <select >
      <option value="">Select day of the week</option>
      <option value="10">Monday</option>
      <option value="10">Tuesday</option>
      <option value="10">Wednesday</option>
       <option value="10">Thursday</option>
      <option value="10">Friday</option>
      </select>

      <select>
      <option value="">Organize a:</option>
      <option value="10">1 bedroom 1 bathroom home</option>
      <option value="20">2 bedroom 1 bathroom home</option>
      <option value="30">2 bedroom 2 bathroom home</option>
      </select>

     </fieldset>

      <fieldset>
    <legend>Biweekly</legend>
      <select >
      <option value="">Select day of the week</option>
      <option value="100">Monday</option>
      <option value="100">Tuesday</option>
      <option value="100">Wednesday</option>
       <option value="100">Thursday</option>
      <option value="100">Friday</option>
      </select>

      <select>
      <option value="">Organize a:</option>
      <option value="100">1 bedroom 1 bathroom home</option>
      <option value="200">2 bedroom 1 bathroom home</option>
      <option value="300">2 bedroom 2 bathroom home</option>
      </select>
      </fieldset>

      <fieldset>
    <legend>Monthly</legend>
      <select >
      <option value="">Select day of the week</option>
      <option value="1000">Monday</option>
      <option value="1000">Tuesday</option>
      <option value="1000">Wednesday</option>
       <option value="1000">Thursday</option>
      <option value="1000">Friday</option>
      </select>

      <select>
      <option value="">Organize a:</option>
      <option value="1000">1 bedroom 1 bathroom home</option>
      <option value="2000">2 bedroom 1 bathroom home</option>
      <option value="3000">2 bedroom 2 bathroom home</option>
      </select>
      </fieldset>

      <button class="button">Book weekly</button>
$PRICE

      <button class="button">Book biweekly</button>
$PRICE

      <button class="button">Book monthly</button>
$PRICE


text:
Q: Calculate all possible permutations/combinations, then check if the result is equal to a value Best way I can explain it is using an example:
You are visiting a shop with $2000, your goal is to have $0 at the end of your trip.
You do not know how many items are going to be available, nor how much they cost.
Say that there are currently 3 items costing $1000, $750, $500.
(The point is to calculate all possible solutions, not the most efficient one.)
You can spend $2000, this means:
You can buy the $1000 item 0, 1 or 2 times.
You can buy the $750 item 0, 1 or 2 times.
You can buy the $500 item 0, 1, 2, 3 or 4 times.

At the end I need to be able to have all solutions, in this case it will be
2*$1000
1*$1000 and 2*$500
2*$750 and 1*$500
4*$500

Side note: you can't have a duplicate solution (like this)
1*$1000 and 2*$500
2*$500 and 1*$1000

This is what I tried:
You first call this function using
 goalmoney = convert.ToInt32(goalMoneyTextBox.Text);
 totalmoney = Convert.ToInt32(totalMoneyTextBox.Text);
 int[] list = new int[usingListBox.Items.Count];
 Calculate(0, currentmoney, list);

The function:
    public void Calculate(int level, int money, int[] list)
    {
        string item = usingListBox.Items[level].ToString();
        int cost = ItemDict[item];
        for (int i = 0; i <= (totalmoney / cost); i++)
        {
            int[] templist = list;
            int tempmoney = money - (cost * i);
            templist[level] = i;
            if (tempmoney == goalmoney)
            {
                resultsFound++;
            }
            if (level < usingListBox.Items.Count - 1 && tempmoney != goalmoney) Calculate(level + 1, tempmoney, templist);
        }
    }

A: Your problem can be reduced to a well known mathematical problem labeled Frobenius equation which is closely related to the well known Coin problem. Suppose you have N items, where i-th item costs c[i] and you need to spent exactly S$. So you need to find all non negative integer solutions (or decide whether there are no solutions at all) of equation
c[1]*n[1] + c[2]*n[2] + ... + c[N]*n[N] = S

where all n[i] are unknown variables and each n[i] is the number of bought items of i-th type.
This equation can be solved in a various ways. The following function allSolutions (I suppose it can be additionally simplified) finds all solutions of a given equation:
public static List<int[]> allSolutions(int[] system, int total) {
    ArrayList<int[]> all = new ArrayList<>();
    int[] solution = new int[system.length];//initialized by zeros
    int pointer = system.length - 1, temp;
    out:
    while (true) {
        do { //the following loop can be optimized by calculation of remainder
            ++solution[pointer];
        } while ((temp = total(system, solution)) < total);

        if (temp == total && pointer != 0)
            all.add(solution.clone());
        do {
            if (pointer == 0) {
                if (temp == total) //not lose the last solution!
                    all.add(solution.clone());
                break out;
            }
            for (int i = pointer; i < system.length; ++i)
                solution[i] = 0;
            ++solution[--pointer];
        } while ((temp = total(system, solution)) > total);
        pointer = system.length - 1;
        if (temp == total)
            all.add(solution.clone());
    }
    return all;
}

public static int total(int[] system, int[] solution) {
    int total = 0;
    for (int i = 0; i < system.length; ++i)
        total += system[i] * solution[i];
    return total;
}

In the above code system is array of coefficients c[i] and total is S. There is an obvious restriction: system should have no any zero elements (this lead to infinite number of solutions). A slight modification of the above code avoids this restriction.

A: Assuming you have class Product which exposes a property called Price, this is a way to do it:
public List<List<Product>> GetAffordableCombinations(double availableMoney, List<Product> availableProducts)
{
    List<Product> sortedProducts = availableProducts.OrderByDescending(p => p.Price).ToList();

    //we have to cycle through the list multiple times while keeping track of the current
    //position in each subsequent cycle. we're using a list of integers to save these positions
    List<int> layerPointer = new List<int>();
    layerPointer.Add(0);

    int currentLayer = 0;

    List<List<Product>> affordableCombinations = new List<List<Product>>();
    List<Product> tempList = new List<Product>();

    //when we went through all product on the top layer, we're done
    while (layerPointer[0] < sortedProducts.Count)
    {
        //take the product in the current position on the current layer
        var currentProduct = sortedProducts[layerPointer[currentLayer]];
        var currentSum = tempList.Sum(p => p.Price);

        if ((currentSum + currentProduct.Price) <= availableMoney)
        {
            //if the sum doesn't exeed our maximum we add that prod to a temp list
            tempList.Add(currentProduct);
            //then we advance to the next layer
            currentLayer++;
            //if it doesn't exist, we create it and set the 'start product' on that layer
            //to the current product of the current layer
            if (currentLayer >= layerPointer.Count)
                layerPointer.Add(layerPointer[currentLayer - 1]);
        }
        else
        {
            //if the sum would exeed our maximum we move to the next prod on the current layer
            layerPointer[currentLayer]++;

            if (layerPointer[currentLayer] >= sortedProducts.Count)
            {
                //if we've reached the end of the list on the current layer,
                //there are no more cheaper products to add, and this cycle is complete
                //so we add the list we have so far to the possible combinations
                affordableCombinations.Add(tempList);
                tempList = new List<Product>();

                //move to the next product on the top layer
                layerPointer[0]++;
                currentLayer = 0;
                //set the current products on each subsequent layer to the current of the top layer
                for (int i = 1; i < layerPointer.Count; i++)
                {
                    layerPointer[i] = layerPointer[0];
                }
            }
        }
    }

    return affordableCombinations;
}


text:
Q: Method return type in build.gradle I have a method in build.gradle that basically creates an oracle database connection and returns it. But while running the script, it shows build failed as seen in the screenshot below.
def ext.getOracleConnection = { ->
            java.sql.Connection conn = null;
            try{
                configurations.jdbcdriver.files.each {
                    groovy.sql.Sql.classLoader.addURL(it.toURI().toURL())
                }
                configurations.xdb.files.each {
                    groovy.sql.Sql.classLoader.addURL(it.toURI().toURL())
                }
                //load the jdbc driver and create the connection.
                java.sql.DriverManager.registerDriver(groovy.sql.Sql.classLoader.loadClass("oracle.jdbc.OracleDriver").newInstance())
                readProperites();
                conn = java.sql.DriverManager.getConnection(db_url, dbUser, dbPassword);

            }
            catch(Exception e){
                e.printStackTrace();
            }
            return conn;
        }

I tried changing the return type to java.sql.Connection but it doesn't work. Can anyone suggest a solution?.

A: This is a compilation error as shown in the failure message.
You need to remove def from the declaration.


text:
Q: Need a Java reg Ex to read numbers in a string I've got a number of different string that look something like:

*

*1

*1,2

*1 2

*1 and 2

*1, 2 and 3

*1, 93

So thats:
- single numbers (potentially multiple digits)
- sequences seperated by 'and', commas or spaces
I'd like to write a Reg Ex to pull back just the numeric bits of the string. I had thought something like this would work:
Pattern.compile("^(?:(\\d+)[^\\d]+)*$");

The idea being that it should match and capture sequences of digits, skip multiple non-digits characters and repeat

A: Are you not just doing a match on digits here?:
    String str = "1, 2 and 3, 93";

    Matcher m = Pattern.compile("\\d+").matcher(str);
    while (m.find()) {
        System.out.println(m.group(0));
    }

A: why not match on "\d+"?
public class SO {

    public static void main(String[] args) {
        String s = "13, 23 and 33";
        Pattern p = Pattern.compile("(\\d+)");
        Matcher m =  p.matcher(s);
        List<Integer> result = new ArrayList<Integer>();
        while (m.find()) {
            result.add(new Integer(m.group()));
        }
        System.out.println(result);
    }
}

prints out
[13, 23, 33]


text:
Q: Using Biblatex with Bibtex: undefined references I  am using TexShop (version 3.92) on Mac to write a PhD thesis. I had been using BibDesk (Version 1.6.13) for my references using the following bibliography commands:
\usepackage{chicago}
\bibliographystyle{chicago}

\bibliography{references}

However, the intext citations had initials as well as surname, and no comma before the date. For example:

(Johnstone, L.R. 2016)

And I'd like to use APA style, so in text citations would appear like this:

Johnstone (2016) states that.... or Some text here (Johnstone, 2016)
  Some text here.

I looked at some previously answered questions on here and it appears that the use package biblatex should resolve the issue, however, the in text citations still include first initials and have no comma, but now the brackets are missing:

Some text here Johnstone, L.R. 2016 some text here.

I am using the following commands:
\documentclass[a4paper,12pt,twoside,openright]{report}

\usepackage[backend=bibtex, style=authoryear, sorting=ynt]{biblatex}
\addbibresource{references}

\begin{document}

\printbibliography

\end{document}

Sorry if this has a simple solution, I am not a LaTex expert. I have tried a few things that people have suggested on other threads and nothing has worked as yet.
Any help would be much appreciated.
Edit:
the bib file looks like:
@book{girginovparry2005,
  Address = {{Oxon, UK}},
  Author = {{Girginov, V., Parry, J.}},
  Date-Added = {2017-10-02 18:06:52 +0000},
  Date-Modified = {2017-10-02 18:06:52 +0000},
  Publisher = {{Routledge}},
  Title = {{The Olympic Games explained: A student guide to the evolution of the modern Olympic Games}},
  Year = {{2005}}}

A: You have several errors in your bib entry, for example do you not need to double the brackets and authors are divided by and, not a comma!
Please see the following complete MWE (with package filecontents I added the corrected bib entry and called style apa with biblatex and biber. Used article to get citings and bibliography on one page):
\RequirePackage{filecontents}
\begin{filecontents*}{\jobname.bib}
@book{girginovparry2005,
  Address = {Oxon, UK},
  Author = {Girginov, V. and Parry, J.},
  Date-Added = {2017-10-02 18:06:52 +0000},
  Date-Modified = {2017-10-02 18:06:52 +0000},
  Publisher = {Routledge},
  Title = {The Olympic Games explained: A student guide to the evolution of the modern Olympic Games},
  Year = {2005},
}
\end{filecontents*}

\documentclass[a4paper,12pt,twoside,openright]{article}

\usepackage[%
  backend=biber, % bibtex <=============================================
  style=apa, % authoryear <=============================================
  natbib, % <===========================================================
  sorting=ynt
]{biblatex}
\addbibresource{\jobname.bib} % ========================================

\begin{document}

text \cite{girginovparry2005}  text \citet{girginovparry2005}
text \citep{girginovparry2005} text \parencite{girginovparry2005}
\printbibliography

\end{document}

and the resulting pdf:


text:
Q: How can i copy tab seperated contents from txt file into Hashmaps? For example
FirstName LastName Balance
Bob     Blue        24.98
Steve   Green       345.98
Pam     White       0.00
Sue     Red         42.16

Scanner scanner = new Scanner(System.in);
Scanner input = new Scanner(System.in);
ArrayList < String > list = new ArrayList < String > ();
String data;
System.out.println("please enter the file path");
File myObj = new File(scanner.nextLine());
Scanner scan = new Scanner(myObj);
while (scan.hasNextLine()) {
    data = scan.nextLine();
    list.add(data);
}

I want the FirstName, LastName and Balance to be the keys and the rest contents to be the values.

A: I have made the code to answer your question and also I have slightly changed the format of the .txt file (Hence, Each value is separated by space (" ") both heading and also values). I have given below the two files and also provided the expected output. I hope this will help you to proceed. Please let me know if you have any queries on the answer.
FileReader.java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

public class FileReader {
        public static void main(final String[] args) throws FileNotFoundException {
                final Scanner sc = new Scanner(System.in);
                System.out.println("Please enter the file path");
                final String path = sc.next();
                File file = new File(path);
                Scanner fileScanner = new Scanner(file);
                String[] keys = fileScanner.nextLine().split(" ");
                List<String> firstNames = new ArrayList<>();
                List<String> lastNames = new ArrayList<>();
                List<String> balances = new ArrayList<>();
                while (fileScanner.hasNext()) {
                        String values[] = fileScanner.nextLine().split(" ");
                        firstNames.add(values[0]);
                        lastNames.add(values[1]);
                        balances.add(values[2]);
                }
                Map<String, List<String>> fileMap = new HashMap<>();
                fileMap.put(keys[0], firstNames);
                fileMap.put(keys[1], lastNames);
                fileMap.put(keys[2], balances);
                fileMap.entrySet().stream().forEach(e -> System.out.println(e));
                sc.close();
                fileScanner.close();
        }
}

TextFile.txt
FirstName LastName Balance
Bob Blue 24.98
Steve Green 345.98
Pam White 0.00
Sue Red 42.16

Expected output:
Please enter the file path
*\GitHub\playground\gvlab\src\TextFile.txt
FirstName=[Bob, Steve, Pam, Sue]
LastName=[Blue, Green, White, Red]
Balance=[24.98, 345.98, 0.00, 42.16]


text:
Q: Vista / Windows Server 2003 Mapped Drive Logon Failure I have a Windows Vista (Ultimate) machine which connects to a Windows Server 2003 machine for just one thing: a mapped network drive.
There is a user account on the Server machine which exactly matches the user name & password on the Vista machine.
The problem is... when I try to connect (map) the network drive, a message comes up saying the user name or password was incorrect! Since it then gives you the opportunity to re-enter the user name and password, I re-enter the password (exactly the same, again) and it works and the drive gets mapped.
BUT... the plot thickens! After a reboot (or, I suppose, a log-off and log-on), the network drive doesn't work anymore - double clicking it gives a short delay, and then a message saying the drive can't be reconnected because the account has been locked out. Sure enough, checking on the server shows the account locked out. A glance at the event log shows repeated "invalid password" events before the account is eventually locked out.
The specific events that are recorded are:

*

*A logon attempt by MICROSOFT_AUTHENTICATION_PACKAGE_V1_0, which fails with code 0xC0000234

*A "logon failure" event which says "unknown user name or bad password."

*

*The user name specified in the event is the user name I'm using

*The "logon type" is "3"

*The logon process is "NtLmSsp"

*The authentication package is NTLM

Both machines are using the same LAN manager authentication method (specifically, "Send LM & NTLM, use NTLMv2 session security if negotiated") - set via security policy.
The Vista machine is not part of the domain, but the user name and password match.
The Vista machine used to work just fine, back when it was an XP machine. But then, it got upgraded to Vista (not a clean re-install, an actual upgrade) and this is what happens now.
For the life of me, I cannot figure out why it seems to be sending the wrong password, when I have checked & double-checked to make sure the password is exactly the same. I've googled & googled and found nothing useful. I'm stumped!
Does anyone have any ideas as to what might be happening here - or ideas for further troubleshooting steps I can take?
UPDATE: I've tried mapping the drive via the command line and the NET USE command - but it throws up its hands as well, with a "system error 86" which says "the specified network password is not correct." Your guess is as good as mine as to what's really going on here. I wish I could sniff the actual traffic going back & forth between the computers and see what password (if any!!) is being sent...

A: i have had similar problems. it seems to be related to logging in to a different server with a different password. for instance, i had a user password for one share and a different one for another - both with the same login id. after i attached both of the shares, it would forever mess up logging into one of them. even after i no longer used one of them, the remaining one always prompted me to login. the solution that seemed to fix it for me was:

*

*removed all network mapped drives

*i remapped everything on the command line: net use z: \myserver\theshare /persistent:yes

after doing that, the drive map worked fine. windows seems to be saving authentication for old shares and gets confused.
-don

A: Have you tried a different username and password ?
Can you also please post the security log from the server / workstation. That would help in figuring out the issue.
Also check out this post on these type of errors:
http://  x-security.blogspot.com/2009/04/trobleshoot-user-account-lockout.  html

A: I had the same issue where the user is running Windows 2008 which was not attached to the domain (also happens on Vista I believe) and I was trying to map to a NAS (not a real server).
The fix was,
Go to Admin Tools >> Local Security Policy >> Local Policies >> Security Options >> Network security: LAN Manager authentication level --> change this value to Send LM & NTLM responses
I guess this is a less secure setting but it resolved the issue.
BTW... Also important to check the time on the workstation and server are within 5 minutes of each other.
-TamW

A: This last suggestion with the LM & NTLM responses setting worked for me. I was trying to access shares on a W2K pro from a Windows 7 pro. Same user names and passwords, no domain, just a workgroup. Without this setting, I was able to access remote shares just fine, then it just quit working and started asking for credentials, which no matter if they were correct, would refuse access. I think the setting must have been changed from a windows update.


text:
Q: ANGULAR: understanding how to await a response Thank you for taking the time to look at this. I've read through multiple questions on how to subscribe to a response but am struggling to frame it in the context of my program.
Here, I am asking Okta for the user data (simple enough). What follows is me mapping the results to an array, then assigning the username to the first value and the userGroups to the userGroups. However, as expected, Angular fires this code before the response comes in. The userClaims != null is a stopgap to prevent Angular errors.
My specific question: how do I structure this request with these variables?
async ngOnInit() {
this.isAuthenticated = await this.oktaAuth.isAuthenticated();
this.oktaAuth.$authenticationState.subscribe(
  (isAuthenticated: boolean)  => this.isAuthenticated = isAuthenticated
  );

const userClaims = await this.oktaAuth.getUser();

if (userClaims != null) {
this.claims = Object.entries(userClaims).map(entry => ({ claim: entry[0], value: entry[1] }));
this.userName = this.claims[1].value;
this.userGroups = userClaims.groups;

console.log('ADMIN COMPONENT: userName ' + this.userName + ' is a member of : ' + this.userGroups);
}}}

EDIT: Here is the promise
import { Router, NavigationExtras } from '@angular/router';
import { OktaConfig } from '../models/okta.config';
import { UserClaims } from '../models/user-claims';
import { Observable } from 'rxjs';
export declare class OktaAuthService {
    private auth;
    private router;
    private oktaAuth;
    private config;
    private observers;
    $authenticationState: Observable<boolean>;
    // $userState: Observable<boolean>;

    constructor(auth: OktaConfig, router: Router);
    /**
     * Checks if there is an access token and id token
     */
    isAuthenticated(): Promise<boolean>;
    private emitAuthenticationState;
    /**
     * Returns the current accessToken in the tokenManager.
     */
    getAccessToken(): Promise<string | undefined>;
    /**
     * Returns the current idToken in the tokenManager.
     */
    getIdToken(): Promise<string | undefined>;
    /**
     * Returns user claims from the /userinfo endpoint if an
     * accessToken is provided or parses the available idToken.
     */
    getUser(): Promise<UserClaims | undefined>;
    // private emitUserState;
    /**
     * Returns the configuration object used.
     */
    getOktaConfig(): OktaConfig;
    /**
     * Launches the login redirect.
     * @param fromUri
     * @param additionalParams
     */
    loginRedirect(fromUri?: string, additionalParams?: object): void;
    /**
     * Stores the intended path to redirect after successful login.
     * @param uri
     * @param queryParams
     */
    setFromUri(uri: string, queryParams?: object): void;
    /**
     * Returns the referrer path from localStorage or app root.
     */
    getFromUri(): {
        uri: string;
        extras: NavigationExtras;
    };
    /**
     * Parses the tokens from the callback URL.
     */
    handleAuthentication(): Promise<void>;
    /**
     * Clears the user session in Okta and removes
     * tokens stored in the tokenManager.
     * @param uri
     */
    logout(uri?: string): Promise<void>;
    /**
     * Scrub scopes to ensure 'openid' is included
     * @param scopes
     */
    scrubScopes(scopes: string): string;
}

A: I hope this helps a little.
Remember that async/await is syntactic sugar to work with promises, to make them clean and "easy".
I made a very simple example at https://stackblitz.com/edit/github-ijnmcd
Where I call The dancing clown 3 times, one with a promise, the other with async / await. With the example should be easy to implement your solution.
Remember to use try{}catch(e){} to catch errors with async/await.
Check this out: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
By the way, remember that HttpClient is an observable, this means you will have to subscribe to it, if you want to use async/await, you will need to use  toPromise() instead of the subscribe();
Hope it helps.


text:
Q: Dynamically adding to page model in form using Razor partial view I created a Razor page that allowed the user to dynamically add to the object model before submitting form but when I tried to convert to a partial view the objects were not being added to the page model. Shouldn't the same code work when just moved to a partial view?
This code works:

        <input type="submit" asp-page-handler="AddQuestion" class="btn btn-info" value="Add Question" />

            @for (var i = 0; i < Model.SurveyObject.Questions.Count; i++)
            {

Question ID# @Model.SurveyObject.Questions[i].QuestionId

                    @Html.LabelFor(x => Model.SurveyObject.Questions[i].QuestionId)
                    @Html.EditorFor(x => Model.SurveyObject.Questions[i].QuestionId)

                @Html.LabelFor(x => Model.SurveyObject.Questions[i].Question)
                @Html.EditorFor(x => Model.SurveyObject.Questions[i].Question)
            }

But when converted to a partial view it does not work:

        <input type="submit" asp-page-handler="AddQuestion" class="btn btn-info" value="Add Question" />

        @for (var i = 0; i < Model.SurveyObject.Questions.Count; i++)
        {
            @await Html.PartialAsync("_SurveyCreateQuestion", Model.SurveyObject.Questions[i]);
        }

Here are the supporting objects.
public class Survey
{
    public string SurveyName { get; set; }
    public List<SurveyQuestion> Questions { get; set; }
    public Survey()
    {
        this.SurveyName = "new survey name here";
        this.Questions = new List<SurveyQuestion>();
    }
}
public class SurveyQuestion
{
    public int QuestionId { get; set; }
    public string Question { get; set; }
    public List<SurveyResponse> ResponseList { get; set; }
    public SurveyQuestion() { }
    public SurveyQuestion(int id)
    {
        this.QuestionId = id;
        this.Question = "question text for id " + id;
        this.ResponseList = new List<SurveyResponse>();
    }
}
public class SurveyResponse
{
    public int ResponseId { get; set; }
    public string Response { get; set; }
    public SurveyQuestion NextQuestion { get; set; }
    public SurveyResponse() { }
    public SurveyResponse(int id)
    {
        this.ResponseId = id;
        this.Response = "response text for id " + id;
    }
}

And here is the cshml file.
public class SurveyCreateModel : PageModel
{
    [BindProperty]
    public Survey SurveyObject { get; set; }
    public void OnGet()
    {

    }
    public void OnPostAddQuestion()
    {
        this.SurveyObject.Questions.Add(new SurveyQuestion(this.SurveyObject.Questions.Count + 1));
    }
}

And the partial view.
@model SurveyCreateModel.SurveyQuestion
@if (Model == null)
{

}
else
{

Question ID# @Model.QuestionId

        @Html.LabelFor(x => Model.QuestionId)
        @Html.EditorFor(x => Model.QuestionId)

    @Html.LabelFor(x => Model.Question)
        @Html.EditorFor(x => Model.Question)
}

Looking at the source of the rendered HTML the loop without a partial view is creating unique elements as expected like these labels generated when the add question button is clicked twice.
QuestionId
QuestionId

But when the same code to generate the tags is moved into a partial view inside the same loop the html is rendered like this:
QuestionId

Screen print of partial view not working - keep pressing add question but always stays at first question - model not updating

Screen print of code working - press add question button twice and two questions added - model is updating

A: I was not able to get this to work with a partial view but it does work when using an editor template.
@model SurveyCreateModel.SurveyQuestion

Question ID# @Model.QuestionId

    @Html.LabelFor(x => Model.QuestionId)
    @Html.EditorFor(x => Model.QuestionId)

@Html.LabelFor(x => Model.Question)
@Html.EditorFor(x => Model.Question)

Then this code was simply referenced by this in the cshtml:

  @Html.EditorFor(x => x.SurveyObject.Questions)


text:
Q: Add AM/PM to datepicker? My UIDatePicker is set to UIDatePickerModeTime but on the apple documentation it says The date picker displays hours, minutes, and (optionally) an AM/PM designation. The exact items shown and their order depend upon the locale set. An example of this mode is [ 6 | 53 | PM ].. How do i add AM/PM because on my device, those aren't options and it instead uses a 24 hour clock?

A: Unfortunately UIDatePicker doesn't have an option for that; it always respects the device option of 12-hour or 24-hour time.
If you must have an AM/PM component you may have to go with a custom UIPickerView instead, and build an NSDate out of its components manually.

A: This will depend on the settings of the user. If you go to Settings -> General -> Date & Time. there is a "24-Hour" time switch, and based on that users will have the AM/PM indicator on your picker.

A: This thread is somewhat old, but maybe this will be useful to someone else...
As written in the original question, the picker will respect the locale. So, if you what to overrule the system-settings you can set the desired locale on the picker like this:
picker.locale = Locale.init(identifier: "en")

A: Two things to check,

*

*UIDatePicker has mode which needs to be either set to .time or .dateAndTime in order to support AM/PM format.

*set locale to a locale that supports AM/PM, eg "en_US_POSIX", if your locale is set to current, it will read system locale.


text:
Q: Can't trigger theme update from a third-party source via Updates API in WordPress I'm trying to update my theme via Updates API in WordPress and can't get it to work.
Here's the transient value:
(object) array(
    'last_checked' => 1675756430,
    'checked'      => array(
        'chipmunk-lite'  => '1.0',
        'chipmunk-theme' => '1.17.1',
    ),
    'response'     => array(
        'chipmunk-theme' => array(
            'theme'        => 'chipmunk-theme',
            'new_version'  => '1.18.0',
            'url'          => 'https://chipmunktheme.com',
            'package'      => 'https://app.lemonsqueezy.com/download/unique_id',
            'requires'     => NULL,
            'requires_php' => NULL,
            'sections'     => array(
                'description' => '
Makes it ridiculously easy to make a content curation website for marketing, authority or just for fun. No coding skills required.
',
                'changelog'   => '1.18.0',
            ),
        ),
    ),
    'no_update'    => array(),
    'translations' => array(),
)

The update alert does not show up. Is there anything wrong with it?
I'm following this guide: https://make.wordpress.org/core/2020/07/30/recommended-usage-of-the-updates-api-to-support-the-auto-updates-ui-for-plugins-and-themes-in-wordpress-5-5/


text:
Q: Is it possible to use multiple parameters in SonarQube search API? After some time spent scouring google and looking through the Sonar Qube API documentation, along with trying a few permutations on common patterns, I have arrived to the point where I am wondering if it is even possible to use multiple parameters when doing an issue search in SonarQube's API.
Purpose of search is to populate a team radiator with issue data from Sonarqube.  This data will be combined with build data from other sources (Or else I would just link to the SonarQube display page)
current configured URL to api is:
https://sonarqubesitehere.com/api/issues/search?=projectKeys=com.projectnamehere
(This is dummy code with names changed to protect the innocent)
I would like to be able to add a second parameter to this search that allows me to receive only major (or minor) issues that belong to the specific project I specify.      the search term for that search is /search?severities=MAJOR
Anyone wrangled with this particular problem?

A: Please check the WS API on sonarqube.com or your own instance like: https://your-sonarqube.com/web_api/api/issues/search.
Here's an example of api/issues/search with several parameters

A: Hummmm... Provided that you read the Web API documentation for /issues/search, and that you know how to correctly write a URL that uses parameters, then it's quite easy to find that the solution is the following:
https://<your_server>/api/issues/search?projectKeys=project1Key,project2Key&severities=MINOR,MAJOR

Live example on SonarQube.com: https://sonarqube.com/api/issues/search?projectKeys=clang,git&severities=BLOCKER


text:
Q: Animation with colormap in python I made a small program in Fortran to generate a matrix of rank n whose elements are random number between 0 and 9, with each iteration, change the matrix elements, I want to assign each color number and show an animation with map colors.
For example:
for t = 5    a[5 6]= 5 and 5 = "red"
for t = 9    a[5 6]= 7 and 7 = "blue"
some ideas? and in three dimension would be similar?
Thank you!


text:
Q: How can you change the text when the bot processes slash command? perhaps from the title, the question is not very well aware that I wanted to ask, so sorry at once. So, I saw in some bots how they changed the text while processing the team. Here's what text I mean:

There, instead of "Sending сommand" was "Bot Thinking…". I don't know if I may confuse it with something else or in discord.py. Therefore, I am interested in whether there is such opportunity in discord.py. If this is, I will be glad to read more about it.

A: yeah it is really easy
that is only in slash commands and views...
you should type
await interaction.response.defer(thinking=True)

that is used mainly if there is a certain command will take time to possess
and u should follow up to send a message
await interaction.followup.send("whatever")


text:
Q: A Man With a Stainless Steel Endoskeleton (like The Terminator) Fighting Cloaked Aliens Only He Can See The story was published in the mid 1960s, around 1967-68 in Analog or The Magazine of Fantasy & Science Fiction.  I delivered both subscriptions to a young guy in Belfast when I was a paper boy and he would pass me his read copies when I delivered the new ones.
The character is bio-engineered, a bit like the Terminator, but with normal sentient self awareness, working as a kind of vigilante detective who can, because of extremely advanced biologically engineered senses, see the otherwise cloaked 'normal' aliens and kills them by whatever means possible.
Like the story Eight O'Clock in the Morning by Ray Nelson, first published in the November 1963 issue of The Magazine of Fantasy & Science Fiction. Which was later made into a film in 1988, They Live, by John Carpenter. He also has narrow escapes, when he crushes one against a wall with a car when he's ambushed.
He also escapes from them when he's trapped on a ship and has to swim a mile under water (with a stainless steel endoskeleton - go figure) to escape them. I thought it was The Stainless Steel Rat by Harry Harrison but apparently not...

A: This is A Plague of Demons' by Keith Laumer
From fantasy literature review.....
http://www.fantasyliterature.com/reviews/a-plague-of-demons/

A Plague of Demons is narrated by John Bravais, an agent who is asked to come to Algeria to meet his old friend Felix Severance, of the CBI (a combination of the CIA and FBI, we can only infer).
Bravais learns that for many years, war combatants around the world have been going missing, seemingly vanishing from their fields of battle. Severance asks him to investigate, and it is not long before Bravais witnesses, during a campaign between Moroccan and Algerian troops, just what has been going on: Seven-foot-tall, skull-faced, occasionally bipedal aliens, vaguely canine in appearance, have been surreptitiously killing soldiers on Terran battlefields, slicing out their brains and storing them in vitro for some reason unknown!
For the next 2/3 of Laumer's book, the aliens, and their human cat's-paws, chase Bravais from Algeria to Jacksonville, Florida, and then on to Coffeyville, Kansas and to Chicago; a nightmarish pursuit that Bravais survives only because of the PAPA (Power Assisted Personal Armament) modifications that Severance had made on his body, turning him into a superwarrior of sorts.
But matters grow even more nightmarish for Bravais in the book's final 1/3, in which he is captured by the aliens, has his own gray matter removed, and awakens on an alien moon in the midst of a battle, his brain being used to power and control a 70-foot-high, massive supertank, in concert with other tanks being propelled by the minds of Earth soldiers from many nations, some from as far back as 1,000 years ago


text:
Q: difference between two result counters in google api result for a given query, google custom search api returns a json which in addition to the top N results contains the following
u'searchInformation': {u'formattedSearchTime': u'0.34',
                       u'formattedTotalResults': u'402',
                       u'searchTime': 0.335969,
                       u'totalResults': u'402'},

Can somebody explain what is the difference between formattedTotalResults and totalResults?
As per my understanding, they don't account for featured ad links within the results and are always same. But I want to confirm if that's the case.

A: The difference is how its formatted.   The first one is a numeric value the second is a string value, with formatted added.

*

*searchInformation.totalResults long The total number of search results returned by the query.

*searchInformation.formattedTotalResults string The total number of search results, formatted according to locale style.

The first one would return 1001 the second one would return 1,001 if you are in the USA and 1.001 if you where in Europe. This is because decimal and thousand separators are different in different countries around the world.
Custom-search documentation can be found here:  CSE: list


text:
Q: Microphone being recognized as headphones in windows 10 using a usb-c I plugged the 3.5mm jack into a USB-c adapter, and into the PC.
It is recognized as headphones, while my internal mic is recognized as the mic. How can I switch it so the plugged USB-c is recognized as the mic instead of headphones?

Here is what I have tried:
1- Updated the Lenovo ThinkPad p52 from the manufacturer's website with auto-scan to the latest all

2- I have the latest windows update

3- Disabled fast startup

4- uninstalled and reinstalled everything under "sound,video and game controllers" and "audio..."

5- unplugged the 3.5mm jack mic from usb-c adapter and plugged to a splitter, and straight into the 3.5mm of the PC. Nothing changes, PC speaker becomes the PC, and internal mic stays as the mic.

6- Installed r2.81  which causes the following error when after I restart the PC. So I uninstall 2.81 and install r2.82 instead.

7 - Installed r 2.82 - back to square one. Here is what the Realtek folder looks like

8- This should have been the input device, but detected as output device

Some other screenshots

The only time it worked is when I plug the microphone jac into the HP Elite docking station jack, and then the USB-c of the docking station into the Lenovo usb-c. Then it recognizes it as a microphone.
In the below image, the far right is the microphone, and the middle is the splitter and the far left is the usb-c adapter. I was trying these 2 different methods since I thought jack might be broken on the laptop.

How can I use the USB-C adapter or the lenovo built-in headset with the splitter to let the PC recognize its a microphone and not a headphone?

A: Solution
Use your audio splitter, and connect both the mic AND some headphones to it. Connecting only the mic will never work.
Why? Your audio interface is not suicidal.
(On some older hardware, or when using a Mac, you might still get some strange audio effects caused by basic hardware incompatibility issues. I won't go into this.)

Explanation
This is all about electric circuitry. It can't be resolved by software. Jack connectors are 'dumb', and there's no possible way your mic can tell your PC "I'm a microphone".
3.5mm Jack connectors come in two basic flavours: four-pin and three-pin, as on the below image.
(OMTP four-pin connectors have mic and ground inverted in respect to CTIA. Some old phones use OMTP)

A four-pin jack plug, as on your PC and USB-Adaptor, for obvious reasons needs to be able to handle BOTH CTIA-Headsets as well as normal Headphones. It can't handle just a microphone, though.
Headphones as well as Mics are electric circuits, with the current flowing from left/right/mic connector to the grounds connector.
As you can deduct from the image, a normal headphone connector will bridge pin 3 & 4 with its ground connector. If the mic pin would be active while you plug-in a headphone, this would cause a short circuit between pin 3 & 4, immediately frying your audio device and probably taking down your whole machine.
For this reason, for the mic pin to be activated, two conditions must be met:

*

*Current flowing from both left(1) & right(2) to ground(3)

*NO Current flowing from  neither left(1) nor right(2) to mic(4)

Condition 2 is not sufficient: a defective headphone could still fry out the device.
Once both conditions are met, the mic pin is activated, and your device driver will tell Windows your OS that there's a microphone connected. But there's no way your device will activate only the mic pin, while left & right pins are inactive: your device is not suicidal.
So, if you just plug in your mic, your device will tell the OS to register a headphone, as there's no way to tell the difference between a headphones and a mic connector.
And if you use the audio splitter but only connect the mic, your device will still say it's a (defective) headphone, as it detects a connector plugged in, but condition 1 is not met: you need to plugin a headphones, too, so your device will detect that the left & right circuits are closed.


text:
Q: NULL pointer protection with ARM Cortex-M MPU The MPU in ARM Cortex-M (M0+/M3/M4/M7/etc.) is often advertised as allowing to set up protection against dereferencing the NULL pointer. But how to do this in practice? (Some online discussions, like in the Zephyr Project, indicate that the issue is not quite trivial.)
I'm looking for the simplest possible MPU code running in "Privileged mode" on bare-metal ARM Cortex-M. Please note that "protection against dereferencing the NULL pointer" means to me protection both against reads and writes. Also, it is not just about the address 0x0, but small offsets from it as well. For example, accessing a struct member via a NULL pointer should also cause MPU exception:
struct foo {
    . . .
    uint8_t x;
};
. . .
uint8_t x = (*(struct foo volatile *)NULL)->x; // should fail!

A: After some experimentation, I've come up with the MPU setting that seems to work for most ARM Cortex-M MCUs. Here is the code (using the CMSIS):
/* Configure the MPU to prevent NULL-pointer dereferencing ... */
MPU->RBAR = 0x0U                          /* base address (NULL) */
            | MPU_RBAR_VALID_Msk          /* valid region */
            | (MPU_RBAR_REGION_Msk & 7U); /* region #7 */
MPU->RASR = (7U << MPU_RASR_SIZE_Pos)     /* 2^(7+1) region, see NOTE0 */
            | (0x0U << MPU_RASR_AP_Pos)   /* no-access region */
            | MPU_RASR_ENABLE_Msk;        /* region enable */

MPU->CTRL = MPU_CTRL_PRIVDEFENA_Msk       /* enable background region */
            | MPU_CTRL_ENABLE_Msk;        /* enable the MPU */
__ISB();
__DSB();

This code sets up a no-access MPU region #7 around the address 0x0 (any other MPU region will do as well). This works even for the MCUs, where the Vector Table also resides at address 0x0. Apparently, the MPU does not check access to the region by instructions other than LDR/STR, such as reading the vector address during Cortex-M exception entry.
However, in case the Vector Table resides at 0, the size of the no-access region must not contain any data that the CPU would legitimately read with the LDR instruction. This means that the size of the no-access region should be about the size of the Vector Table. In the code above, the size is set to 2^(7+1)==256 bytes, which should be fine even for relatively small vector tables.
The code above works also for MCUs that automatically relocate the Vector Table, such as STM32. For these MCUs, the size of the no-access region can be increased all the way to the relocated Vector Table, like 0x0800'0000 in the case of STM32. (You could set the size to 2^(26+1)==0x0800'0000).
Protection against NULL-pointer dereferencing is an important tool for improving the system's robustness and even for preventing malicious attacks. I hope that this answer will help fellow embedded developers.


text:
Q: Create Great Parser - Extract Relevant Text From HTML/Blogs I'm trying to create a generalized HTML parser that works well on Blog Posts. I want to point my parser at the specific entrie's URL and get back clean text of the post itself. My basic approach (from python) has been to use a combination of BeautifulSoup / Urllib2, which is okay, but it assumes you know the proper tags for the blog entry. Does anyone have any better ideas?
Here are some thoughts maybe someone could expand upon, that I don't have enough knowledge/know-how yet to implement.

*

*The unix program 'lynx' seems to parse blog posts especially well - what parser do they use, or how could this be utilized?

*Are there any services/parsers that automatically remove junk ads, etc?

*In this case, i had a vague notion that it may be an okay assumption that blog posts  are usually contained in a certain defining tag with class="entry" or something similar. Thus, it may be possible to create an algorithm that found the enclosing tags with the most clean text between them - any ideas on this?
Thanks!

A: There are projects out there that specifically look at filtering out the 'noise' of a given page. Typically the way this is done is by giving the algorithm a few examples of a given type of page, and it can look at what parts don't change between them. That being said, you'd have to give the algorithm a few example pages/posts of every blog you wanted to parse. This usually works well when you have a small defined set of sites you'll be crawling (news sites, for instance). The algorithm is basically detecting the template they use in HTML and picking out the interesting part. There's no magic here, it's tough and imperfect.
A great example of this alogrithm can be found in the EveryBlock.com source code which was just open-sourced. Go to everyblock.com/code and download the "ebdata" package and look at the "templatemaker" module.
And I don't mean to state the obvious, but have you considered just using RSS from the blogs in question? Usually the fields have the entire blog post, title, and other meta info along with them. Using RSS is going to be far simpler than the previous solution I mentioned.

A: Boy, do I have the perfect solution for you.
Arc90's readability algorithm does exactly this. Given HTML content, it picks out the content of the main blog post text, ignoring headers, footers, navigation, etc.
Here are implementations in:

*

*JavaScript

*Perl

*PHP

*Python

*Ruby

*C#
I'll be releasing a Perl port to CPAN in a couple of days. Done.
Hope this helps!


text:
Q: Any ETL/modeling tool to create a ROLAP star schema data warehouse? I was wondering if there's any software/tool out there which allows one to design/model a cube and have the software generate the code (at least the framework) necessary for updating dimensions and facts in a relational database?
Sorry if this is a dumb question. But, we have tools like Cognos TM1 which I can design a cube and associated ETL processes to bring data in and store in the TM1 cubes. However, I'm looking for something similar to store/maintain the data in the ROLAP star schema database.
Thanks!

A: You can use the Turbo Integrator to maintain the cube/dimension structure. See http://www.bedrocktm1.org/ for some help regarding loading and extracting data with TI processes and chores.
I haved used Cubeware Importer and SSIS as ETL tool in the past to load and save the parent child of TM1 projects. Everything from and to relational databases/SAP BW/flatfiles will work to store dimension tables and cube meta data.


text:
Q: Chronicle queue writes moveToIndex log on each empty read Chronicle queue writes moveToIndex log on each call on excerptTailer.readDocument(message) after a rollcycle reaches.
This log comes only when there is no messages available in the queue.
Is it an expected behavior? does it make any problem if the appender got idle  for long time ?
I have a case that the reader stops reading messages and return false even the appender still writes messages to the queue. But I'm unable to find out the scenario. That's why I doubted the log.
Log follows,
16:52:19.783 [Chronicle Reader] DEBUG n.o.c.q.i.s.SingleChronicleQueueExcerpts$StoreTailer - moveToIndex: 17ec5f2 3
16:52:20.784 [Chronicle Reader] DEBUG n.o.c.q.i.s.SingleChronicleQueueExcerpts$StoreTailer - moveToIndex: 17ec5f2 3
16:52:21.785 [Chronicle Reader] DEBUG n.o.c.q.i.s.SingleChronicleQueueExcerpts$StoreTailer - moveToIndex: 17ec5f2 3
16:52:22.785 [Chronicle Reader] DEBUG n.o.c.q.i.s.SingleChronicleQueueExcerpts$StoreTailer - moveToIndex: 17ec5f2 3
16:52:23.786 [Chronicle Reader] DEBUG n.o.c.q.i.s.SingleChronicleQueueExcerpts$StoreTailer - moveToIndex: 17ec5f2 3
16:52:24.787 [Chronicle Reader] DEBUG n.o.c.q.i.s.SingleChronicleQueueExcerpts$StoreTailer - moveToIndex: 17ec5f2 3
16:52:25.787 [Chronicle Reader] DEBUG n.o.c.q.i.s.SingleChronicleQueueExcerpts$StoreTailer - moveToIndex: 17ec5f2 3
16:52:26.788 [Chronicle Reader] DEBUG n.o.c.q.i.s.SingleChronicleQueueExcerpts$StoreTailer - moveToIndex: 17ec5f2 3

My Chronicle-Queue version: 4.5.27


text:
Q: Overwrite the this value in array.prototype I've found that the native js sort function screws up from time to time so I wanted to implement my own. Lets say i have the following :
Array.prototype.customSort = function(sortFunction, updated) {...}
var array = [5, 2, 3, 6]
array.customSort(function(a,b) {return a - b})
console.log(array)

Array should be [2, 3, 5, 6]
Updated is the array that has been sorted.
No matter what I return in customSort, the order of array is still in the original order. How do I overwrite the 'this' value / get it to point to the array with the correct order?

A: If you consider the actual code you gave above, you have to make sure that your customSort function updates this.
One case is that customSort only uses this as "read-only" input, that is - only puts the sorted array in updated, rather than changing this.
In such case, considering the code above (which you might have performed tests with), no updated parameter is sent to the function, to receive the sorted values.
Another case is that customSort returns the sorted array, in which case you have to collect it:
array = array.customSort(function(a,b) {return a - b});
console.log(array);

A: I just ended up iterating over the updated array and replacing each value in this with the value in updated. In code, that looks like...
function customSort(cb) {
    ...//updated is the sorted array that has been built
    var that = this;
    _.each(updated, function (ele, index) {
        that[index] = ele;
    })
}

I wanted the function to operate in the exact same way the native array.sort function does - it overwrites the array provided instead of returning a new, sorted array.
I find it odd that this works... you cannot overwrite the entire this value in one clean sweep but you can in steps. I couldn't do this for in the customSort function :
this = updated;


text:
Q: alterar a distancia entre a barra e o eixo Y no r Como posso alterar a distancia das barras em relaçao ao eixo y usando o ggplot?
utilizando o código:
k <- c("a","b","c","d","e","f")
j <- c(3,5,8,1,2,6)

df <- data.frame(k,j)

ggplot(df, aes(y=reorder(k, -j), x=j))+
  geom_col(fill="#70A2E7",  width = 0.85)+
  theme_bw(10)

grafico

A: A opção expand das scales existe para isso. Pode ser usada com a função expansion para maior controle:
library(ggplot2)

p <- ggplot(df, aes(j, reorder(k, -j))) +
  geom_col(fill="#70A2E7", width = 0.85) +
  theme_bw(10)

# Distância aditiva (adiciona espaço na mesma escala dos dados plotados)
p + scale_x_continuous(expand = expansion(add = c(0, 0.5)))

# Distância multiplicativa (adiciona espaço proporcional, p.e. 0.1 para 10%)
p + scale_x_continuous(expand = expansion(mult = c(0.1, 0.2)))


text:
Q: Ping and Install applications for multiple PCs I hope someone can help me with the following script:
The script I built works for 1 computer.  It asks the user to enter the computer name, and It will check if the computer is ONLINE, if it is it will copy and install the application.
Now, I want to add another functionality.  I want users to create a TXT file with all the computer names (line by line) and save them somewhere in the computer.  The user will run the script, and a Windows Explorer would open requesting the location of the TXT file.  So, the script will collect that data (I might be wrong, but should I use arrays for that?)  From there, I am assuming a ForEach statement should do it right?
The most difficult (for me) part is... if the computer is OFFLINE, it will skip that computer, and go for the next one... when it reaches the end of the lines, it should go back to the first line and check if the computer (that was offline) is online.  The tricky part is... if the computer already has the app installed, it should skip it, and continue to keep pinging computers and so on.  I want the script to run until someone manually stops it, installed the app to all the pcs, or runs for 3 days.
This might be too much to ask, but... it would also be nice to see a report of all the computers where the app was successfully installed (I am sure this should be on the ForEACH portion).
Thank you all
function HarvesterMenu {

$PCName = read-host -Prompt "Enter the computer name"
$PCName = $PCName -replace '(^\s+|\s+$)','' -replace '\s+',' '
$pingPC = Test-Connection -ComputerName $PCName -Quiet -Count 1 -ErrorAction SilentlyContinue

if ($pingPC -eq $True) {
    Write-host "ONLINE"
    harvesterInstall($PCName)
}
else {
    Write-host "OFFLINE"
}
}

function HarvesterInstall($InstallOnPC) {

    $Sourcefile = "\\SERVER1\discovery03$\HarvesterRemote.msi"
    Copy-Item -Path $Sourcefile -Destination "\\$InstallOnPC\c$\windows\temp\HarvesterRemote.msi"
    Invoke-Command -ComputerName $InstallOnPC -ScriptBlock {
        Start-Process c:\windows\temp\HarvesterRemote.msi -ArgumentList "/quiet" -Wait
    }
    Start-Sleep 3

    $InstCompleted = Test-Path -Path '\\$InstallOnPC\C$\Program Files (x86)\Labs\Harvester Remote\Harvester\Harvester.exe'

    Write-Host $InstCompleted
    if ($InstCompleted -eq $True) {
        Write-host "Harvester was successfuly installed on $InstallOnPC"
    }
    else {
        Write-host "Something went wrong.  Ping the server and try again"
    }

    $BacktoMenu = read-host -Prompt "Press Y to go back to the Main Menu or N to exist"
    if ($backtoMenu -eq "y") {
        harvesterMenu
    }
    else {
        Exit
    }
}

HarvesterMenu

A: You can do that easily with a Foreach-Loop.
U need a File with the pc's u wanna install the application. maybe .txt or .csv
Then u can just address it in a foreach.
something like that:
$InputFile = 'C:\Temp\lIST.csv'
$addresses = get-content $InputFile
        foreach($address in $addresses) {
                if (test-Connection -ComputerName $address -Count 1 -Quiet ) {
                    write-Host "$address Online"

                    #ur harvesterinstall

                    }
                    else
                    {
                    Write-Warning "$address Offline"

                    }
        }


text:
Q: How do I dispose inner producers in ReactiveCocoa? Let's say I have parallel work I want to do, such as downloading multiple images. Each of these downloads is represented by a SignalProducer. I create them and flatten them using the Merge strategy. When I start the outer producer and get a disposable I expected that disposing of that would also dispose of the inner producers. What actually happens is that after disposal, my outer producer stops receiving events, but the actual work being done by the inner producers continues, because they have not been disposed.
How do I get the actual work being done by the inner producers to stop? Here's some test code that illustrates the scenario:
func producerOfValues(values: [String]) -> SignalProducer<String, NoError> {
    return SignalProducer<String, NoError> {observer, disposable in
        for value in values {
            sleep(1)
            print("doing work: \(value)")
            sendNext(observer, value)
            if disposable.disposed { // 'disposed' is never true
                print("producer disposed")
                break
            }
        }
        sendCompleted(observer)
    }
}

let (signal, sink) = SignalProducer<SignalProducer<String, NoError>, NoError>.buffer(2)
let flattened = signal.flatten(.Merge)

let letterProducer = producerOfValues(["a", "b", "c"])
let numberProducer = producerOfValues(["1", "2", "3"])

sendNext(sink, letterProducer.startOn(QueueScheduler()))
sendNext(sink, numberProducer.startOn(QueueScheduler()))
sendCompleted(sink)

let disposable = flattened.startWithNext {
    print($0)
}
disposable.dispose()

Output:
doing work: a
doing work: 1
doing work: b
doing work: 2
doing work: c
doing work: 3


text:
Q: What "gotchas" should I be aware of when using Resharper to generate the IEquatable interface? I've generated the following code using Resharper.  I'm wondering if its good as it is, or if there are problems I need to fix/be aware of.
I'm wondering about the comparison for m_customTRP.  m_customTRP is an IList, the TimeRfPower also implements IEquatable.  So will the following line....
Equals(m_customTRP, other.m_customTRP)

...compare each TimeRfPower using the TimeRfPower class's Equals() method?
    //*********************************************************************
    // IEquatable Interface - implemented with Resharper
    //*********************************************************************
    protected bool Equals(Waveform other)
    {
        return base.Equals(other) && m_sweepSpan.Equals(other.m_sweepSpan)
            && m_sweepRate.Equals(other.m_sweepRate)
            && m_bandwidth.Equals(other.m_bandwidth)
            && m_centerFrequency.Equals(other.m_centerFrequency)
            && m_waveformType == other.m_waveformType
            && m_dutyCycle.Equals(other.m_dutyCycle)
            && m_pulsePeriod.Equals(other.m_pulsePeriod)
            && m_modulationFrequency.Equals(other.m_modulationFrequency)
            && m_relativePowerIncrement.Equals(other.m_relativePowerIncrement)
            && m_relativeTimeIncrement.Equals(other.m_relativeTimeIncrement)
            && m_endRelativePower.Equals(other.m_endRelativePower)
            && m_timeRFOn.Equals(other.m_timeRFOn)
            && m_timeRFOff.Equals(other.m_timeRFOff)
            && m_powerReferenceType == other.m_powerReferenceType
            && Equals(m_customTRP, other.m_customTRP);
    }

    //*********************************************************************
    // IEquatable Interface - implemented with Resharper
    //*********************************************************************
    public override bool Equals(object obj)
    {
        if (ReferenceEquals(null, obj)) return false;
        if (ReferenceEquals(this, obj)) return true;
        if (obj.GetType() != this.GetType()) return false;
        return Equals((Waveform)obj);
    }

    //*********************************************************************
    // IEquatable Interface - implemented with Resharper
    //*********************************************************************
    public override int GetHashCode()
    {
        unchecked
        {
            int hashCode = base.GetHashCode();
            hashCode = (hashCode * 397) ^ m_sweepSpan.GetHashCode();
            hashCode = (hashCode * 397) ^ m_sweepRate.GetHashCode();
            hashCode = (hashCode * 397) ^ m_bandwidth.GetHashCode();
            hashCode = (hashCode * 397) ^ m_centerFrequency.GetHashCode();
            hashCode = (hashCode * 397) ^ (int)m_waveformType;
            hashCode = (hashCode * 397) ^ m_dutyCycle.GetHashCode();
            hashCode = (hashCode * 397) ^ m_pulsePeriod.GetHashCode();
            hashCode = (hashCode * 397) ^ m_modulationFrequency.GetHashCode();
            hashCode = (hashCode * 397) ^ m_relativePowerIncrement.GetHashCode();
            hashCode = (hashCode * 397) ^ m_relativeTimeIncrement.GetHashCode();
            hashCode = (hashCode * 397) ^ m_endRelativePower.GetHashCode();
            hashCode = (hashCode * 397) ^ m_timeRFOn.GetHashCode();
            hashCode = (hashCode * 397) ^ m_timeRFOff.GetHashCode();
            hashCode = (hashCode * 397) ^ (int)m_powerReferenceType;
            hashCode = (hashCode * 397) ^ (m_customTRP != null ? m_customTRP.GetHashCode() : 0);

            return hashCode;
        }
    }


text:
Q: Usage and Benefits of Last Activity Storage - Session Management I have been seeing examples and documentations of various frameworks about last activity storage into database instead of session arrays (temporarily). After researching on various websites, blogs and tuts site what I learned a single common approach on why to keep track of last activity is that we can inspect when the user last logged out/in.
==========
Questions
a. What would be those major reasons and benefits for storing user's last activity?
b. What are the advantages and disadvantages of storing user's last activity into database instead of storing them into temporary session arrays?
c. What are those best strategies you use for security purposes by using user's last activity?
d. Is there any way better than last activity storage for keeping track of users and for enhancing web application security?

A: а) It depends on the needs of the application you are building. For some scenarios it is irrelevant, and for some it is important (when was the last time a customer logged in in your e-commerce store?)
b) storage in DB - global access to the session activity, meaning you can display that to all/other users than the one that is currently logged in. Storing in DB means larger database space so you will need trashing mechanism (Codeigniter does this automatically I believe)
c) If you store the session onto the server, it depends on the security of the server, and if you store it in the database, it depends on the security level of the database. In any case, the cookie containing the session key should be random, long string (handled by Codeigniter as well). Personally, I have used both approaches, depending on the needs of th application.
d) Again this depends on the scenario. For example, if you see that the user has not logged in for more than a year, and there are 5 consecutive unsuccessful attempts to log in, it probably means that he has forgotten his password, so you should send him an email containing a reset link or a warning that there were attempts for logging in.


text:
Q: AngularJS - Ordering and Parsing data in a ng-repeat, based on a parent ng-repeat Im trying to write a fairly complex ng-repeat that potentially uses filtering and parseing.
What i am first doing is ng-repeating a table heading of 12 months from the current month.
I am then displaying two rows - Searches with impact and Searches with NO impact
What i am trying to do is loop through my JSON file that contains my search data, and counts how many Searches with Impact and Search with No Impact, have been carried out for that particular month based on the SearchedOn field.
The logic behind understanding Searches with Impact and Search with No Impact is based on the IsIncludedInSearchImpactCalculation field being true or false.
What also needs to happen is that if my JSON file contains element of data that is greater than 12months old (based on the SearchedOn field), then this should be not included in the calculation.
HTML:

                    {{currMonth}}

                    Searches with impact

                    3

                    1
                    1

                    3
                    1

                    1

                    Searches with NO impact
                    2

                    1

Searches with impact:

{{searchedOn.SearchedOn}}

Searches with NO impact:

{{searchedOn.SearchedOn}}

JS:
angular.module('test', []).controller('Ctrl', function ($scope) {
    var date = new Date();
    var months = [],
        monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
            "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
    for (var i = 0; i < 12; i++) {
        months.push(monthNames[date.getMonth()] + ' ' + date.getFullYear());

        // Subtract a month each time
        date.setMonth(date.getMonth() - 1);
    }
    $scope.months = months;

    $scope.Searches = [{
        "SearchedOn": "19/04/2014",
            "IsIncludedInSearchImpactCalculation": true
    }, {
        "SearchedOn": "18/04/2014",
            "IsIncludedInSearchImpactCalculation": true
    }, {
        "SearchedOn": "01/05/2014",
            "IsIncludedInSearchImpactCalculation": false
    }, {
        "SearchedOn": "21/05/2014",
            "IsIncludedInSearchImpactCalculation": false
    }, {
        "SearchedOn": "20/07/2013",
            "IsIncludedInSearchImpactCalculation": true
    }, {
        "SearchedOn": "07/01/2014",
            "IsIncludedInSearchImpactCalculation": true
    }, {
        "SearchedOn": "08/12/2013",
            "IsIncludedInSearchImpactCalculation": false
    }, {
        "SearchedOn": "24/02/2014",
            "IsIncludedInSearchImpactCalculation": true
    }, {
        "SearchedOn": "30/06/2013",
            "IsIncludedInSearchImpactCalculation": true
    }, {
        "SearchedOn": "28/06/2014",
            "IsIncludedInSearchImpactCalculation": true
    }, {
        "SearchedOn": "14/08/2013",
            "IsIncludedInSearchImpactCalculation": true
    }, {
        "SearchedOn": "11/04/2014",
            "IsIncludedInSearchImpactCalculation": true
    }, {
        "SearchedOn": "13/08/2013",
            "IsIncludedInSearchImpactCalculation": true
    }, {
        "SearchedOn": "03/08/2013",
            "IsIncludedInSearchImpactCalculation": true
    }, {
        "SearchedOn": "20/01/2011",
            "IsIncludedInSearchImpactCalculation": true
    }];
});

Here's my fiddle: http://jsfiddle.net/oampz/j9LBe/
In my fiddle, i have manually hard coded what the table should look like based on the lists.

UPDATE:
Adding:

                Filtered list has {{filtered.length}} items

Gets me the total number of items in a row for Searches with impact or Searches with NO impact see fiddle: http://jsfiddle.net/oampz/j9LBe/1/
Now all that is needed is to group by month based on the previous ng-repeat:
 {{currMonth}}

A: Try this out
script
Working Demo
var months = [],
        monthNames = [{ monthNo: 1, monthName: "Jan" },
                      { monthNo: 2, monthName: "Feb" },
                      { monthNo: 3, monthName: "Mar" },
                      { monthNo: 4, monthName: "Apr" },
                      { monthNo: 5, monthName: "May" },
                      { monthNo: 6, monthName: "Jun" },
                      { monthNo: 7, monthName: "Jul" },
                      { monthNo: 8, monthName: "Aug" },
                      { monthNo: 9, monthName: "Sep" },
                      { monthNo: 10, monthName: "Oct" },
                      { monthNo: 11, monthName: "Nov" },
                      { monthNo: 12, monthName: "Dec" }];

    for (var i = 0; i < 12; i++) {
        var obj = {};
        obj.month = monthNames[date.getMonth()];
        obj.year = date.getFullYear();
        months.push(obj);
        // Subtract a month each time
        date.setMonth(date.getMonth() - 1);
    }

html
{{curr.month.monthName}}  {{curr.year}}

A: Fiddle Here
It simply boils down to this filter:
$scope.searchFilter = function(included,date){
    return function(search){
        if(search.IsIncludedInSearchImpactCalculation!==included) return false;

        //needed to parse and use date constructor on your json's dates
        var dateParts = search.SearchedOn.split("/");
        var searchedOn = new Date(dateParts[2],dateParts[1]-1,dateParts[0]);//months are 0-11

        if(date.month === searchedOn.getMonth() && date.year===searchedOn.getFullYear()) return true;
        else return false;
    };
}

and used it like this:
Searches with impact
      {{(Searches|filter:searchFilter(true,currMonth)).length}}

or this:
Searches with NO impact
      {{(Searches|filter:searchFilter(false,currMonth)).length}}

This basically does what you are asking in the title, based on the parent loop (ng-repeat of months) parses and filters data in inner loop(which is caused by | filter passing every element of array to a function.)
Basically we need to ng-repeat months again but this time for printing count of included and not included searches for each month. So our filter needs 3 parameters, first whether it's included or not, second the month in question and lastly the searches to check for matching months.
angular filters expect an array to filter and passes each item to the filter function. So we return a function that gets single search as a parameter, do our thing and return true or false depending on if it's matched our criteria or not.
As a result | filter returns a new array filled with ones returned true from the filter function(this way we can ng-repeat with filters etc). Since we have our matched array now, we can simply get it's length as count.
I know sounds kind of confusing but check the fiddle it's not as confusing as i explained.
Feel free to ask anything that is not clear.

A: Working Demo - JSFiddle
Script:
Retrieve the last 12 months and store them in an array. Notice we are storing an array of object literals (year, month, value).
      function getMonths() {
            var date = new Date();

            var months = [];

            for (var i = 0; i < 12; i++) {
                months.push({
                    year: date.getFullYear(),
                    month: date.getMonth()+1,
                    value: new Date(date.getFullYear(), date.getMonth(), 1)
                });

                // Subtract a month each time
                date.setMonth(date.getMonth() - 1);
            }

            return months;
        }

        $scope.months = getMonths();

Define Your Search Filters. These search filters will be used to narrow down the results by search impact, and group the results by month.   The 'count' filter is the final filter that returns a count of the results.
Filter by Search Impact:
   app.filter('bySearchImpact', function() {
        return function(input, isIncludedInSearchImpact) {
            var output = [];
            for (var i in input) {
                if (input[i].IsIncludedInSearchImpactCalculation == isIncludedInSearchImpact) {
                    output.push(input[i]);
                }
            }

            return output;
        }
    });

Filter by Month:
    app.filter('byMonth', function () {

        function isSameMonth(date1, date2) {
            var month1 = date1.split('/')[1];
            var year1 = date1.split('/')[2];
            return parseInt(year1) == date2.year &&
                parseInt(month1) == date2.month;
        }
        return function (input, month) {

            var output = [];
            for (var i in input) {
                if (isSameMonth(input[i].SearchedOn, month)) {
                    output.push(input[i]);
                }
            }

            return output;
        };

    });

Count Filter:
    app.filter('count', function() {
        return function(input) {
            return input.length;
        };
    });

HTML:
Now that we have filters for filtering by SearchImpact and Month, as well as a filter for returning the count, we can apply them to get the final results:
Display Table Headers (notice how we make use of Angular's date filter)
 {{month.value | date: 'MMM yyyy' }}

Searches With Impact:
 {{Searches | bySearchImpact:true | byMonth:month | count}}

Searches With NO Impact:
 {{Searches | bySearchImpact:false | byMonth:month | count }}

Display Search Dates With Impact:

{{searchedOn.SearchedOn}}

Display Search Dates With NO Impact:

{{searchedOn.SearchedOn}}


text:
Q: Getting hiddenvalue HTML property from javascript I am trying to access the hidden HTML value (hiddenvalue) from javascript and storing it into a variable env.
HTML:
<button id="slct" hiddenfield="Forest" type="button" class="btn btn-default">Hello</button>

JS:
$('#slct').click(function (event) {
document.getElementById('env').value = $('#' + $(event.target).data('hiddenfield')).value;
});

What am I missing?

A: I would create a hidden html field
<input type="hidden" id="someId" value="someValue">

Getting the value of this field would look like:
var theValue = document.getElementById('someId').value;

What you want is probably this:
html:
<input type="hidden" id="env" value="">
<button class="slct" hiddenfield="Forest" type="button" class="btn btn-default">This sets Forest</button>
<button class="slct" hiddenfield="Fruit" type="button" class="btn btn-default">This sets Fruit</button>

javascript:
$('.slct').click(function(event) {
    // Set value to hidden field
    $('#env').val($(this).attr('hiddenfield'));
});

you can use data() instead of attr(), but the attribute needs to start with 'data-' then. E.g. data('hiddenvalue') to retrieve the value of attribute data-hiddenvalue
(see https://jsfiddle.net/2k0791hk/1/)


text:
Q: ACF Gallery thumbnails (image included) I am trying to achieve the below image:

Basically, I have set up ACF Gallery, and used the code below:
<?php $images = get_field('gallery'); if( $images ): ?>
  <?php foreach( $images as $image ): ?>
    <img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt']; ?>" />
  <?php endforeach; ?>
<?php endif; ?>

Which now lists all the images in the gallery. What I am looking for, is the first image to be full size, and the other 3 images to be thumbnails, like the image, which when clicked, change the full size image.
Anyone have any ideas?
EDIT:
Im open to another way of doing this

A: Normally I wouldn't post all of this, as it would require creating a lot of stuff, but luckily I just made something similar for work yesterday.
<?php $galleryImages = get_field('gallery'); ?>

    <img src="<?php echo $galleryImages[0]['sizes']['gallery-full']; ?>" id="galleryImageLarge" />

        <?php $i = 0;
        foreach($galleryImages as $galleryThumb){
                $i++;
                if($i==1){
                        $imgClass = 'active';
                }else{
                        $imgClass = '';
                }
                echo '';
        } ?>

In this example, "gallery-full" is a set custom image size for the large photo, and "gallery-thumb" is a set custom image size for my thumbnails.
The thumbnails have an attribute applied to them, called "picURL" and it houses the URL of the large image. The large image is auto-filled with the URL of the first image. Then, using jQuery, when a thumb is clicked, it changes the src value of the large image with the value of the thumbnail's "picURL".
It also gives the current thumbnail an "active" class, to allow for styling your current thumb.


text:
Q: Disable mouse codes passing to terminal once it was turned on by application? Sometimes I have application, which supports mouse (for ex. Midnight Commander) crash or disconnect but after that terminal remains in some mode, which makes it accept mouse movements as string commands:
(base) dimskraft@studebaker:~$ set mouse=
(base) dimskraft@studebaker:~$ set ttymouse=
(base) dimskraft@studebaker:~$ 0;32;19M32;33;19M32;34;19M32;36;19M32;37;19M32;38;20M32;39;20M32;41;20M32;42;20M32;43;20M32;44;20M32

How to disable it once it already happened?
I observe it in Terminator and can see different behavior in different panes. As you see, setting mouse and ttymouse to nothing doesn't help.

A: Those settings apply to Vim, not to the shell.
I think the best approach is to reset the terminal:
reset

This disables mouse tracking, and will also undo other changes made by tools such as Midnight Commander (try pressing CtrlC after MC crashes for example).
Alternatively, you could determine which mouse tracking mode is in use, and disable that explicitly (e.g. echo -e '\e[?1002;1005l' after Midnight Commander crashes in my terminal), but that will still leave other settings as-is. stty sane will restore sanity to the line discipline which will take care of those.

A: reset is vast overkill.  For starters, simply re-starting and then properly exiting the application will fix this.  It after all turns off the mouse reports that it has asked for at exit.
Alternatively, you just yourself send to the terminal the control sequences that turn the mouse reports back off.  You can do this with the printf shell utility, entering the control sequences by hand using the escape notation.
For convenience, and for user-space virtual terminals, I created an improved portable version of the setterm utility that can do this.  It works with GUI terminal emulators and the BSDs, unlike the util-linux one; and it is sensitive to the fact that only some terminal families properly handle the control sequences:
% printenv TERM
dumb
% setterm -7 --xterm-mouse-reports off --dec-locator-reports off
% setterm -7 --xterm-mouse-reports off --dec-locator-reports off | console-decode-ecma48
% setterm -7 --xterm-mouse-reports off --dec-locator-reports off | hexdump -C
% export TERM=xterm-256color
% export XTERM_VERSION=999
% setterm -7 --xterm-mouse-reports off --dec-locator-reports off | console-decode-ecma48
DECELR 0
DECSLE 0
DECRM 1006
DECRM 1003
DECRM 1002
DECRM 1000
% setterm -7 --xterm-mouse-reports off --dec-locator-reports off | hexdump -C
00000000  1b 5b 30 27 7a 1b 5b 30  27 7b 1b 5b 3f 31 30 30  |.[0'z.[0'{.[?100|
00000010  36 6c 1b 5b 3f 31 30 30  33 6c 1b 5b 3f 31 30 30  |6l.[?1003l.[?100|
00000020  32 6c 1b 5b 3f 31 30 30  30 6c                    |2l.[?1000l|
0000002a
%
There are the control sequences.
Further reading

*

*Jonathan de Boyne Pollard (2018). setterm.  nosh Guide.  Softwares.

*https://unix.stackexchange.com/a/482782/5132

*Why is printf better than echo?

*https://unix.stackexchange.com/a/491883/5132


text:
Q: C# Client to Client Messaging I will try and explain exactly what I want to achieve first.
Imagine two users are using a windows forms application, when User A opens a particular form a lock is applied to the data record underlying the form so that only that user can make changes at that time.
User B has a list of all records (in a grid) which among others contains a reference to the record already opened by User A. What we want to do is when User A opens the records User B's list of records is updated to show a lock icon next to the row to indicate the record is in use.
This is a trivial example of what we do with messaging but you get the idea, User A does something User B needs to knows about it.
I have implemented a system using Jabber-net for C# and an OpenFire Jabber Server. Basically when a message is to be sent, a new row gets inserted on a messages table in the database. The messages table is watched by a service client using the SqlDependancy object, so that when a new message is ready the service builds the relevant message and sends it to the desired client via Jabber and the OpenFire server.
This works OK, however OpenFire's out of the box functionality is for supporting Instant Messaging which obviously isn't what I'm trying to achieve . The problem I have is that if a user is logged in to two Application Contexts (i.e. Test and Live) OpenFire does not know which one to send a message to because the JID structure of user@server/resource takes no notice of the resource.
Basically the way I'm currently using OpenFire and Jabber-net isn't quite right.
Is there a pattern I can use for achieving what I want to achieve i.e. send a message to a client telling it do something, whilst being able to specify which client you are sending the message too. XMPP seemed like the answer because I can construct my own messages types to be parsed.
My application is a Windows Forms, .NET 3.5 C# application.

A: I'd just add some more data to indicate which Application Context is affected and have the other clients decide whether they need to handle the message or not.


text:
Q: Unable to pull up a field value in Drupal 7. Is this a bug? Global $user;
$items = field_get_items('user', $user, 'field_patientid', $user->language);

I have a field on user entity and I always get a value of FALSE in my debug.
In my database I have the correct entity type which is user. Why am I not getting any values?
I am able to pull up value using:
$user_fields->field_patientid['und']['0']['value'];

Why will the above mentioned statement not work?

A: If you look at the code for field_get_items(), you'll notice that the field information you're looking for needs to already be in the $user object in order for it to be returned by the function.
But global $user does not provide the field data.
From http://api.drupal.org/api/drupal/developer%21globals.php/global/user/7#comment-13744

The global user object contains some basic data from Drupal core. It
  does not automatically include data from other modules, including the
  core profile module. To get all data in the user object, you need to
  do a full user_load().


text:
Q: Silverstripe UserForms - populate options from DataObject I'm very new to Silverstripe,
On the CMS page I can add a dropdown form item, and I see that I can create options. BUT. What I want to do is populate the dropdown from an array. How can I do this?
The array will look something like this:
$dropdownFields = array(
  'option1' => array(lots of emails),
  'option2' => array(lots of emails),
  'option3' => array(lots of emails),
  etc
)

I think what I want to do is have a DataObject with an 'option' field and a 'text' field where emails are entered in CSV format.
But how can I get the dropdown menu UserForms to retrieve option values from the DataObject instead of as an input from a user via the cms...

A: You cannot achieve this via the CMS and the module alone. You will need to create a custom EditableFormField to achieve this.
Subclass this and make changes where necessary: https://github.com/silverstripe/silverstripe-userforms/blob/master/code/model/formfields/EditableDropdown.php


text:
Q: Asp.Net MVC project with n-tier architecture I want to asp.net mvc project using n-tier architecture. I have Confused in that issue;
I have 4 tiers that are BLL, DAL,Entities and WebUI. WebUI tier is a asp.net mvc project. I added data model into entities tier. In DAL, I create some classes about crud opparations using entity framework. Finally I serve this classes as repositories on BLL. BLL knows DAL and entities tiers, DAL knows entites tier and WebUI is only knows BLL. In WebUI, I can access repositories where is into BLL.
But this repositories' return values are entity classes. I have to give a reference from entities to WebUI tier. I don't want that WebUI accesses databese directly. It should access database using repositories inside BLL.
What should I do? I want to do right thing. Is anything wrong my
architecture?
Thanks for helping answers.

A: You can have another project that has only models for BLLEntities.
BLL will always have to map BLLEntities to DALEntities and DALEntities to BLLEnttiies.
You can use AutoMapper for that.
Any Layer above BLL should deal with BLL entities and not with DALEntities.