text:
Q: How to create rooms with socket.io? I am writing an online lottery, I want to create different rooms with a limit on rates and participants. Question. How to implement the room?
Actually, here is the class of the GameController.js game:
class GameController {
    constructor (timer, minBetPrice, maxBetPrice, maxAmount, room, port, socket) {

        this.bets = {}
        this.users = {}
        this.room = room
        this.timer = timer
        this.minBetPrice = minBetPrice
        this.maxBetPrice = maxBetPrice
        this.maxAmount = maxAmount
        this.amount = null
        this.io = socket
        this.io.listen (port)
        this.initConnect ()

    }
    initConnect () {
        try {
            this.io.on ('connection', (socket => {
                this.users [socket.id] = {
                    id: socket.id
                }
                console.log (this.users)
                this.connectInRoom (socket)
                socket.on ('disconnect', data => {
                    console.log (`$ {socket.id} disconnected`)
                    delete this.users [socket.id]
                })
            }))
        } catch (e) {
            console.error (e)
        }
    }
    connectInRoom (socket) {
        socket.on ('event', data => {
            socket.join (data.room)
            console.log (`$ {socket.id} - Joined in $ {data.room} room`)
            socket.emit ('event', {
                success: true
                message: `UserID - $ {socket.id}`,
                room: data.room
            })
        })
    }
}

Here is the contents of app.js:
const smallRoom = new GameController (10, 10, 20, 20, 'smallRoom', 4040, io)
const highRoom = new GameController (5, 0, 10, 20, 'highRoom', 4045, io)

From the client on the event event, I get the name of the room and connect to it. As far as I understand, do not need to create 2 instances of the class for different rooms in app.js? Because now I have 2 connections happening right away.
In the future, when creating a bet in a certain room, will I need to send a bet and the name of the room to which it will go?


text:
Q: Custom Post Type Pagination Problem in Admin Section I have several custom post types, here is the creation of two of them:
Projects
add_action( 'init', 'register_cpt_project' );

function register_cpt_project() {

$labels = array(
    'name' => _x( 'Projects', 'project' ),
    'singular_name' => _x( 'Project', 'project' ),
    'add_new' => _x( 'Add New', 'project' ),
    'add_new_item' => _x( 'Add New Project', 'project' ),
    'edit_item' => _x( 'Edit Project', 'project' ),
    'new_item' => _x( 'New Project', 'project' ),
    'view_item' => _x( 'View Project', 'project' ),
    'search_items' => _x( 'Search Projects', 'project' ),
    'not_found' => _x( 'No projects found', 'project' ),
    'not_found_in_trash' => _x( 'No projects found in Trash', 'project' ),
    'parent_item_colon' => _x( 'Parent Project:', 'project' ),
    'menu_name' => _x( 'Projects', 'project' ),
);

$args = array(
    'labels' => $labels,
    'hierarchical' => true,

    'supports' => array( 'title', 'editor', 'excerpt' ),
    'taxonomies' => array( 'project_categories' ),
    'public' => true,
    'show_ui' => true,
    'show_in_menu' => true,

    'show_in_nav_menus' => true,
    'publicly_queryable' => true,
    'exclude_from_search' => false,
    'has_archive' => true,
    'query_var' => true,
    'can_export' => true,
    'rewrite' => array('slug' => 'our-work/%project_categories%', 'with_front' => false),
    'capability_type' => 'post'
);

register_post_type( 'project', $args );
}

Leadership
add_action( 'init', 'register_cpt_leadership' );
function register_cpt_leadership() {

    $labels = array(
        'name' => _x( 'Leaders', 'leadership' ),
        'singular_name' => _x( 'Leadership', 'leadership' ),
        'add_new' => _x( 'Add New', 'leadership' ),
        'add_new_item' => _x( 'Add New Leadership', 'leadership' ),
        'edit_item' => _x( 'Edit Leadership', 'leadership' ),
        'new_item' => _x( 'New Leadership', 'leadership' ),
        'view_item' => _x( 'View Leadership', 'leadership' ),
        'search_items' => _x( 'Search Leaders', 'leadership' ),
        'not_found' => _x( 'No leaders found', 'leadership' ),
        'not_found_in_trash' => _x( 'No leaders found in Trash', 'leadership' ),
        'parent_item_colon' => _x( 'Parent Leadership:', 'leadership' ),
        'menu_name' => _x( 'Leaders', 'leadership' ),
    );

    $args = array(
        'labels' => $labels,
        'hierarchical' => true,

        'supports' => array( 'title', 'editor' ),

        'public' => true,
        'show_ui' => true,
        'show_in_menu' => true,
        'menu_position' => 20,

        'show_in_nav_menus' => true,
        'publicly_queryable' => true,
        'exclude_from_search' => false,
        'has_archive' => false,
        'query_var' => true,
        'can_export' => true,
        'rewrite' => array('slug' => 'who-we-are/leadership'),
        'capability_type' => 'post'
    );

    register_post_type( 'leadership', $args );
}

Everything is working great on the public site, but when you log into the wp-admin section, that's where things get weird.
The Leadership post type functions correctly. But the Projects type, when using the pagination buttons in the list page, returns no posts when going to any page greater than 1.
So if I go to:
http://www.example.com/wp-admin/edit.php?post_type=project&paged=2
I get:

No projects found

Even though there are 70 posts, and the Screen Options are set to 20 posts per page. Yes, I can set that option to a higher number, and just show all posts in a single page, but that doesn't fix the problem at hand.
Has anyone had this issue before, or have any thoughts on how to fix this?

A: It turns out that in my functions.php file, I had the following function:
function limit_posts_per_archive_page() {
    if ( is_tax('project_categories') )
        $limit = 9999;
    else
        $limit = get_option('posts_per_page');
        set_query_var('posts_per_archive_page', $limit);
    }
add_filter('pre_get_posts', 'limit_posts_per_archive_page');

This was an old function modifying the pagination on the front-end, and it turns out that this was causing the error.
Removing the function fixed this.

A: It's Permalinks issue.
Please go to Appearance > Permalinks > set default first and than set post name.
Than refresh your post you will be able to show your post content with it's title.

redpajama_set_name: RedPajamaStackExchange


text:
Q: is there a way to make a button cause a div to appear on the first click then disappear on the second click? I wonder if there is a way for the same button to make a div appear if I click on it once and disappear if I click on it another time
JS code:
const button = document.getElementById("menu");
const menu = document.querySelector(".box");
button.addEventListener("click", function () {
  menu.style.display = "block";
});

HTML code:
<button id="menu">click me for menu!</button>

</box>

CSS code:
.box{
  height: 200px;
  width: 200px;
  display: none;
}

I used this method before but I don't know if there is a way to use it directly
let clicks = 0;
button.addEventListener("click", function () {
  checkclicks();
  if (clicked === true) menu.style.display = "block";
  if (clicked === false) menu.style.display = "none";
});
function checkclicks() {
  clicks += 1;
  if (clicks % 2 === 1) {
    //on
    clicked = true;
  }
  if (clicks % 2 === 0) {
    //off
    clicked = false;
  }
}

EDIT
I want it to be hidden by default and only appearing when I click on the button and gets hidden again when I click on the same button

A: You can use classList.toggle to toggle hidden class to your div with each click

    var mydiv = document.querySelector("#mydiv")
    var mybtn = document.querySelector("#mybtn")

    mybtn.addEventListener("click", function () {
       mydiv.classList.toggle("hidden")
    });
.hidden{
display:none;
}

#mydiv{
height:50px;
width:50px;
color:white;
background-color:blue;
padding:10px;
}

test

<button id="mybtn">Click Me!</button>


text:
Q: angularjs: one directive in another, inherit or share it's isolated scope The origin problem is: I want to create a directive to process field checking automaticly, the result should be like this:

    Item Name:
    <input type='text' ng-model="item.item_name" />
    <error-message>ITEM NAME INVALID!</error-message>

so I created two directive: filedCheck and errorMessage, the second requires the first.
my origin code is below here:
(->
    app.directive 'fieldCheck', () ->
        search_ng_model_elem = (element) ->
            if element.attributes?
                if element.attributes.getNamedItem('ng-model')
                    return element

            if element.children?.length
                for e in element.children
                    r = search_ng_model_elem(e)
                    return r if r?

        priority: 0
        restrict: "A"
        replace: false
        scope:
            'check': '=fieldCheck'
        controller: ($scope, $element) ->
            $scope.valid = true
            model_elem = search_ng_model_elem($element[0])
            alert 'directive: fieldCheck compile error (ng-model not found) !' if not model_elem?
            model_name = model_elem.attributes.getNamedItem('ng-model').value
            if not $scope.check?
                alert 'check func not found!'
            else
                angular.element(model_elem).scope().$watch model_name, ((data) ->
                    $scope.valid = $scope.check(data)
                ), true
            $scope: $scope
        link:
            post: (scope, element, attrs, controller) ->
                scope.error = message: "error!"

    app.directive 'errorMessage', () ->
        priority: 2
        require: '^fieldCheck'
        restrict: "E"
        template: '

'
        #scope:
        #   'message': '=message'
        replace: false
        link:
            post: (scope, element, attrs, controller) ->
                scope.message = element.text() or '??????'
                alert scope is controller.$scope.$parent
)()

to make it easier to read, I simplified my code so it looks like this:
app.directive 'fieldCheck', () ->
    restrict: "A"
    scope:
        'check': '=fieldCheck'
    controller: ($scope, $element) ->
        model_elem = search_ng_model_elem($element[0])
        model_name = model_elem.attributes.getNamedItem('ng-model').value
        angular.element(model_elem).scope().$watch model_name, ((data) ->
            $scope.valid = $scope.check(data) ### 'valid' is the value I want to set to [the shared scope]
        ), true
        $scope: $scope
    link: (scope, element, attrs, controller) ->
        scope.message: "error!"

app.directive 'errorMessage', () ->
    require: '^fieldCheck'
    restrict: "E"
    template: '

' ### 'valid' is the value I want to get
    link: (scope, element, attrs, controller) ->
        scope.message = element.text() or '??????'
        alert scope is controller.$scope.$parent

the problem is, "scope is controller.$scope.$parent" returns true, that means the scope I got from the link function of directive errorMessagee is not the $scope I put data to, but it's parent. so that's the question: how to make these directive share a same scope?


text:
Q: Recursive Mergesort in Java first and foremost, thanks in advance for any and all replies, they are greatly appreciated. Now to the purpose of this post; I am having trouble implementing a merge sort in Java. I am getting a Null Pointer Exception, however, I can not figure out what the mistake is, to me the code looks ok. Here is what I have thus far:
public List mSort(List l) {

    if (l.size() <= 1)
        return l;

    List left = null;
    List right = null;
    int mid = l.size() / 2;

    for (int x = 0; x < mid; x++)
        left.add(l.get(x));
    for (int x = 0; x >= mid; x++)
        right.add(l.get(x));

    left = mSort(left);
    right = mSort(right);

    return merge(left, right);
}

public List merge(List left, List right) {

    List r = null;
    while (left.size() > 0 || right.size() > 0) {
        if (left.size() > 0 && right.size() > 0)
            if (left.get(0) <= right.get(0)) {
                r.add(left.get(0));
                left.remove(0);
            }
            else {
                r.add(right.get(0));
                right.remove(0);
            }
        else if (left.size() > 0) {
            r.add(left.get(0));
            left.remove(0);

        }
        else if (right.size() > 0) {
            r.add(right.get(0));
            right.remove(0);
        }
    }
    return r;

}

...apparently, the pointer exception is coming from the 'For' statements in the 'mSort' methods, anything that can point out my mistake or guide me in the right direction is greatly appreciated!!!

A: left and right are null, you can't add to that!!!
List left = new ArrayList();
List right = new ArrayList();

A: for (int x = 0; x < mid; x++)
        left.add(l.get(x));
    for (int x = 0; x >= mid; x++)
        right.add(l.get(x));

must be
int x = 0;
for (; x < mid; x++)
    left.add(l.get(x));
for (; x < l.size(); x++)
    right.add(l.get(x));


text:
Q: Esri ST_Geometry functions too slow on Oracle I'm writing an SQL statement to create a feature class and using st_geometry functions. But it's taking too long.
So I begin the statement with a join, which is taking 150-200ms
SELECT PRC.OBJECTID AS OWNED_PARCEL_FID,
                       OWN.DEPARTMENT,
                       OWN.STATE_NAME,
                       OWN.CITY_NAME,
                       OWN.NEIGHBRHD_NAME,
                       OWN.BLOCK,
                       OWN.PARCEL,
                       OWN.NAME,
                       OWN.CONDITION,
                       PRC.SHAPE
                FROM   CITY_PARCEL PRC
                       INNER JOIN PARCEL_OWNERSHIP OWN
                               ON PRC.OBJECTID = OWN.GIS_ID
                WHERE OWN.STATUS = 'OWNED'

then I added ST_Intersects and ST_Intersection functions
SELECT OWNED_PARCEL.OWNED_PARCEL_fid AS OWNED_PARCEL_FID,
               PLAN.OBJECTID AS PLAN_FID,
               PLAN.PLAN_CODE,
               PLAN.PLAN_NAME,
               PLAN.PLAN_FUNCTION,
               PLAN.PLAN_MAIN_FUNCTION,
               PLAN.USAGE_YTPE,
               OWNED_PARCEL.DEPARTMENT,
               OWNED_PARCEL.STATE_NAME,
               OWNED_PARCEL.CITY_NAME,
               OWNED_PARCEL.NEIGHBRHD_NAME,
               OWNED_PARCEL.BLOCK,
               OWNED_PARCEL.PARCEL,
               OWNED_PARCEL.NAME,
               SDE.ST_INTERSECTION(OWNED_PARCEL.SHAPE, PLAN.SHAPE) AS SHAPE
        FROM   (SELECT PRC.OBJECTID AS OWNED_PARCEL_FID,
                       OWN.DEPARTMENT,
                       OWN.STATE_NAME,
                       OWN.CITY_NAME,
                       OWN.NEIGHBRHD_NAME,
                       OWN.BLOCK,
                       OWN.PARCEL,
                       OWN.NAME,
                       OWN.CONDITION,
                       PRC.SHAPE
                FROM   CITY_PARCEL PRC
                       INNER JOIN PARCEL_OWNERSHIP OWN
                               ON PRC.OBJECTID = OWN.GIS_ID
                WHERE OWN.STATUS = 'OWNED') OWNED_PARCEL,
                      CITY_PLAN PLAN
        WHERE SDE.ST_INTERSECTS(OWNED_PARCEL.SHAPE, PLAN.SHAPE) = 1)OWNED_PARCEL_PLAN_INTERSECT;

This is where it gets extremely slow. Like around 8 minutes.
Parcel table has roughly 23000 records and Plan table has 280000 records. I assume it shouldn't take so long. Even if I take first 100 rows of the tables. It takes around 4 mins.
After that, I applied ST_Symmetricdiff with this select and PARCEL table and union this two tables. That SQL worked for a day and still didn't finished. So I had to kill the process. Are those times makes sense or is there something wrong with it?
Here is the last statement.
SELECT owned_PARCEL_fid,
       plan_fid,
       PLAN_CODE,
       PLAN_NAME,
       PLAN_FUNCTION,
       USAGE_TYPE,
       DEPARTMENT,
       STATE_NAME,
       CITY_ANME,
       NEIGHBRHD_NAME,
       BLOCK,
       PARCEL,
       NAME,
       CONDIT,
       OWNED_PARCEL_SHAPE_AREA,
       SHAPE
FROM   (SELECT OWNED_PARCEL.owned_PARCEL_fid,
               OWNED_PARCEL_PLAN_INTERSECTION.plan_fid,
               OWNED_PARCEL_PLAN_INTERSECTION.PLAN_CODE,
               OWNED_PARCEL_PLAN_INTERSECTION.PLAN_NAME,
               OWNED_PARCEL_PLAN_INTERSECTION.PLAN_FUNCTION,
               OWNED_PARCEL_PLAN_INTERSECTION.USAGE_TYPE,
               OWNED_PARCEL.DEPARTMENT,
               OWNED_PARCEL.STATE_NAME,
               OWNED_PARCEL.CITY_ANME,
               OWNED_PARCEL.NEIGHBRHD_NAME,
               OWNED_PARCEL.BLOCK,
               OWNED_PARCEL.PARCEL,
               OWNED_PARCEL.NAME,
               OWNED_PARCEL.CONDIT,
               SDE.ST_AREA(OWNED_PARCEL.SHAPE) AS OWNED_PARCEL_SHAPE_AREA,
               SDE.ST_SYMMETRICDIFF(OWNED_PARCEL.SHAPE,OWNED_PARCEL_PLAN_INTERSECTION.SHAPE) AS SHAPE
        FROM   (SELECT PRC.OBJECTID AS OWNED_PARCEL_FID,
                       OWN.DEPARTMENT,
                       OWN.STATE_NAME,
                       OWN.CITY_ANME,
                       OWN.NEIGHBRHD_NAME,
                       OWN.BLOCK,
                       OWN.PARCEL,
                       OWN.NAME,
                       OWN.CONDIT,
                       PRC.SHAPE
                FROM   CITY_PARCEL PRC
                       INNER JOIN PARCEL_ownership OWN
                               ON PRC.OBJECTID = OWN.GIS_ID
                WHERE  OWN.status = 'OWNED_PARCEL') OWNED_PARCEL,
               (SELECT OWNED_PARCEL.owned_PARCEL_fid AS OWNED_PARCEL_FID,
                       PLAN.OBJECTID AS PLAN_FID,
                       PLAN.PLAN_CODE,
                       PLAN.PLAN_NAME,
                       PLAN.PLAN_FUNCTION,
                       PLAN.USAGE_TYPE,
                       OWNED_PARCEL.DEPARTMENT,
                       OWNED_PARCEL.STATE_NAME,
                       OWNED_PARCEL.CITY_ANME,
                       OWNED_PARCEL.NEIGHBRHD_NAME,
                       OWNED_PARCEL.BLOCK,
                       OWNED_PARCEL.PARCEL,
                       OWNED_PARCEL.NAME,
                       SDE.ST_INTERSECTION(OWNED_PARCEL.SHAPE, PLAN.SHAPE) AS
                       SHAPE
                FROM   (SELECT PRC.OBJECTID AS OWNED_PARCEL_FID,
                               OWN.DEPARTMENT,
                               OWN.STATE_NAME,
                               OWN.CITY_ANME,
                               OWN.NEIGHBRHD_NAME,
                               OWN.BLOCK,
                               OWN.PARCEL,
                               OWN.NAME,
                               OWN.CONDIT,
                               PRC.SHAPE
                        FROM   CITY_PARCEL PRC
                               INNER JOIN PARCEL_ownership OWN
                                       ON PRC.OBJECTID = OWN.GIS_ID
                        WHERE  OWN.status = 'OWNED_PARCEL') OWNED_PARCEL,
                       CITY_PLAN PLAN
                WHERE  SDE.St_intersects(OWNED_PARCEL.SHAPE, PLAN.SHAPE) = 1)
               OWNED_PARCEL_PLAN_INTERSECTION
        UNION
        SELECT OWNED_PARCEL.owned_PARCEL_fid AS OWNED_PARCEL_FID,
               PLAN.OBJECTID AS PLAN_FID,
               PLAN.PLAN_CODE,
               PLAN.PLAN_NAME,
               PLAN.PLAN_FUNCTION,
               PLAN.USAGE_TYPE,
               OWNED_PARCEL.DEPARTMENT,
               OWNED_PARCEL.STATE_NAME,
               OWNED_PARCEL.CITY_ANME,
               OWNED_PARCEL.NEIGHBRHD_NAME,
               OWNED_PARCEL.BLOCK,
               OWNED_PARCEL.PARCEL,
               OWNED_PARCEL.NAME,
               OWNED_PARCEL.CONDIT,
               SDE.ST_AREA(OWNED_PARCEL.SHAPE) AS OWNED_PARCEL_SHAPE_AREA,
               SDE.ST_INTERSECTION(OWNED_PARCEL.SHAPE, PLAN.SHAPE) AS SHAPE
        FROM   (SELECT PRC.OBJECTID AS OWNED_PARCEL_FID,
                       OWN.DEPARTMENT,
                       OWN.STATE_NAME,
                       OWN.CITY_ANME,
                       OWN.NEIGHBRHD_NAME,
                       OWN.BLOCK,
                       OWN.PARCEL,
                       OWN.NAME,
                       OWN.CONDIT,
                       PRC.SHAPE
                FROM   CITY_PARCEL PRC
                       INNER JOIN PARCEL_ownership OWN
                               ON PRC.OBJECTID = OWN.GIS_ID
                WHERE  OWN.status = 'OWNED') OWNED_PARCEL,
               CITY_PLAN PLAN
        WHERE  SDE.ST_INTERSECTS(OWNED_PARCEL.SHAPE, PLAN.SHAPE) = 1);


text:
Q: WPF : how to iterate through observable collection items and store specific items in a list of double type I have an Observable collection containing some properties. My requirement is i want to iterate through observable collection properties and store/add properties from  budgetReportYear1 to budgetReportYear30  in a separate list (double type).
Model:-
namespace RedCube45Mvvm.Model
 {
    public class RangeData : INotifyPropertyChanged
{

    #region Constructor

    public RangeData(MainWindowViewModel viewModel)
    {

        m_ViewModel = viewModel;

    }

    #endregion

    #region Fields

    private MainWindowViewModel m_ViewModel;

    private string name;
    private int fleet_size;
    private double availability;
    #endregion

    #region Properties

    public string Name
    {
        get { return name; }
        set
        {
            name = value;
        }
    }

    public double Availability
    {
        get { return availability; }
        set
        {
            availability = value;
            Onchanged("Availability");
            var u = new Operations.Process.Updater(m_ViewModel, this,                          "avail");
        }
    }

    public int FleetSize
    {
        get { return fleet_size; }
        set
        {
            fleet_size = value;
            Onchanged("FleetSize");
            var u = new Operations.Process.Updater(m_ViewModel, this, "fleetSize");
        }
    }

    #endregion

    #region Budget Report Year
    private double _budgetReportYear1 = 1;
    private double _budgetReportYear2 = 1;
    private double _budgetReportYear3 = 1;
    private double _budgetReportYear4 = 1;
    private double _budgetReportYear5 = 1;
    private double _budgetReportYear6 = 1;
    private double _budgetReportYear7 = 1;
    private double _budgetReportYear8 = 1;
    private double _budgetReportYear9 = 1;
    private double _budgetReportYear10 = 1;
    private double _budgetReportYear11 = 1;
    private double _budgetReportYear12 = 1;
    private double _budgetReportYear13 = 1;
    private double _budgetReportYear14 = 1;
    private double _budgetReportYear15 = 1;
    private double _budgetReportYear16 = 1;
    private double _budgetReportYear17 = 1;
    private double _budgetReportYear18 = 1;
    private double _budgetReportYear19 = 1;
    private double _budgetReportYear20 = 1;
    private double _budgetReportYear21 = 1;
    private double _budgetReportYear22 = 1;
    private double _budgetReportYear23 = 1;
    private double _budgetReportYear24 = 1;
    private double _budgetReportYear25 = 1;
    private double _budgetReportYear26 = 1;
    private double _budgetReportYear27 = 1;
    private double _budgetReportYear28 = 1;
    private double _budgetReportYear29 = 1;
    private double _budgetReportYear30 = 1;

    public bool Loaded { get; set; }

    public double budgetReportYear1
    {
        get { return _budgetReportYear1; }
        set
        {
            _budgetReportYear1 = value;
            Onchanged("budgetReportYear1");
        }
    }

    public double budgetReportYear2
    {
        get { return _budgetReportYear2; }
        set
        {
            _budgetReportYear2 = value;
            Onchanged("budgetReportYear2");
        }
    }

    public double budgetReportYear3
    {
        get { return _budgetReportYear3; }
        set
        {
            _budgetReportYear3 = value;
            Onchanged("budgetReportYear3");
        }
    }

    public double budgetReportYear4
    {
        get { return _budgetReportYear4; }
        set
        {
            _budgetReportYear4 = value;
            Onchanged("budgetReportYear4");
        }
    }

    public double budgetReportYear5
    {
        get { return _budgetReportYear5; }
        set
        {
            _budgetReportYear5 = value;
            Onchanged("budgetReportYear5");
        }
    }

    public double budgetReportYear6
    {
        get { return _budgetReportYear6; }
        set
        {
            _budgetReportYear6 = value;
            Onchanged("budgetReportYear6");
        }
    }

    public double budgetReportYear7
    {
        get { return _budgetReportYear7; }
        set
        {
            _budgetReportYear7 = value;
            Onchanged("budgetReportYear7");
        }
    }

    public double budgetReportYear8
    {
        get { return _budgetReportYear8; }
        set
        {
            _budgetReportYear8 = value;
            Onchanged("budgetReportYear8");
        }
    }

    public double budgetReportYear9
    {
        get { return _budgetReportYear9; }
        set
        {
            _budgetReportYear9 = value;
            Onchanged("budgetReportYear9");
        }
    }

    public double budgetReportYear10
    {
        get { return _budgetReportYear10; }
        set
        {
            if (value < 0.01 || value > 99)
            {
                throw new ArgumentException("Value must be within 0.01 & 99");
            }
            _budgetReportYear10 = value;
            Onchanged("budgetReportYear10");
        }
    }

    public double budgetReportYear11
    {
        get { return _budgetReportYear11; }
        set
        {
            _budgetReportYear11 = value;
            Onchanged("budgetReportYear11");

        }
    }

    public double budgetReportYear12
    {
        get { return _budgetReportYear12; }
        set
        {
            _budgetReportYear12 = value;
            Onchanged("budgetReportYear12");

        }
    }

    public double budgetReportYear13
    {
        get { return _budgetReportYear13; }
        set
        {
            _budgetReportYear13 = value;
            Onchanged("budgetReportYear13");
        }
    }

    public double budgetReportYear14
    {
        get { return _budgetReportYear14; }
        set
        {
            _budgetReportYear14 = value;
            Onchanged("budgetReportYear14");
        }
    }

    public double budgetReportYear15
    {
        get { return _budgetReportYear15; }
        set
        {
            _budgetReportYear15 = value;
            Onchanged("budgetReportYear15");
        }
    }

    public double budgetReportYear16
    {
        get { return _budgetReportYear16; }
        set
        {
            _budgetReportYear16 = value;
            Onchanged("budgetReportYear16");
        }
    }

    public double budgetReportYear17
    {
        get { return _budgetReportYear17; }
        set
        {
            _budgetReportYear17 = value;
            Onchanged("budgetReportYear17");
        }
    }

    public double budgetReportYear18
    {
        get { return _budgetReportYear18; }
        set
        {
            _budgetReportYear18 = value;
            Onchanged("budgetReportYear18");
        }
    }

    public double budgetReportYear19
    {
        get { return _budgetReportYear19; }
        set
        {
            _budgetReportYear19 = value;
            Onchanged("budgetReportYear19");
        }
    }

    public double budgetReportYear20
    {
        get { return _budgetReportYear20; }
        set
        {
            _budgetReportYear20 = value;
            Onchanged("budgetReportYear20");
        }
    }

    public double budgetReportYear21
    {
        get { return _budgetReportYear21; }
        set
        {
            _budgetReportYear21 = value;
            Onchanged("budgetReportYear21");

        }
    }

    public double budgetReportYear22
    {
        get { return _budgetReportYear22; }
        set
        {
            _budgetReportYear22 = value;
            Onchanged("budgetReportYear22");
        }
    }

    public double budgetReportYear23
    {
        get { return _budgetReportYear23; }
        set
        {
            _budgetReportYear23 = value;
            Onchanged("budgetReportYear23");
        }
    }

    public double budgetReportYear24
    {
        get { return _budgetReportYear24; }
        set
        {
            _budgetReportYear24 = value;
            Onchanged("budgetReportYear24");
        }
    }

    public double budgetReportYear25
    {
        get { return _budgetReportYear25; }
        set
        {
            _budgetReportYear25 = value;
            Onchanged("budgetReportYear25");
        }
    }

    public double budgetReportYear26
    {
        get { return _budgetReportYear26; }
        set
        {
            _budgetReportYear26 = value;
            Onchanged("budgetReportYear26");
        }
    }

    public double budgetReportYear27
    {
        get { return _budgetReportYear27; }
        set
        {
            _budgetReportYear27 = value;
            Onchanged("budgetReportYear27");
        }
    }

    public double budgetReportYear28
    {
        get { return _budgetReportYear28; }
        set
        {
            _budgetReportYear28 = value;
            Onchanged("budgetReportYear28");
        }
    }

    public double budgetReportYear29
    {
        get { return _budgetReportYear29; }
        set
        {
            _budgetReportYear29 = value;
            Onchanged("budgetReportYear29");
        }
    }

    public double budgetReportYear30
    {
        get { return _budgetReportYear30; }
        set
        {
            _budgetReportYear30 = value;
            Onchanged("budgetReportYear30");
        }
    }

    public string Error
    {

        get { throw new NotImplementedException(); }

    }

    #endregion

    #region Event Handler

    public event PropertyChangedEventHandler PropertyChanged;
    public void Onchanged(string name)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(name));

    }

       #endregion
  }
}

View Model:-
 public ObservableCollection<Model.RangeData> RangeData
  {
      get { return range_data; }

      set {
        range_data = value;
        base.RaisePropertyChangedEvent("RangeData");
      }
   }


text:
Q: create a data frame by selecting the max from subset of a data set I wish to create a data frame from another data frame by selecting the max of subsets from the 1st data frame. Say I have the 1st data frame
df:
name     date      weekday    util
----     ----      -------    ----
alpha    201801          1    10.1
alpha    201801          2    7.1
alpha    201801          3    1.1
alpha    201801          4    4.1
bravo    201801          1    9.9
bravo    201801          2    8.9
bravo    201801          3    1.9
bravo    201801          4    11.9
charlie  201801          1    0.1
charlie  201801          2    2.0
charlie  201801          3    7.3
charlie  201801          4    5.0

I wish to create another data frame using the max util for every unique date, name tuple
df_unique:
name       date       util
-----      ----       ----
alpha      201801     10.1
bravo      201801     11.9
charlie    201801     7.3

I know we can choose a max by using
>max(df[df$name == 'alpha' && df$date == 201801, df$util])
10.1

However how would we do this for every unique name, date tuple. Is this even possible or do I need to create a function to do this?

A: Here is a solution using the data.table package.
library(data.table)

setDT(dat)

dat2 <- dat[, .(util = max(util)), by = .(name, date)]
dat2
#       name   date util
# 1:   alpha 201801 10.1
# 2:   bravo 201801 11.9
# 3: charlie 201801  7.3

Or we can use the dplyr package.
library(dplyr)

dat2 <- dat %>%
  group_by(name, date) %>%
  summarise(util = max(util)) %>%
  ungroup()
dat2
# # A tibble: 3 x 3
#   name      date  util
#   <chr>    <int> <dbl>
# 1 alpha   201801  10.1
# 2 bravo   201801  11.9
# 3 charlie 201801   7.3

DATA
dat <- read.table(text = "name     date      weekday    util
                  alpha    201801          1    10.1
                  alpha    201801          2    7.1
                  alpha    201801          3    1.1
                  alpha    201801          4    4.1
                  bravo    201801          1    9.9
                  bravo    201801          2    8.9
                  bravo    201801          3    1.9
                  bravo    201801          4    11.9
                  charlie  201801          1    0.1
                  charlie  201801          2    2.0
                  charlie  201801          3    7.3
                  charlie  201801          4    5.0",
                  header = TRUE, stringsAsFactors = FALSE)


text:
Q: Sum of Series with negative exponents $
3= \sum_{n=1}^{t} \frac{1}{1.08^n}
$
I see that it is $3 = 1.08^{-t}(12.5 \times 1.08^t{-12.5})$ (from Wolfram Alpha, but I'm not sure how to get it. I tried solving as a geometric series, I had problems and didn't get the correct answer.
I see that $ t\approx3.56592$, which seems like it's correct, but I have no idea where the 12.5 and all that stuff came from. Unfortunately my calculus book doesn't help much, as it is mainly focus on infinite series.

A: I would solve for $t$
$$S(t)=\displaystyle\sum_{n=1}^{t}\dfrac{1}{1.08^{n}}=3.$$
The sum of a geometric progression with first term $u_{1}$ and ratio $r$ is
given $(\ast)$ by
$$S(t)=u_{1}\times \dfrac{1-r^{t}}{1-r}.$$
In this case
$$\dfrac{1}{1.08}\times \dfrac{1-\left( \dfrac{1}{1.08}\right) ^{t}}{1-\dfrac{1}{%
1.08}}=3$$
or
$$\dfrac{1-\left( \dfrac{1}{1.08}\right) ^{t}}{0.08}=3\iff \left( \dfrac{1}{1.08}%
\right) ^{t}=0.76.$$
Applying logarithms, we obtain the "time" $t$
$$t\log \left( \dfrac{1}{1.08}\right) =\log 0.76,$$
$$t=\dfrac{\log 0.76}{-\log 1.08}\approx 3.5659,$$
which means that we need more than $3$ periods and less than $4$, at an interest rate of $8\%$, coumpounded per period, to get a total of $3$ currency units.
$(\ast)$ Derivation:
$$S=u_{1}+u_{2}+u_{3}+\ldots +u_{t}$$
$$rS=ru_{1}+ru_{2}+ru_{3}+\ldots +ru_{t-1}+ru_{t}$$
$$u_{k}=ru_{k-1}=u_{1}r^{k-1}$$
$$S-rS=\left( u_{1}+u_{2}+u_{3}+\ldots +u_{t}\right) -\left(
ru_{1}+ru_{2}+ru_{3}+\ldots +ru_{t-1}+ru_{t}\right) $$
$$(1-r)S=u_{1}-ru_{t}$$
$$S=\dfrac{u_{1}-ru_{t}}{1-r}=\dfrac{u_{1}-u_{1}r^{t}}{1-r}$$

A: HINT$\ $ Put $\rm\ a = 1.08\:$. Multiply both sides by $\rm\ a^t\ $ to get$\:$ RHS $\rm\: = \ \sum_{k=0}^{t-1}\ a^k$
As for "where the $12.5$ came from", $\rm\ 1/(a-1) = 1/0.08 = 100/8 = 12.5$

A: Simply suppose that $r = \frac{1}{1.08}$, or $r = a^{-k} = \frac{1}{a^k}$ and solve in the usual manner, as you would if the exponent was positive.
Example
$$ \sum \limits_{i=0}^{k-1} 9^{-i} = \sum \limits_{i=0}^{k-1} \frac{1}{9^i} = \frac{1- \left( 1/9 \right)^k}{1- \left( 1/9 \right)} = \frac{1 - \left( 1 / 9 \right)^k}{8/9} = \frac{9}{8} \left( 1 - \frac{1}{9^{k}} \right) $$
(Do not be confused with the harmonic series which does not have an exponent in its term.)


text:
Q: Mysterious Jboss shutdown We have a several application deployed in Jboss server. From last few month its observed that jboss servers gets killed without logging any error or exception neither in any application log nor in Jboss server log. The crash is not periodic and happens randomly. The crash is very silent (similar to kill -9 )and its become extremely difficult to debug the root cause.From our analysis one thing sure its not out of memory issue.We analysed the syslog as well, nothing suspicious found. Is possible to force VM to generate error log before the process crash due to any reason.
Any help would be appreciated.

A: The JVM logs fatal errors to hs_err_<pid>.log files
You can change the location of the fatal log file using java -XX:ErrorFile=/var/log/java/java_error%p.log

A: I experienced similar problem using JBoss EAP 6 in Linux enviroment, when system memory is almost gone the S.O kill some process, normally the file hs_err_pidxxx.log  with crash report are generated inside bin directory of JBoss. Other case that process is killed is when you are using JBoss with DC mode, when instance stay long time without communication with DC, the process is finalized, I dont know why.


text:
Q: Twisted: ReconnectingClientFactory connection to different servers I have a twisted ReconnectingClientFactory and i can successfully connect to given ip and port couple with this factory. And it works well.

reactor.connectTCP(ip, port, myHandsomeReconnectingClientFactory)

In this situation, when the server is gone, myHandsomeReconnectingClientFactory tries to connect same ip and port (as expected).
My goal is, when the server which serves on given ip and port couple is gone, connecting to a backup server (which have different ip and port).
Any ideas/comments on how to achieve this goal will be appreciated.

A: Id try something like:
class myHandsomeReconnectingClientFactory(protocol.ReconnectingClientFactory):

    def __init_(self, hosts):
        # hosts should be a list of tuples (host, port)
        self._hosts = hosts

    def clientConnectionFailed(self, connector, reason):
        if self.continueTrying:
            self._try_next_host(connector)

    def clientConnectionLost(self, connector, unused_reason):
        if self.continueTrying:
            self._try_next_host(connector)

    def _try_next_host(self, connector):
        # round robing of servers
        to_try = self._hosts.pop(0)
        self._hosts.append(to_try)
        connector.host, connector.port = to_try
        self.connector = connector
        self.retry()

I haven't actually tested it, but at least it should give you a good starting point. Good uck.

A: ReconnectingClientFactory doesn't have this capability.  You can build your own factory which implements this kind of reconnection logic, mostly by hooking into the clientConnectionFailed factory method.  When this is called and the reason seems to you like that justifies switching servers (eg, twisted.internet.error.ConnectionRefused), pick the next address on your list and use the appropriate reactor.connectXYZ method to try connecting to it.
You could also try constructing this as an endpoint (which is the newer high-level connection setup API that is preferred by some), but handling reconnection with endpoints is not yet a well documented topic.


text:
Q: Dynamic Text Using JavaScript & PHP? I'm working on a little project, basically I have some text on my PHP/HTML page that is being echo'ed from a variable ($brief_string).
There is also a back, and continue button which basically subtracts or adds to another variable ($brief_page - which is pulled from my DB). The brief_string changes depending on the brief_page by using if statements. First problem I encounter is that when I hit continue (submit button) it resubmits/refreshes the page, causing my brief_page to reset back to 0.
So I'm thinking maybe I could use JS to hold the info and page variables and control the dynamic text, but then, how would I update my DB with the current page value via JS? Isn't it really easy to manually change/hack these values? I would preferably like my DB to be updated with the page number each time the use presses the back/continue button.
I would just like some advice really as I am a student trying to develop an interactive book like site (that uses a DB to save your current page).
Code:
<?
$brief_info = "brief info goes here";
$brief_page = 0; //< will soon be pulled off DB

if (isset($_GET['brief1Go'])) {
    $brief_page = $brief_page + 1;
}
else if (isset($_GET['brief1Back'])) {
    $brief_page = $brief_page - 1;
}

$breifController = "
    <form action=\"".$_SERVER['PHP_SELF']."\" method=\"POST\">
        <input type=\"submit\" name=\"brief1Back\" id=\"brief1Back\" value=\"BACK\" />
    </form>

    <form action=\"".$_SERVER['PHP_SELF']."\" method=\"POST\">
        <input type=\"submit\" name=\"brief1Go\" id=\"brief1Go\" value=\"CONTINUE\" />
    </form>";

if($brief_page == 0){
    $brief1_info = "Welcome Commander, you are currently viewing the Mission Control Brief page, here you can view all your missions that you need to complete in order to advance through your prestiges. You will need to follow your briefs carefully in order to succeed.

    ";
}
else if($brief_page == 1){
    $brief_info = "Okay, let me show you around the place ...";
}
else if($brief_page == 2){
    $brief_info = "brief is on 2";
}

?>

A: Why not just use get vars entirely?
yes, start at 0 unless $_GET['page'] is set...
$brief_page = 0;
if(isset($_GET['page']))
    $brief_page = $_GET['page'];

then only use links to your next and previous pages instead of some weird post thing.
<a href="/somefile.php?page=<?php echo $prev; ?>">Previous <a href="/somefile.php?page=<?php echo $next; ?>">Next

where obviously the page numbers in the previous and next are just echoed from php
$prev = $brief_page - 1;
$next = $brief_page + 1;

The user specific things to store can easily be handled with sesisons, cookies or even other get vars if you want to introduce a horrible security hole. Your choice really.
I would definitely not do this via $_POST though. totally annoying. Go with all full on ajax if you want to do that. At least you won't pester the user with "are you sure you want to resubmit the form data" messages if they choose to refresh the page.


text:
Q: Tilemap displaying incorrectly on iOS using Cocos2D I used Tiled to create a tilemap to use in one of my games for iOS; however, it displays incorrectly when I run it. I've tried making multiple different .tmx files with different file sizes for phone, phonehd, tablet, and tablethd. The tilemap is base64 zlib compressed, but I've also tried no compression and gzip compressed. I've included the code used to display it.
self.tileMap = [CCTiledMap tiledMapWithFile:@"assets/Test.tmx"];
[self addChild:_tileMap z:-1];

A: The problem was that instead of using a tileset, I was using a collection of images as a tileset in Tiled. Apparently that causes weird results with the tilemap in Cocos2D. It worked fine after using a sprite sheet.


text:
Q: Jenkins Build Error Missing: cn.guoyukun.jdbc:oracle-ojdbc6:jar:11.2.0.3.0 I am trying to build maven project using Jenkins.
bellow is my maven configuration in Jenkins

every thing looks fine to me but I am getting the bellow error

[ERROR] BUILD ERROR
[INFO] ------------------------------------------------------------------------
[INFO] Failed to resolve artifact.

Missing:
----------
1) cn.guoyukun.jdbc:oracle-ojdbc6:jar:11.2.0.3.0

----------
1 required artifact is missing.

for artifact:
  com.varun:myproject:war:0.0.1-SNAPSHOT

from the specified remote repositories:
  central (http://repo1.maven.org/maven2)

I can see the error is saying that maven is not able to resolve
cn.guoyukun.jdbc:oracle-ojdbc6:jar:11.2.0.3.0 jar file.
but in lib folder of my project I have kept above jar.
I tried multiple solution but dint work.
In Jenkins/job/maven i kept the jar. but this dint work also.
from some jenkins Google group I found some solution but not bale to fix it.
The solution

Try downloading the file manually from the project website.

 Then, install it using the command:
 mvn install:install-file -DgroupId=cn.guoyukun.jdbc -DartifactId=oracle-  ojdbc6 -Dversion=11.2.0.3.0 -Dpackaging=jar -Dfile=/path/to/file

 Alternatively, if you host your own repository you can deploy the file there:
 mvn deploy:deploy-file -DgroupId=cn.guoyukun.jdbc -DartifactId=oracle-    ojdbc6 -Dversion=11.2.0.3.0 -Dpackaging=jar -Dfile=/path/to/file -Durl=[url] -DrepositoryId=[id]

The above solution looks ok to me.
as mentioned in first solution I have that jar file and I am trying to install that jar. but I am getting command not found.
I dont know how to achieve the above solution. sorry for being dumb, I am totally new to Jenkins and maven.
can any body help me to achieve the above solution or any other solution is there.


text:
Q: how do I get my google sheet app verified with Google? I have a google sheet that takes several weeks from a staff schedule and post it to a shared calendar using apps script. I want to share this sheet and it's embedded script with my colleagues.
When it runs the first time they need to give it permissions until I "verify this app with Google". What does this mean and how do I go about it?
/thanks


text:
Q: Avoiding exposure to NullReferenceException when using LINQ to XML I am using a chain of calls to the XElement.Element() method to drill down into an XML document and pull out the value of an attribute:
XElement root = ...;
XNamespace ns = "...";
var firstName =
  root
    .Element(ns + "Employee")
    .Element(ns + "Identity")
    .Element(ns + "Name")
    .Attribute(ns + "FirstName");

However, since the incoming document has not been schema validated it is possible that a malformed document will cause a NullReferenceException if any of the expected intermediate elements does not exist.
Is there a way to avoid this risk, whilst keeping the code succinct?
I can wrap the code above in a handler for NullReferenceException however this feels wrong, and would also not specifically indicate where the failure occurred. Constructing an informative error message would be manual, tedious, error prone, and a maintenance hazard.
Should I be using XPath instead, that way I can check for a null return and then easily construct an error message indicating that the XPath expression could not be resolved?

A: One option is to use Elements() instead of Element() - which will yield an empty sequence if the element isn't found. Using the extension methods in Extensions, you can go from a sequence of elements to a sequence of elements - and the same for attributes. So:
var firstName =
  root
    .Elements(ns + "Employee")
    .Elements(ns + "Identity")
    .Elements(ns + "Name")
    .Attributes(ns + "FirstName")
    .FirstOrDefault();

There is a difference between the two snippets, mind you - this will find the first matching attribute even if it comes from (say) the first Name element within the third Identity element within the second Employee element. That may or may not be an issue for you.
(Just to check, do you definitely need the namespace on the attribute? Unlike elements, attributes don't inherit a "default" namespace. It's rarer to use attributes on namespaces than on elements.)

A: You can define en extension method to wrap the null detection. Something like this, for instance:
public static class XmlExtender
{
   public static XAttribute AttributeOrDefault(this XElement el, XName name, string defValue)
   {
      var v = el.Attribute(name);
      return v == null ? new XAttribute(name, defValue) : v;
   }

   public static string AttributeValue(this XElement el, XName name, string defValue)
   {
      var v = el.Attribute(name);
      return v == null ? defValue : v.Value;
   }
}

which can then be used like this:
var firstName = root.ELement("elname")
                    .AttributeOrDefault("attrName", "N/A").Value;

or this:
var firstName = root.Element("elname")
                    .AttributeValue("attrName", "N/A");


text:
Q: Show that $lim \frac{n^{2}}{n!} =0$ Please check my proof and point mistake
Consider
$$\frac{n^{2}}{n!} = \frac{n}{(n-1)!}$$
$$\frac{n}{(n-1)!} <  \frac{n}{(n-2)!}$$
Then
$$ \frac{n}{(n-2)!} <\epsilon for every n>N$$
$$ \frac{1}{\epsilon }< \frac{(n-2)!}{n} for every n>N$$
We choose $N=\frac{1}{\epsilon }$
Therefore
$$ \frac{(n-2)!}{n}>\frac{(N-2)!}{N}>\frac{n^{2}}{n!}>\frac{1}{\epsilon } $$
therefore limit converge to 0

A: You have that $$\frac{n^{2}}{n!} = \frac{n}{(n-1)!}.$$ Now, note that
$$\frac{n}{(n-1)!}=\frac{n}{n-1}\frac{1}{(n-2)!}\le \frac{2}{n-2}, \forall n\ge 2.$$
So, given $\epsilon>0$ we need to find $N$ such that $$n\ge N\implies \frac{2}{n-2}<\epsilon.$$ Well, $$\frac{2}{n-2}<\epsilon\iff n>\frac{2}{\epsilon}+2.$$
So, we have that
$$\forall\epsilon>0 \exists N \left(\ge \frac{2}{\epsilon}+2\right): n\ge N\implies 0<\frac{n^2}{n!}\le \frac{2}{n-2}<\epsilon.$$ This shows that the limit is zero.


text:
Q: Collapsing An Empty Ad I'm using an Ad service named Advoly. It's partner of Google ADx service. Here is its sample ad code.
<script type="text/javascript">
advoly_ad_client = "xxxxx";
advoly_ad_slot = "xxxxxxxxxx";
advoly_ad_width = 300;
advoly_ad_height = 250;
</script>
<script type="text/javascript"
src="//apps.advoly.com/proslot/cdn/ads.js">
</script>

Their system works like;
Whether they show ads on the site or not depends on position and importance of ad placement. That is, if you place your ad in a bad position, possibility to show ads is lower. There is a coefficient which determines this possibility.
When there is no ad because of this system, it shows an empty ad which occupies place as white space in design. How can I collapse this white space if there is no ad?
Thanks.

A: I assume it injects an iframe with the ad content? Then there is no way to detect whether the iframe has any ad content or not due to the cross origin policy. However, many ad networks allow you to specify content that should be shown if there is no ad.


text:
Q: Adding Delete button to custom list controller for ContentVersion I've been trying to have this code done with and finished for ages, and everytime I think I'm done, the person who wanted the code always adds an extra feature he'd like added in last minute. :T
In any case, I've gotten this far in my code for a custom controller and VisualForce page to display ContentVersion objects:
ContentVersionFiles.vfp:
<apex:page docType="html-5.0" readOnly="true" recordSetVar="{!content}" controller="ContentVersionController" showChat="false" showHeader="false" showQuickActionVfHeader="false" sidebar="false">
  <apex:includeScript id="console-js" value="/support/console/35.0/integration.js" />
  <apex:variable var="count" value="{!0}" />
  <apex:pageBlock title="Registration Scans" id="pageBlock">
    <apex:form id="topForm">

Page #: <apex:outputLabel value="{!PageNumber}"/> out of <apex:outputLabel value="{!totalPageNumber}"/>

        <apex:commandButton value="Previous" action="{!previousBtnClick}" reRender="pageBlock" disabled="{!previousButtonEnabled}" />
        <apex:commandButton value="Next" action="{!nextBtnClick}" reRender="pageBlock" disabled="{!nextButtonDisabled}" />

    </apex:form>
    <apex:panelBar id="scans">
      <apex:repeat var="cv" value="{!pageContent}">
        <apex:variable var="count" value="{!count + 1}" />
        <apex:panelBarItem id="barItem" label="{!cv.Title} - #{!count} of {!content.size}" onenter="autoResize(this.id)"></apex:panelBarItem>
      </apex:repeat>
    </apex:panelBar>
    <apex:form id="bottomForm">

Page #: <apex:outputLabel value="{!PageNumber}"/> out of <apex:outputLabel value="{!totalPageNumber}"/>

        <apex:commandButton value="Previous" action="{!previousBtnClick}" reRender="pageBlock" disabled="{!previousButtonEnabled}" />
        <apex:commandButton value="Next" action="{!nextBtnClick}" reRender="pageBlock" disabled="{!nextButtonDisabled}" />

    </apex:form>
  </apex:pageBlock>
</apex:page>

ContentVersionController.apxc:
public with sharing class ContentVersionController {
    public List<ContentVersion> pageContent { get; set; }
    public List<ContentVersion> content { get; set; }
    public String selectedContentId { get; set; }
    private ApexPages.StandardSetController controller;
    private Integer pageNumber;
    private Integer pageSize;
    private Integer totalPageNumber;

    public ContentVersionController() {
        //controller = new ApexPages.StandardSetController();
        pageNumber = 0;
        totalPageNumber = 0;
        pageSize = 20;
        ViewData();
    }

    public ContentVersionController(ApexPages.StandardSetController con) {
        controller = con;
        pageNumber = 0;
        totalPageNumber = 0;
        pageSize = 20;
        ViewData();
    }

    public List<ContentVersion> getContentVersions() {
        return [SELECT Id, Title, ContentDocumentId FROM ContentVersion
                WHERE IsLatest = true AND OwnerId = '005A0000003mkyk'];
    }

    public Integer getPageNumber() {
        return pageNumber;
    }

    public List<ContentVersion> getContent() {
        //return pageContent;
        return [SELECT Id, Title, ContentDocumentId FROM ContentVersion
                WHERE IsLatest = true AND OwnerId = '005A0000003mkyk'];
    }

    public Integer getPageSize() {
        return pageSize;
    }

    public Boolean getPreviousButtonEnabled() {
        return !(pageNumber > 1);
    }

    public Boolean getNextButtonDisabled() {
        if (content == null) {
            return true;
        } else {
            return ((pageNumber * pageSize) >= content.size());
        }
    }

    public Integer getTotalPageNumber() {
        if(totalPageNumber == 0 && content !=null) {
            totalPageNumber = content.size() / pageSize;
            Integer mod = content.size() - (totalPageNumber * pageSize);
            if(mod > 0) {
                totalPageNumber++;
            }
        }
        return totalPageNumber;
    }

    public PageReference ViewData() {
        content = null;
        totalPageNumber = 0;
        BindData(1);
        return null;
    }

    public void BindData(Integer newPageIndex) {
        try {
            if(content == null){
               content = [SELECT Id, Title, ContentDocumentId FROM ContentVersion
                          WHERE IsLatest = true AND OwnerId = '005A0000003mkyk'];
            }
            pageContent = new List<ContentVersion>();
            transient Integer counter = 0;
            transient Integer min = 0;
            transient Integer max = 0;
            if (newPageIndex > pageNumber) {
                min = pageNumber * pageSize;
                max = newPageIndex * pageSize;
            } else {
                max = newPageIndex * pageSize;
                min = max - pageSize;
                //min = min <>
            }
            for(ContentVersion c : content) {
                counter++;
                if (counter > min && counter <= max){
                    pageContent.add(c);
                }
            }
            pageNumber = newPageIndex;
            if (pageContent == null || pageContent.size() <= 0) {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, 'Data not available for this view.'));
            }
        } catch(Exception ex) {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.FATAL, ex.getMessage()));
        }
    }

    public PageReference nextBtnClick() {
        BindData(pageNumber + 1);
        pageNumber += 1;
        return null;
    }

    public PageReference previousBtnClick() {
        BindData(pageNumber - 1);
        pageNumber -= 1;
        return null;
    }

    public PageReference deleteBtnClick() {
        /* TODO: get current ContentDocumentId of a clicked-on(selected) ContentVersion record, and delete the ContentDocument associated with it,
           since you can't delete a ContentVersion via API calls. */
        return null;
    }
}

It took me a lot of work to get this working correctly, and I REALLY don't want to break anything, if at all possible. The way the VisualForce page works is that it will show all the ContentVersion records in a massive list of <apex:panelBar> elements, all closed by default, and only one ContentVersion is visible at a time when a user clicks on the given panel bar. Is there a way to add a delete button for each of the records? Or at least for the current record that's in view? I realize it'll need AJAX to handle reloading the content within the panel bars, but I'll handle that on my own. I just want to know if a delete functionality is possible in this setup. Can anyone help?

A: I've found the solution, but not in the way that I thought I would. Thankfully, either from recent updates to Salesforce, or simply due a lack of understanding on my part (the latter being more likely), the answer is to delete the parent ContentDocument record that is related to each ContentVersion:

*

*Generate a report of files that have been downloaded.

Or, run a SOQL query on ContentVersionHistory: SELECT Id, Title, ContentVersionId FROM ContentVersionHistory WHERE Field = 'contentVersionDownloaded'

Which ever way that lets you pull that data and insert it into a temporary relational database like MySQL or MariaDB.

*Run a similar query/report on all the ContentVersion records available to the library, and put this in a separate table within the temporary database.

REMEMBER: You NEED to include the ContentDocumentId for this query or you won't have any way to know which ContentDocument records will need to be removed. For example:
SELECT Id, ContentDocumentId, Title FROM ContentVersion WHERE FirstPublishLocationId IN (SELECT ParentId FROM ContentDocument)

*In the temporary database, run a INNER JOIN query to show a dataset of only the records that have been downloaded and exist in the given library. This is so you filter out any other files that you don't want deleted, or ones that exist outside of the library in question.

*Generate a CSV of that dataset from step 3. This is required so that you can just use the Apex Data Loader tool to mass delete the files, rather than use a delete button on each file individually. MySQL Workbench has a save functionality for SQL query results to be saved as a CSV.

*Be sure to run the Data Loader with enough heap space to actually function: Add -Xms1024m -Xmx1596m to either the command line batch file, or modify the shortcut that opens the tool to include these flags, or you will get Java heap space errors.


text:
Q: Did Auto-Bundling/Minification Get Tossed in Final Release of MVC 4? According to an article I read earlier by Scott Guthrie, and a video posted by Mads Kristensen, I should be able to auto-bundle/minify in ASP.net MVC 4 by replacing this:
<link href="Styles/reset.css" rel="stylesheet" type="text/css" />
<link href="Styles/normalize.css" rel="stylesheet" type="text/css" />
<link href="Styles/styles.css" rel="stylesheet" type="text/css" />

<script src="Scripts/jquery-1.8.0.min.js" type="text/javascript"></script>
<script src="Scripts/jquery-validation.min.js" type="text/javascript"></script>

With this:
<link href="Styles/css" rel="stylesheet" type="text/css" />

<script src="Scripts/js" type="text/javascript"></script>

I've tried targeting both .Net 4.0 and 4.5 and it doesn't seem to make a difference. I get 404 errors and the link and script tags are never directed at the bundled resources.
Did this feature get dropped from the final version?
I'd like to utilize this feature for "Themes".

This is how I ended up implementing. Hopefully it makes sense...
 /// <summary>
 /// Render stylesheets HTML for the given theme. Utilizes System.Web.Optimization for bundling and minification
 /// </summary>
 /// <param name="themeName">Name of theme</param>
 /// <returns>HtmlString containing link elements</returns>
 public static IHtmlString RenderThemeStyles(string themeName)
 {
     IHtmlString retValue = null;

     // If no theme name is passed, return null
     if (!themeName.HasValue())
         return retValue;

     var ctxt = HttpContext.Current;
     string themePath = "~/Themes/" + themeName;
     string themeKey = themePath + "/css";

     if (ctxt.Cache[themeKey] != null)
         return (IHtmlString)ctxt.Cache[themeKey];

     // Check to see if the theme directory exists. Throw error if it does not
     string themeSysPath = HttpContext.Current.Server.MapPath(themePath);
     DirectoryInfo themeDir = new DirectoryInfo(themeSysPath);
     if (!themeDir.Exists)
         throw new ApplicationException(string.Format("Theme directory \"{0}\" does not exist", themePath));

     // Remove the old bundle if it already exists
     var old_bundle = BundleTable.Bundles.FirstOrDefault(b => b.Path == themeKey);
     if (old_bundle != null)
         BundleTable.Bundles.Remove(old_bundle);

     if (themeDir.GetFiles("*.css").Length > 0)
     {
         // If there are css files, add them to the bundler and save the rendered output to cache
         Bundle styles = new StyleBundle(themeKey).IncludeDirectory(themePath, "*.css");
         BundleTable.Bundles.Add(styles);
         retValue = Styles.Render(themeKey);
         ctxt.Cache.Insert(themeKey, retValue, new System.Web.Caching.CacheDependency(themeSysPath));
     }
     else
     {
         // If there are no css files, save empty string to cache
         ctxt.Cache.Insert(themeKey, new HtmlString(string.Empty), new System.Web.Caching.CacheDependency(themeSysPath));
     }

     return retValue;
 }

A: Yes, this feature is removed in the MVC4 RC version although I could not find the RC release notes anymore.
Rick Anderson 's blog post on upgrade MVC4 beta to RC describes the process:
Remove the "autobundling" references and create/copy a BundleConfig.cs with your bundle configs and call it from Global.asax with BundleConfig.RegisterBundles(BundleTable.Bundles);.
Hanselman mentions some backround info about the decision:

There's been some significant changes to the web optimization
  (minification and bundling) framework since beta. There wasn't enough
  control over what was bundled and in what order in the beta, so that's
  been moved into a BundleConfig.cs (or .vb) where you have total
  control

A: Not exactly, so we removed EnableDefaultBundles which is what you refer to 'autobundling', but the underlying functionality is still there.
You can do the equivalent of what that method was doing by registering:
BundleTable.Bundles.Add(new DynamicFolderBundle("js", "*.js");
BundleTable.Bundles.Add(new DynamicFolderBundle("css", "*.css");

We removed the method since this is a fairly problematic approach as alphabetical ordering is not usually the desired ordering.


text:
Q: How to pass data from an native application (AdiIRC, an IRC client) to my Chrome extension? I use Chrome 79 and and Nodejs 13, in windows 10.
I also use an IRC client, AdiIRC, to connect to some IRC channel. This program can call external programs with arguments via its scripting language (via Run and $exec ).
So, what I want to do is, probably using Native Messaging, whenever a specific message appears in the IRC channel,
it to be passed as argument from AdiIRC to my Chrome extension, most probably via something like:  Run \path\to\some_executable.exe %message
where "some_executable.exe" would send the wanted message data (using stdout) to the extension .
So, my question is, how can I pass data from AdiIRC to my Chrome extension? Is it possible?
Am I entirely missing something regarding the Native Messaging concept, and so, what I want to do is possible via a different way??

Below is my effort, i.e. my Chrome extension and a native messaging host.
Note:  in Google's Native Messaging documentation, at some point is says that:

Chrome starts each native messaging host in a separate process and
  communicates with it using standard input (stdin) and standard output
  (stdout).

So, from what I understand from that,
in order to be able to pass data from AdiIRC to my extension whenever needed, I need AdiIRC to manually launch another instance of NativeMessaging.js .
So, to test my theory, I launched node "C:\MDN\app\NativeMessaging.js" manually, outside of Chrome (after loading my extension in Chrome), and tried entering random test text inside it,  but unfortunately they are not received in my extension's background.html page|Console .

background.js (of my Chrome extension) :
var port = chrome.runtime.connectNative('my_messaging_host');

port.onMessage.addListener((message) => {
  console.log("Received: " + message);
});

Native Messaging host setup:
install-host.bat
REG ADD "HKCU\Software\Google\Chrome\NativeMessagingHosts\my_messaging_host" /ve /t REG_SZ /d "%~dp0my_messaging_host.json" /f

my_messaging_host.json
{
  "name": "my_messaging_host",
  "description": "Example host for native messaging",
  "path": "C:\\MDN\\app\\my_messaging_host_win.bat",
  "type": "stdio",
  "allowed_origins": [
    "chrome-extension://(my extension's hash)/"
  ]
}

my_messaging_host_win.bat
node "C:\MDN\app\NativeMessaging.js"

NativeMessaging.js  ( NodeJS code from MDN )
#!/usr/local/bin/node

process.stdin.on('readable', () => {
    var input = [];
    var chunk;
    while (chunk = process.stdin.read()) {
        input.push(chunk);
    }
    input = Buffer.concat(input);

    var msgLen = input.readUInt32LE(0);
    var dataLen = msgLen + 4;

    if (input.length >= dataLen) {
        var content = input.slice(4, dataLen);
        var json = JSON.parse(content.toString());
        handleMessage(json);
    }
});

function sendMessage(msg) {
    var buffer = Buffer.from(JSON.stringify(msg));

    var header = Buffer.alloc(4);
    header.writeUInt32LE(buffer.length, 0);

    var data = Buffer.concat([header, buffer]);
    process.stdout.write(data);
}

process.on('uncaughtException', (err) => {
    sendMessage({error: err.toString()});
});

Possible addition to NativeMessaging.js, in case it's to be run with an argument:
e.g. via node NativeMessaging.js messageToSend
sendMessage(process.argv[2]);


text: Q: Funcion para navegar dentro de una misma pagina sin usar Scroll Imaginate que tengo una pagina que tiene las siguientes lineas en la parte de abajo o final  de la pagina, lo que nesecito es una funcion que al ejecutar muestre el contenido en la pantalla que el cliente no tenga que usar el scoll para poder verlo


text:
Q: How to properly include header C++ files (from ALGLIB) in Matlab MEX files I am struggling to get a mexfunction in MATLAB to work from C++ file. Below you can find my code first the mex file to compile and call and a header and the corresponding cpp file.
And now I have 2 questions:

*

*A basic question; that code compiles and runs, but normaly I have learned to include the header files
#include "Test.h"      instead of      #include "Test.cpp"     in the cSpl_CPP.cpp file. But if I do so I get the following error, so I assume it does not find the Test function. Why is that so?

    Error using mex
    C:\Users\XXX\AppData\Local\Temp\mex_26596607590260_19292\cSpl_CPP.obj:cSpl_CPP.cpp:(.text+0x35):
    undefined reference to `Test()'
    collect2.exe: error: ld returned 1 exit status

*

*Further this is just a basic test to implement the ALGLIB C++ files, which is a numerical analysis C++ code. The part I want to implement can be found in the Test.h header file within #include "interpolation.h".  If I uncomment      //real_1d_array x_old = "[-1.0,-0.5,0.0,+0.5,+1.0]";    in the Test.cpp file, the function should access the interpolation.h enviroment to use any necessary function within the namespace alglib. But it returns the following error. Seems to me the same problem as above, it does not find the function. Why? By the way calling all this within a C++ enviroment does work, of course with an abstracted cSpl_CPP.cpp file.

    Error using mex
    C:\Users\XXX\AppData\Local\Temp\mex_27656676634838_19292\cSpl_CPP.obj:cSpl_CPP.cpp:(.text+0x8f):
    undefined reference to `alglib::real_1d_array::real_1d_array(char const*)'
    C:\Users\XXX\AppData\Local\Temp\mex_27656676634838_19292\cSpl_CPP.obj:cSpl_CPP.cpp:(.text+0xb0):
    undefined reference to `alglib::real_1d_array::~real_1d_array()'
    C:\Users\XXX\AppData\Local\Temp\mex_27656676634838_19292\cSpl_CPP.obj:cSpl_CPP.cpp:(.text+0xf7):
    undefined reference to `alglib::real_1d_array::~real_1d_array()'
    collect2.exe: error: ld returned 1 exit status

Just to avoid any problems with the compilation command; I use:
    ipath = ['-I' fullfile(pwd,'cSpl','src')]; %Folder where the c & h files except cSpl_CPP.cpp are located
    mex(ipath,'cSpl_CPP.cpp')

Hoewever, putting everything in the same folder doesn't change anything.
That works for Question 1, so it seems to  have the correct folder included, as it does find the Test.cpp, though obviously not the Test.h...
For me it seems like I have a general problem including header files, but I don't know which one. Has any one an idea how to solve that issue???
Thanks a lot guys!
Greetings from Germany
Pablo
Mex-Function called cSpl_CPP.cpp to compile and call:
#include "math.h"
#include "matrix.h"
#include "mex.h"
#include "Test.cpp"
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    mexPrintf("Hello World!\n"); // prints !!!Hello World!!!
    int res;
    res = Test();
    mexPrintf("Hello World @%d!\n",res); // prints !!!Hello World!!!
    return;
}

Test header file Test.h:
#ifndef TEST_H_
#define TEST_H_

#include "interpolation.h"
using namespace alglib;
#include <iostream>
using namespace std;

int Test();

#endif /* TEST_H_ */

Test cpp file Test.cpp:
#include "Test.h"
int Test()
{
    int c = 55;
    cout << "Test works!" << endl;
    //real_1d_array x_old = "[-1.0,-0.5,0.0,+0.5,+1.0]";
    cout << "worked good\n";
    return c;
}

A: Well actually the solution is to compile all cpp files that you will possibly use according to the command in Matlab, having all files in the same folder:
File = 'cSpl_CPP.cpp'; % Mexfunction
list = dir('**/*.cpp'); % Collect all cpp files
cppfiles = {list.name}; % Gather file names
cppfiles(find(strcmp(cppfiles,File))) = []; % delete the Mexfuntion from list
cppfiles = {File,cppfiles{:}}; % Put the Mexfuntion on the first position
mex(cppfiles{:}); % compile all files

of course all #include commands only contain *.h - files.


text:
Q: Multi set in c++ and oops Start with the person class, and create a multiset to hold pointers to person
objects. Define the multiset with the comparePersons function object, so it will
be sorted automatically by names of persons. Define a half-dozen persons, put
them in the multiset, and display its contents. Several of the persons should
have the same name, to verify that the multiset stores multiple objects with the
same key.
PROBLEM: I am unable to sort the multiset and I am not sure why.
Code:
// sorts person objects stored by pointer
#include <iostream>
#include <algorithm>
#include <string>
#include <set> //addded---------------------------------------------
using namespace std;

class person
{
private:
   string lastName;
   string firstName;
   long phoneNumber;
public:
   // default constructor
   person() :lastName("blank"), firstName("blank"), phoneNumber(0L)
   { }
   // 3-arg constructor
   person(string lana, string fina, long pho) :
       lastName(lana), firstName(fina), phoneNumber(pho)
   { }
   friend bool operator<(const person&, const person&);
   friend bool operator==(const person&, const person&);

   void display() const // display person's data
   {
       cout << endl << lastName << ",\t" << firstName
           << "\t\tPhone: " << phoneNumber;
   }
   long get_phone() const // return phone number
   {
       return phoneNumber;
   }
}; //end class person
//--------------------------------------------------------------
// overloaded < for person class
bool operator<(const person& p1, const person& p2)
{
   if (p1.lastName == p2.lastName)
       return (p1.firstName < p2.firstName) ? true : false;
   return (p1.lastName < p2.lastName) ? true : false;
}
//--------------------------------------------------------------
// overloaded == for person class
bool operator==(const person& p1, const person& p2)
{
   return (p1.lastName == p2.lastName &&
       p1.firstName == p2.firstName) ? true : false;
}
//--------------------------------------------------------------
// function object to compare persons using pointers
class comparePersons
{
public:
   bool operator() (const person* ptrP1, const person* ptrP2) const
   {
       return *ptrP1 < *ptrP2;
   }
};
//--------------------------------------------------------------
//function object to display a person, using a pointer
class displayPerson
{
public:
   void operator() (const person* ptrP) const
   {
       ptrP->display();
   }
};
////////////////////////////////////////////////////////////////
int main()
{
   //make persons
   person* ptrP1 = new person("KuangThu", "Bruce", 4157300);
   person* ptrP2 = new person("Deauville", "William", 8435150);
   person* ptrP3 = new person("Wellington", "John", 9207404);
   person* ptrP4 = new person("Bartoski", "Peter", 6946473);
   person* ptrP5 = new person("Fredericks", "Roger", 7049982);
   person* ptrP6 = new person("McDonald", "Stacey", 7764987);
   person* ptrP7 = new person("KuangThu", "Bruce", 4157300);
   person* ptrP8 = new person("Deauville", "William", 8435150);

   //Creating multiset
   multiset<person*> multiPtrsPers;
   multiPtrsPers.insert(ptrP1);
   multiPtrsPers.insert(ptrP2);
   multiPtrsPers.insert(ptrP3);
   multiPtrsPers.insert(ptrP4);
   multiPtrsPers.insert(ptrP5);
   multiPtrsPers.insert(ptrP6);
   multiPtrsPers.insert(ptrP7);
   multiPtrsPers.insert(ptrP8);

   for_each(multiPtrsPers.begin(),multiPtrsPers.end(), displayPerson());//display person
   cout << endl;

   sort(multiPtrsPers.begin(), multiPtrsPers.end(), comparePersons());//compare persons

   for_each(multiPtrsPers.begin(), multiPtrsPers.end(), displayPerson());//display persons
   cout << endl;

   system("pause");
   return 0;
} end main()

A: Your comparer should go in multiset type:
multiset<person*, comparePersons> multiPtrsPers;

Demo
(multi)set cannot be reordered by other comparison afterward.
You cannot call sort on that container.

A: Sets cannot be sorted because they use an internal ordering in order to quickly locate and insert elements. Sorting the set externally would break this.
Instead, if you refer to the documentation, you find that you can adjust the ordering yourself:
template<
    class Key,
    class Compare = std::less<Key>,
    class Allocator = std::allocator<Key>
> class multiset;

Which means that what you want is:
std::multiset<person*, comparePersons> multiPtrsPers;


text:
Q: Google Maps Images Outdated When using the API the images in some situations are outdated compared to what is provided in the public Google Maps interface.
Is there anything we can do about this?
Regards
Jeremy

A: No, there isn't anything you can do about that, other than possibly to select different versions of the Maps API or to select the "visual refresh" in the API.
The Maps API and the Google Maps site don't use the same map tiles and imagery. Much is common between the two, and they tend to sync up over time, but it will always vary as new releases of each come out.


text:
Q: How can I download a file from a site that is protected with a username and password, using the Selenium framework? I am trying to download a file from a site that is protected with a username and password, using Selenium.
First, I got the href attribute from the download link:
WebElement downloadLinkElement = htmlElement.findElement(By.xpath(<xpath_value>));
    String url = downloadLinkElement.getAttribute("href");

Secondly, I got the "AUTHSESSION" cookie using the Selenium web driver:
org.openqa.selenium.Cookie cookie = webDriver.manage().getCookieNamed("AUTHSESSION");

Then I built a string that includes a Linux "wget" command, like so (I'm using apache commons exec artifact for this):
CommandLine cmdLine = new CommandLine("wget");
        cmdLine.addArgument("--cookies=on");
        cmdLine.addArgument("--header");
        cmdLine.addArgument("Cookie: AUTHSESSION=" + cookie.getValue());
        cmdLine.addArgument("-O");
        cmdLine.addArgument("/home/name/Downloads/file.ftl");
        cmdLine.addArgument(url);
        cmdLine.addArgument("--no-check-certificate");

Finally, I execute the command, and extract the execution output:
DefaultExecutor executor = new DefaultExecutor();
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        PumpStreamHandler streamHandler = new PumpStreamHandler(byteArrayOutputStream);
        executor.setStreamHandler(streamHandler);
        try {
            executor.execute(cmdLine);
        }catch(ExecuteException ee){
            ee.printStackTrace();
            System.out.println(byteArrayOutputStream.toString());
        }

After the execution, the file is downloaded to the specified path. But it is not the desired one. It is an html file with the login page of the site I'm trying to download from.
The following is a string contained within the execution output:
WARNING: cannot verify <ip_address>'s certificate, issued by <company_details>
  Self-signed certificate encountered.
WARNING: no certificate subject alternative name matches
    requested host name '<ip_address>'.
HTTP request sent, awaiting response... 302

An important note is that if I run the following command in the Linux terminal, the file is downloaded successfully:
wget --cookies on --header "Cookie: AUTHSESSION=<cookie_value>" -O "<download_path>" "<url>"
--no-check-certificate

What am I missing ?

A: So, I changed the approach a bit.
Before I initialize the firefox web driver, I first create a FirefoxOptions object, like so:
    FirefoxOptions firefoxOptions = new FirefoxOptions();
    firefoxOptions.addPreference("browser.helperApps.neverAsk.saveToDisk", "text/plain");

After that, I insert this object within the firefox driver constructor:
WebDriver driver = new FirefoxDriver(firefoxOptions);

After you click on the download link, the file is stored in the disk, with no questions asked by the browser.


text:
Q: Saving associated domain classes in Grails I'm struggling to get association right on Grails. Let's say I have two domain classes:
class Engine {
    String name
    int numberOfCylinders = 4
    static constraints = {
        name(blank:false, nullable:false)
        numberOfCylinders(range:4..8)
    }
}

class Car {
    int year
    String brand
    Engine engine = new Engine(name:"Default Engine")
    static constraints = {
        engine(nullable:false)
        brand(blank:false, nullable:false)
        year(nullable:false)
    }
}

The idea is that users can create cars without creating an engine first, and those cars get a default engine. In the CarController I have:
def save = {
    def car = new Car(params)
    if(!car.hasErrors() && car.save()){
        flash.message = "Car saved"
        redirect(action:index)
    }else{
        render(view:'create', model:[car:car])
    }
}

When trying to save, I get a null value exception on the Car.engine field, so obviously the default engine is not created and saved. I tried to manually create the engine:
def save = {
    def car = new Car(params)
    car.engine = new Engine(name: "Default Engine")
    if(!car.hasErrors() && car.save()){
        flash.message = "Car saved"
        redirect(action:index)
    }else{
        render(view:'create', model:[car:car])
    }
}

Didn't work either. Is Grails not able to save associated classes? How could I implement such feature?

A: I think you need a belongsTo in your Engine ie
static belongsTo = [car:Car]

Hope this helps.

A: For what is worth, I finally nailed it.
The exception I got when trying to save a car was

not-null property references a null or
  transient value

It was obvious that the engine was null when trying to save, but why? Turns out you have to do:
def car = new Car(params)
car.engine = new Engine(name: "Default Engine")
car.engine.save()

Since engine doesn't belongs to a Car, you don't get cascade save/update/delete which is fine in my case. The solution is to manually save the engine and then save the car.


text:
Q: NSInvalidArgumentException - "unrecognized selector sent to instance " getting error when passing json data IOS7 Hi in my application I'm trying to passing json data in to my tableview but its showing like unrecognized selector sent to instance like this.
I have a json data like this.
"youtube_videos":[{"id":"1","name":"Little Flower Public School","youtube":"FFTi2Sl8hHw","link":"http:\/\/img.youtube.com\/vi\/FFTi2Sl8hHw\/default.jpg"}]

This json have to youtube video id and thumbnail image of the video now I'm trying to view the thumbnail image in my imageview in my tableview but its giving error like
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance 0xa72e290

This is the code have used to get the json data .
    -(void) retrieveData
     {
      NSURL * url = [NSURL URLWithString:getDataURL];
      NSData * data = [NSData dataWithContentsOfURL:url];

       json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];

       imgarray =[[NSMutableArray alloc]init];

      for (int i=0; i<json.count; i++) {

       NSString * dd = [[json objectAtIndex:i]objectForKey:@"youtube"];
       NSString * sspp = [[json objectAtIndex:i]objectForKey:@"link"];
       NSString * plae =[[json objectAtIndex:i]objectForKey:@"name"];
       NSLog(@"%@",dd);

       vv *myimg =[[vv alloc]initWithvideo:dd andtitle:plae andlink:sspp];

       [imgarray addObject:myimg];

    }

     [self.mytableview reloadData];

My Json NSlog.
json :{
"youtube_videos" =     (
            {
        id = 1;
        link = "http://img.youtube.com/vi/FFTi2Sl8hHw/default.jpg";
        name = "Little Flower Public School";
    },
            {
        id = 2;
        link = "http://img.youtube.com/vi/4oI7xC2wSpw/default.jpg";
        name = "Little Flower Public School";
    },
            {
        id = 3;
        link = "http://img.youtube.com/vi/XCPKMWyF1Lo/default.jpg";
        name = Function;
    }
  );
}

Please Tell me how to resolve this issue i have stuck here for long .
Thanks.

A: I think you should update your code as like below. Because of  your JSON looks like a Dictionary.
-(void) retrieveData
{
    NSURL * url = [NSURL URLWithString:getDataURL];

    NSData * data = [NSData dataWithContentsOfURL:url];

    id json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];

    imgarray = [[NSMutableArray alloc]init];

    NSArray * respArray = [json objectForKey:@"youtube_videos"];

    for (int i=0; i<respArray.count; i++)
    {

        NSString * dd = [[respArray objectAtIndex:i]objectForKey:@"youtube"];

        NSString * sspp = [[respArray objectAtIndex:i]objectForKey:@"link"];

        NSString * plae =[[respArray objectAtIndex:i]objectForKey:@"name"];

        NSLog(@"%@",dd);

        vv *myimg =[[vv alloc]initWithvideo:dd andtitle:plae andlink:sspp];

        [imgarray addObject:myimg];

    }

    [self.mytableview reloadData];
}

A: Not sure what your response is. Do you get single or multiple records in the json response.
Try this code:
-(void) retrieveData
 {
  NSURL * url = [NSURL URLWithString:getDataURL];
  NSData * data = [NSData dataWithContentsOfURL:url];

   json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];

   imgarray =[[NSMutableArray alloc]init];
   NSString * dd = [json objectForKey:@"youtube"];
   NSString * sspp = [json objectForKey:@"link"];
   NSString * plae =[json objectForKey:@"name"];
   NSLog(@"%@",dd);

   vv *myimg =[[vv alloc]initWithvideo:dd andtitle:plae andlink:sspp];

   [imgarray addObject:myimg];

 [self.mytableview reloadData];
 }


text:
Q: How do I modify environment variables between tests at runtime with pytest? I have a use case where I have several functions which depend on the environment (dev/staging/prod). I pre load these into a variable (in this case ENV) and is used across my util functions.
Following is an MWE.
.env
MYENV=staging

config.py
import os
import dotenv

dotenv.load_dotenv()

ENV = os.environ.get("MYENV")

util.py
from config import ENV

def resolve_db(db: str) -> str:
    return f"{ENV}_" + db

conftest.py
import pytest

@pytest.fixture(scope="function")
def dev_env(monkeypatch):
    monkeypatch.setenv("MYENV", "dev")

@pytest.fixture(scope="function")
def staging_env(monkeypatch):
    monkeypatch.setenv("MYENV", "staging")

@pytest.fixture(scope="function")
def prod_env(monkeypatch):
    monkeypatch.setenv("MYENV", "prod")

test_util.py
from util import resolve_db
import os

def test_resolve_db_dev(dev_env):
    assert resolve_db("stackoverflow") == "dev_stackoverflow"

def test_resolve_db_staging(staging_env):
    assert resolve_db("stackoverflow") == "staging_stackoverflow"

def test_resolve_db_prod(prod_env):
    assert resolve_db("stackoverflow") == "prod_stackoverflow"

$ pytest
===================================================================== test session starts =====================================================================
platform linux -- Python 3.10.4, pytest-7.1.1, pluggy-1.0.0
rootdir: /mnt/c/Users/name/PROJECTS/test-pytest-env
plugins: anyio-3.5.0, cov-3.0.0, deadfixtures-2.2.1, html-3.1.1, metadata-1.11.0, timeout-2.1.0
collected 3 items

test_util.py F.F                                                                                [100%]

========================================================================== FAILURES ===========================================================================
_____________________________________________________________________ test_resolve_db_dev _____________________________________________________________________

dev_env = None

    def test_resolve_db_dev(dev_env):
>       assert resolve_db("stackoverflow") == "dev_stackoverflow"
E       AssertionError: assert 'staging_stackoverflow' == 'dev_stackoverflow'
E         - dev_stackoverflow
E         + staging_stackoverflow

test_util.py:5: AssertionError
____________________________________________________________________ test_resolve_db_prod _____________________________________________________________________

prod_env = None

    def test_resolve_db_prod(prod_env):
>       assert resolve_db("stackoverflow") == "prod_stackoverflow"
E       AssertionError: assert 'staging_stackoverflow' == 'prod_stackoverflow'
E         - prod_stackoverflow
E         + staging_stackoverflow

test_util.py:11: AssertionError
=================================================================== short test summary info ===================================================================
FAILED test_util.py::test_resolve_db_dev - AssertionError: assert 'staging_stackoverflow' == 'dev_stackoverflow'
FAILED test_util.py::test_resolve_db_prod - AssertionError: assert 'staging_stackoverflow' == 'prod_stackoverflow'
================================================================= 2 failed, 1 passed in 0.08s =================================================================

I don't understand how I can monkeypatch the ENV variable at runtime to help with my tests.


text:
Q: Select until in MySQL I have this table the contains user_id and father_id.
I want to select all the father_ids that are associated with the user_id until the value of the father_id = 0 and store them in a comma-separated format.
Table: network
select user_id, father_id from network where user_id = 1762;

user_id father_id
1762    1761

select user_id, father_id from network where user_id = 1761; -- resulting father_id from the first query

user_id father_id
1761    1760

select user_id, father_id from network where user_id = 1760; -- resulting father_id from the second query

user_id father_id
1760    0

In this example, I want to get all the father_ids until i reached father_id = 0 by using the resulting father_id as the next user_id.


text:
Q: Incomplete type not allowed error for built in array When i am trying to declare this cursed array it tells me incomplete type not allowed, i have made it myself and when it didn't work for no reason i got the same piece of code from the tutorial i'm following (lessons on a site) and it still didn't work , any help ?
#include <iostream>
enum CardSuit
{
    SUIT_CLUB,
    SUIT_DIAMOND,
    SUIT_HEART,
    SUIT_SPADE,
    MAX_SUITS
};

enum CardRank
{
    RANK_2,
    RANK_3,
    RANK_4,
    RANK_5,
    RANK_6,
    RANK_7,
    RANK_8,
    RANK_9,
    RANK_10,
    RANK_JACK,
    RANK_QUEEN,
    RANK_KING,
    RANK_ACE,
    MAX_RANKS
};
struct Card
{
    CardRank rank;
    CardSuit suit;
};

int main()
{
std::array<Card, 52> deck {};

    for (int suit = 0; suit < MAX_SUITS; ++suit)
        for (int rank = 0; rank < MAX_RANKS; ++rank)
        {
            deck[card].suit = static_cast<CardSuit>(suit);
            deck[card].rank = static_cast<CardRank>(rank);
            ++card;
        }

    return 0;
}

A: You need to #include <array>
Also:
These are wrong:
        deck[card].suit = static_cast<CardSuit>(suit);
        deck[card].rank = static_cast<CardRank>(rank);

Indexing (deck[ index ]) should be done using integral types, and card is not declared.
size_t card=0; // add this

for (int suit = 0; suit < MAX_SUITS; ++suit)
    for (int rank = 0; rank < MAX_RANKS; ++rank)
    {
        deck[card].suit = static_cast<CardSuit>(suit);
        deck[card].rank = static_cast<CardRank>(rank);
        ++card;
    }


text:
Q: Python listening and analyzing data at the same time TL;DR- Python listens to live audio and reacts accordingly on the go.
I am a complete beginner to Python, this is my first idea i'd love to work on. So it all began with me "hacking" my LED strips i have connected to WiFi. I can easily switch their color by launching a file and make them do certain pattern one time (haven't tried repeated/infinite patterns). My goal is to make it listen to music played on computer (essentially listen to system sounds one could say) and analyze the low bands and depending on the intensity of them, change the LED colors. As example music plays and lights switch color on each beat.
I haven't tried anything so far.
Lights work completely fine as i enter custom RGB and brightness values.


text:
Q: PL/SQL procedure for inner join and where clause I want to create PL/SQL stored procedure for following query:
SELECT order_id, order_date,  customer_id
FROM Orders
INNER JOIN Customers ON Orders.customer_id = Customers.customer_id
WHERE order_id = xyz;

I want to pass order_id as input parameter in stored procedure.
Can someone please share the PL/SQL code for this?

A: Try this function
   CREATE OR REPLACE FUNCTION fn_test(p1 IN NUMBER)
    RETURN VARCHAR2
    IS

    s_query_stmt     VARCHAR2(1000 CHAR);
    r1               VARCHAR2(100 CHAR);
    r2               VARCHAR2(100 CHAR);
    r3               VARCHAR2(100 CHAR);

   BEGIN

   s_query_stmt := 'Select order_id, order_date, customer_id
                    From Orders inner join Customers
                    On Orders.customer_id = Customers.customer_id
                   WHERE order_id = :x )';

   EXECUTE IMMEDIATE s_query_stmt INTO r1, r2, r3 USING p1;
   return 'x';

  END;

A: The most simple form of a procedure that would return those values is like this (:
create or replace procedure retrieve_order_values(
  p_order_id IN Orders.order_id%type
, p_order_date OUT Orders.order_date%type
, p_customer_id OUT Orders.customer_id%type
)
is
begin
  select order_date, customer_id
  into p_order_date, p_customer_id
  from orders
  where order_id = p_order_id;
end retrieve_order_values;

Please note that you do not need the join to the Customers table to retrieve the customer_id.


text:
Q: Expected return and covariance from return time series I'm trying to simulate the Matlab ewstats function here defined:
https://it.mathworks.com/help/finance/ewstats.html
The results given by Matlab are the following ones:
> ExpReturn = 1×2
0.1995    0.1002

> ExpCovariance = 2×2
0.0032   -0.0017
-0.0017    0.0010

I'm trying to replicate the example with the RiskPortfolios R package:
https://cran.r-project.org/web/packages/RiskPortfolios/RiskPortfolios.pdf
The R code I'm using is this one:
library(RiskPortfolios)

rets <- as.matrix(cbind(c(0.24, 0.15, 0.27, 0.14), c(0.08, 0.13, 0.06, 0.13)))
w <- 0.98

rets
w
meanEstimation(rets, control = list(type = 'ewma', lambda = w))
covEstimation(rets, control = list(type = 'ewma', lambda = w))

The mean estimation is the same of the one in the example, but the covariance matrix is different:
> rets
     [,1] [,2]
[1,] 0.24 0.08
[2,] 0.15 0.13
[3,] 0.27 0.06
[4,] 0.14 0.13
> w
[1] 0.98
>
> meanEstimation(rets, control = list(type = 'ewma', lambda = w))
[1] 0.1995434 0.1002031
>
> covEstimation(rets, control = list(type = 'ewma', lambda = w))
             [,1]         [,2]
[1,]  0.007045044 -0.003857217
[2,] -0.003857217  0.002123827

Am I missing something?
Thanks

A: They give the same answer if type = "lw" is used:
round(covEstimation(rets, control = list(type = 'lw')), 4)

##   0.0032 -0.0017
##  -0.0017  0.0010

A: They are using different algorithms. From the RiskPortfolio manual:

ewma ... See RiskMetrics (1996)

From the Matlab hlp page:

There is no relationship between ewstats function and the RiskMetrics® approach for determining the expected return and covariance from a return time series.

Unfortunately Matlab does not tell us which algorithm is used.

A: For those who eventually need an equivalent ewstats function in R, here the code I wrote:
ewstats <- function(RetSeries, DecayFactor=NULL, WindowLength=NULL){

  #EWSTATS Expected return and covariance from return time series.
  #   Optional exponential weighting emphasizes more recent data.
  #
  #   [ExpReturn, ExpCovariance, NumEffObs] = ewstats(RetSeries, ...
  #                                           DecayFactor, WindowLength)
  #
  #   Inputs:
  #     RetSeries : NUMOBS by NASSETS matrix of equally spaced incremental
  #     return observations.  The first row is the oldest observation, and the
  #     last row is the most recent.
  #
  #     DecayFactor : Controls how much less each observation is weighted than its
  #     successor.  The k'th observation back in time has weight DecayFactor^k.
  #     DecayFactor must lie in the range: 0 < DecayFactor <= 1.
  #     The default is DecayFactor = 1, which is the equally weighted linear
  #     moving average Model (BIS).
  #
  #     WindowLength: The number of recent observations used in
  #     the computation.  The default is all NUMOBS observations.
  #
  #   Outputs:
  #     ExpReturn : 1 by NASSETS estimated expected returns.
  #
  #     ExpCovariance : NASSETS by NASSETS estimated covariance matrix.
  #
  #     NumEffObs: The number of effective observations is given by the formula:
  #     NumEffObs = (1-DecayFactor^WindowLength)/(1-DecayFactor).  Smaller
  #     DecayFactors or WindowLengths emphasize recent data more strongly, but
  #     use less of the available data set.
  #
  #   The standard deviations of the asset return processes are given by:
  #   STDVec = sqrt(diag(ECov)).  The correlation matrix is :
  #   CorrMat = VarMat./( STDVec*STDVec' )
  #
  #   See also MEAN, COV, COV2CORR.

  NumObs <- dim(RetSeries)[1]
  NumSeries <- dim(RetSeries)[2]

  # size the series and the window
  if (is.null(WindowLength)) {
    WindowLength <- NumObs
  }

  if (is.null(DecayFactor)) {
    DecayFactor = 1
  }

  if (DecayFactor <= 0 | DecayFactor > 1) {
    stop('Must have 0< decay factor <= 1.')
  }

  if (WindowLength > NumObs){
    stop(sprintf('Window Length #d must be <= number of observations #d',
                 WindowLength, NumObs))
  }

  # ------------------------------------------------------------------------
  # size the data to the window
  RetSeries <- RetSeries[NumObs-WindowLength+1:NumObs, ]

  # Calculate decay coefficients
  DecayPowers <- seq(WindowLength-1, 0, by = -1)
  VarWts <- sqrt(DecayFactor)^DecayPowers
  RetWts <- (DecayFactor)^DecayPowers

  NEff = sum(RetWts) # number of equivalent values in computation

  # Compute the exponentially weighted mean return
  WtSeries <- matrix(rep(RetWts, times = NumSeries),
                     nrow = length(RetWts), ncol = NumSeries) * RetSeries

  ERet <- colSums(WtSeries)/NEff;

  # Subtract the weighted mean from the original Series
  CenteredSeries <- RetSeries - matrix(rep(ERet, each = WindowLength),
                                       nrow = WindowLength, ncol = length(ERet))

  # Compute the weighted variance
  WtSeries <- matrix(rep(VarWts, times = NumSeries),
                     nrow = length(VarWts), ncol = NumSeries) * CenteredSeries

  ECov <- t(WtSeries) %*% WtSeries / NEff

  list(ExpReturn = ERet, ExpCovariance = ECov, NumEffObs = NEff)
}


text:
Q: parsing an external json file in javascript I am trying to parse an external JSON file, and then parse it in javascript but i am getting an uncaught reference error.
I first declare the .json file in my html
<!DOCTYPE html>

    <meta charset="UTF-8">
    <link rel="stylesheet" href="style.css">

    <title>title</title>

        <button onclick="myFunction()" class="dropbtn">Dropdown</button>

            NAME
            ADDRESS
            BUSINESS HOURS
            MENU
            SERVICES and FEATURES

I then try to parse that file in my javascript code:
var jsonFile = JSON.parse(OnebusinessDataFormat_yelp.json);
function name(){
    document.getElementById("rest_name").innerHTML = jsonFile.name;
}

but when i select name from the dropdown it does not populate the
 element with the restaurant name.

A: You need to use the Fetch API in vanilla JS if you want to get the contents of a file:
var jsonFile;
fetch("JOnebusinessDataFormat_yelp.json")
    .then(res => res.json())
    .then(data => jsonFile = JSON.parse(data));

Please also note that this line:

Will not work because you can't have a JSON file inside a


text:
Q: Gitbook force changing uppercase directories to lowercase in GitHub When editing .md files in Gitbook after committing and merging through Gitbook changes are automatically pushed to my repo in GitHub. For some reason if I have a directory named Controllers and edit a markdown file under this directory in Gitbook. Once I edit and save my changes to the markdown file  under the Controllers directory through Gitbook the changes are successfully pushed to my repo in GitHub, but directory is renamed to controllers lower case.
Is there a way to prevent this and maintain the correct case of my directories?


text:
Q: What's a basic solution, and how do we find them? I've just started learning linear programming, and for some reason, have run into a question about something that isn't mentioned in the first chapter (and we're supposed to answer these questions based on the first chapter).
What is a "basic" solution? It is only mentioned once (so far) in the book, in the following manner:
$$\text{"The solutions we obtain by setting the nonbasic variables to zero are called basic feasible solutions"}$$
But the question now asks; "indicate EACH basic solution, and determine which are feasible and which are infeasible", and I don't see how the above quote says anything about several basic solutions. Surely there's only one way we can set all variables to zero, and so only one basic solution?
For example, what are the basic solutions for something as simple as; $$max \ 2x + y \\ s.t. x + y \le 3 \\ x \le 2 $$
where both variables are nonnegative.

A: Rewrite the inequalities as
$$x+y+a=3\\x+b=2\\x\geq0,y\geq0,a\geq0,b\geq0$$
A basic solution has any two of $a,b,x,y$ equal to zero.  The other two variables are forced by the two equations.
The feasible basic solutions have the other two variables positive or zero.