text:
Q: Expression has changed after it was checked --> checkbox mat-tree I have the functionality working but when I switch the value of intermediate i get that error. Not sure if Im changing 2 observables so its like which value should i take. IDK lol! I added my code down below. If you need anything else just let me know. Any Ideas on how to solve this? Man Mat tree component is so annoying!

import { NestedTreeControl } from '@angular/cdk/tree';
import { Component, ChangeDetectorRef } from '@angular/core';
import { MatTreeNestedDataSource } from '@angular/material/tree';
import { SelectionModel } from '@angular/cdk/collections';

interface ITreeNode {
    children?: ITreeNode[];
    name: string;
    expanded: boolean;
}

const TREE_DATA = [
    {
        name: 'Land Plane',
        expanded: true,
        children: [
            { name: 'Piston', expanded: true, children: [] },
            { name: 'Jet', expanded: true, children: [] },
            { name: 'Turboprop', expanded: true, children: [] }
        ]
    },
    {
        name: 'Helicopter',
        expanded: true,
        children: [
            { name: 'Piston', expanded: true, children: [] },
            { name: 'Turboprop', expanded: true, children: [] }
        ]
    },
    {
        name: 'Amphibian',
        expanded: true,
        children: [{ name: 'Turboprop', expanded: true, children: [] }]
    },
    {
        name: 'Tiltwing',
        expanded: true,
        children: [{ name: 'Turboprop', expanded: true, children: [] }]
    },
    {
        name: 'Gyrocopter',
        expanded: true,
        children: [{ name: 'Piston', expanded: true, children: [] }]
    },
    {
        name: 'Tower',
        expanded: true,
        children: []
    },
    {
        name: 'Gyrocopter',
        expanded: true,
        children: []
    }
];

@Component({
    selector: 'globe-source-facets',
    templateUrl: './globe-source-facets.component.html',
    styleUrls: ['./globe-source-facets.component.scss']
})
export class GlobeSourceFacetsComponent {
    public nestedTreeControl: NestedTreeControl<ITreeNode>;
    public nestedDataSource: MatTreeNestedDataSource<ITreeNode>;
    public checklistSelection = new SelectionModel<ITreeNode>(true);
    constructor(private changeDetectorRef: ChangeDetectorRef) {
        this.nestedTreeControl = new NestedTreeControl<ITreeNode>(
            this.getChildren
        );
        this.nestedDataSource = new MatTreeNestedDataSource();
        this.nestedDataSource.data = TREE_DATA;
    }

    public hasNestedChild = (_: number, nodeData: ITreeNode) =>
        nodeData.children.length > 0;

    public getChildren = (node: ITreeNode) => node.children;

    public changeState(node) {
        node.expanded = !node.expanded;
    }

    descendantsAllSelected(node: ITreeNode): boolean {
        const descendants = this.nestedTreeControl.getDescendants(node);
        if (!descendants.length) {
          return this.checklistSelection.isSelected(node);
        }
        const selected = this.checklistSelection.isSelected(node);
        const allSelected = descendants.every(child => this.checklistSelection.isSelected(child));
        if (!selected && allSelected) {
          this.checklistSelection.select(node);
          this.changeDetectorRef.markForCheck();
        }
        return allSelected;
      }

    public descendantsPartiallySelected(node: ITreeNode): boolean {
        const descendants = this.nestedTreeControl.getDescendants(node);
        if (!descendants.length) {
        return false;
        }
        const result = descendants.some(child => this.checklistSelection.isSelected(child));
        return result && !this.descendantsAllSelected(node);
    }

    public todoItemSelectionToggle(node: ITreeNode): void {
        this.checklistSelection.toggle(node);
        const descendants = this.nestedTreeControl.getDescendants(node);
        this.checklistSelection.isSelected(node)
            ? this.checklistSelection.select(...descendants)
            : this.checklistSelection.deselect(...descendants);
    }
}

        <mat-tree
            [dataSource]="nestedDataSource"
            [treeControl]="nestedTreeControl"
            class="example-tree"
        >
            <mat-tree-node *matTreeNodeDef="let node" disabled="true">

                    <button mat-icon-button disabled></button>
                    <mat-checkbox
                        class="checklist-leaf-node"
                        [checked]="checklistSelection.isSelected(node)"
                        (change)="todoItemSelectionToggle(node)"
                        >{{ node.name }}</mat-checkbox
                    >

            </mat-tree-node>

            <mat-nested-tree-node
                *matTreeNodeDef="let node; when: hasNestedChild"
            >

                        <button
                            mat-icon-button
                            [attr.aria-label]="'toggle ' + node.name"
                            (click)="changeState(node)"
                        >
                            <mat-icon class="mat-icon-rtl-mirror">
                                {{
                                    node.expanded
                                        ? 'chevron_right'
                                        : 'expand_more'
                                }}
                            </mat-icon>
                        </button>
                        <mat-checkbox
                            *ngIf="node.name !== ''"
                            class="checklist-leaf-node"
                            [checked]="checklistSelection.isSelected(node)"
                            [indeterminate]="descendantsPartiallySelected(node)"
                            (change)="todoItemSelectionToggle(node)"
                            >{{ node.name }}</mat-checkbox
                        >

                        <ng-container matTreeNodeOutlet></ng-container>

            </mat-nested-tree-node>
        </mat-tree>

        <button mat-button>CLEAR</button>
        <button mat-button color="primary">APPLY</button>

A: This issue is more complex than it seems. This is related to how the Angular works.
Basically, the angular life cycle starts on the parent component, goes to children components, than come back to the parent and finishes.
What is happening is, the life cycle started at the parent and some variable value is A, it goes all the way down to the components tree and when it comes back to the parent the value now is B, the Angular knows the value has changed and shows this error. This error means: "Man, the value has changed while I was doing my life cycle, It not sure if the view was painted with the lasted value"
To fix it?
Try to use the lifecycle functions instead of doing things on the constructor.

A: Changing the checked condition in the nested nodes like following in the view gets rid of the error:

  <mat-tree
    [dataSource]="nestedDataSource"
    [treeControl]="nestedTreeControl"
    class="example-tree"
  >
    <mat-tree-node *matTreeNodeDef="let node" disabled="true">

        <button mat-icon-button disabled></button>
        <mat-checkbox
          class="checklist-leaf-node"
          [checked]="checklistSelection.isSelected(node)"
          (change)="todoItemSelectionToggle(node)"
        >{{ node.name }}</mat-checkbox
        >

    </mat-tree-node>

    <mat-nested-tree-node
      *matTreeNodeDef="let node; when: hasNestedChild"
    >

          <button
            mat-icon-button
            [attr.aria-label]="'toggle ' + node.name"
            (click)="changeState(node)"
          >
            <mat-icon class="mat-icon-rtl-mirror">
              {{
              node.expanded
                ? 'chevron_right'
                : 'expand_more'
              }}
            </mat-icon>
          </button>
          <mat-checkbox
            *ngIf="node.name !== ''"
            class="checklist-leaf-node"
            [checked]="descendantsAllSelected(node)"
            [indeterminate]="descendantsPartiallySelected(node)"
            (change)="todoItemSelectionToggle(node)"
          >{{ node.name }}</mat-checkbox
          >

          <ng-container matTreeNodeOutlet></ng-container>

    </mat-nested-tree-node>
  </mat-tree>

  <button mat-button>CLEAR</button>
  <button mat-button color="primary">APPLY</button>

To fix the bug with the parent node state after last child node is deselected, change todoItemSelectionToggle() method like following:
import {NestedTreeControl} from '@angular/cdk/tree';
import {Component, ChangeDetectorRef, OnInit} from '@angular/core';
import {MatTreeNestedDataSource} from '@angular/material/tree';
import {SelectionModel} from '@angular/cdk/collections';

interface ITreeNode {
  children?: ITreeNode[];
  name: string;
  expanded: boolean;
}

const TREE_DATA = [
  {
    name: 'Land Plane',
    expanded: true,
    children: [
      {name: 'Piston', expanded: true, children: []},
      {name: 'Jet', expanded: true, children: []},
      {name: 'Turboprop', expanded: true, children: []}
    ]
  },
  {
    name: 'Helicopter',
    expanded: true,
    children: [
      {name: 'Piston', expanded: true, children: []},
      {name: 'Turboprop', expanded: true, children: []}
    ]
  },
  {
    name: 'Amphibian',
    expanded: true,
    children: [{name: 'Turboprop', expanded: true, children: []}]
  },
  {
    name: 'Tiltwing',
    expanded: true,
    children: [{name: 'Turboprop', expanded: true, children: []}]
  },
  {
    name: 'Gyrocopter',
    expanded: true,
    children: [{name: 'Piston', expanded: true, children: []}]
  },
  {
    name: 'Tower',
    expanded: true,
    children: []
  },
  {
    name: 'Gyrocopter',
    expanded: true,
    children: []
  }
];

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
  public nestedTreeControl: NestedTreeControl<ITreeNode>;
  public nestedDataSource: MatTreeNestedDataSource<ITreeNode>;
  public checklistSelection = new SelectionModel<ITreeNode>(true);

  constructor(private changeDetectorRef: ChangeDetectorRef) {

  }

  ngOnInit() {
    this.nestedTreeControl = new NestedTreeControl<ITreeNode>(
      this.getChildren
    );
    this.nestedDataSource = new MatTreeNestedDataSource();
    this.nestedDataSource.data = TREE_DATA;
  }

  public hasNestedChild = (_: number, nodeData: ITreeNode) =>
    nodeData.children.length > 0

  public getChildren = (node: ITreeNode) => node.children;

  public changeState(node) {
    node.expanded = !node.expanded;
  }

  descendantsAllSelected(node: ITreeNode): boolean {
    const descendants = this.nestedTreeControl.getDescendants(node);
    if (!descendants.length) {
      return this.checklistSelection.isSelected(node);
    }
    const selected = this.checklistSelection.isSelected(node);
    const allSelected = descendants.every(child => this.checklistSelection.isSelected(child));
    if (!selected && allSelected) {
      this.checklistSelection.select(node);
      this.changeDetectorRef.markForCheck();
    }
    return allSelected;
  }

  public descendantsPartiallySelected(node: ITreeNode): boolean {
    const descendants = this.nestedTreeControl.getDescendants(node);
    if (!descendants.length) {
      return false;
    }
    const result = descendants.some(child => this.checklistSelection.isSelected(child));
    return result && !this.descendantsAllSelected(node);
  }

  public todoItemSelectionToggle(node: ITreeNode): void {
    this.checklistSelection.toggle(node);
    const descendants = this.nestedTreeControl.getDescendants(node);
    this.checklistSelection.isSelected(node)
      ? this.checklistSelection.select(...descendants)
      : this.checklistSelection.deselect(...descendants);

    // Force update for the parent
    descendants.every(child =>
      this.checklistSelection.isSelected(child)
    );

  }

}

These are from the example with the checkboxes at https://material.angular.io/components/tree/examples
Check the difference in flat tree view for nodes when they have child nodes and not.


text:
Q: Why t-stat is normally reported but not p-value? I just wonder why t-stat is normally reported with an asterisk to indicate significance but not p-value.

A: I guess the reason is that, with the p-value, it is trivial to see the significance levels at which the hypothesis is and is not rejected (that is why it is also called marginal significance level!): if your p-value is 0.0867, it would really be an overkill to add an asterix to indicate that the null is rejected at the 10%-level.
When your t-statistic is, say, 1.78, you may or may not see directly whether that implies rejection at the 10% level (and even less so with statistics that are, say, $\chi^2$, $F$-distributed etc.).

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to pipe value to another observable creator without cancelling original stream? What I wanted to do is to implement suggestion box for the UI. The goal here is to listen to input changes, filter them out, pass them to service call and return results.
What I did is
this.sub = this.form.controls['host'].valueChanges
      .pipe(
        tap(console.log),
        filter((v) => v != null && v.length),
        debounceTime(500),
        distinctUntilChanged(),
        switchMap(v => this.hostService.suggest(v)) //actuall REST call
      ).subscribe(value => {
        this.hostSuggestions = value;
      });

however, this does REST call only once, and stops reacting after that. As a workaround I am doing this
this.sub = this.form.controls['host'].valueChanges
  .pipe(
    tap(console.log),
    filter((v) => v != null && v.length),
    debounceTime(500),
    distinctUntilChanged(),
    // switchMap(v => this.hostService.suggest(v))
  ).subscribe(value => {
    this.hostService.suggest(value).subscribe(hosts => this.hostSuggestions = value);
  });

and it works fine, but I think it can be done using pure operators. Am I correct?

A: Change switchMap for a mergeMap. when the observable in switchMap operator emit the first value cancel the subscription of previous observable.


text:
Q: Typified DataTable to get her row values using a custom class I'm been looking some way to use DataTables and get values of her rows using a custom class.
My approach is the following:
DataTable dtUsers = new DataTable();

dtUsers.Columns.Add("Name");
dtUsers.Columns.Add("Last name");
dtUsers.Columns.Add("Age", typeof(int));

for (int x = 1; x <= 100; x++)
{
    dtUsers.Rows.Add(new object[]
    {
        "Name " + x,
        "Last name " + x,
        x
    });
}

// I want to do this
var Name = dtUsers.Rows[0].Name; // Get "Name 1"
var Age = dtUsers.Rows[50].Age; // Get "Age 50"

// Or
foreach(DataRow drCurrent in dtUsers.Select("Age > 50"))
{
    int Age = drCurrent.Age; // Get 51,52,53..
}

I'm thinking something like this:
public class DataTablePerson : DataTable
{
    public string Name { get; set; } // Implement a method to return a specific value in some specific row
    public string Last_name { get; set; } // Implement a method to return a specific value in some specific row
    public int Age { get; set; }// Implement a method to return a specific value in some specific row
}

Exists a method to achieve this?
Will be double of useful if I could use the custom class using as parameter some Typified class, to reapply this class other structures (Ex: Person, Tree, Movie, Book).

A: Err no, don't use array-based data model for your application. I have blogged it why. Instead, convert the data table to List/Array/Enumerable of your own class model (POCO) and use it instead.
But if you insist to use it (it's your own choice though), you can do it with "wrapper class".
public class DataTablePerson{
    public DataTablePerson(DataTable source){
        this.Source = source;
    }
    protected DataTable Source = null;

    public string Name(int row = 0){
        return Get("name", row);
    }
    public string LastName(int row = 0){
        return Get("last_name", row);
    }
    public int Age(int row = 0){
        return Convert.ToInt32(Get("age", row));
    }

    protected string Get(string name, int row){
        return source.Rows[row][name].ToString();
    }
}

And use it like:
DataTablePerson dtp = new DataTablePerson(dtUsers);
string name = dtp.Name(1);

Or if you want row-level entity (you can use property in exchange though):
public class DataRowPerson{
    public DataRowPerson(DataRow source){
        this.Source = source;
    }
    protected DataRow Source = null;

    public string Name(){
        return source["name"].ToString();
    }
    public string LastName(){
        return source["last_name"].ToString();
    }
    public int Age(){
        return Convert.ToInt32(source["age"].ToString()));
    }
}

And use it like:
foreach(DataRow drCurrent in dtUsers.Select("Age > 50"))
{
    DataRowPerson drp = new DataRowPerson(drCurrent);
    int Age = drp.Age; // Get 51,52,53..
}

A: You almost had it! Only instead of using property notation, you just need to specify the column name as a string inside square brackets:
var Name = dtUsers.Rows[0]["Name"];
var Age = dtUsers.Rows[50]["Age"];

Or:
var agesOverFifty = new List<int>();
foreach (DataRow currentRow in dtUsers.Select("Age > 50"))
{
    agesOverFifty.Add(Convert.ToInt32(currentRow["Age"]));
}

Or even using LINQ:
List<int> agesOverFifty = dtUsers.Select("Age > 50")
    .Select(row => Convert.ToInt32(row["Age"]))
    .ToList();

Console.WriteLine("The average age of a person over 50 in our sample is: {0}",
    agesOverFifty.Average());


text:
Q: 'this' in arrow function not showing lexical scoping I was trying to understand the lexical scoping of 'this' in arrow functions. I tried the following code -
const obj1 = {
  name: "obj1name",
  method: function(){
    return () => {return this.name};
  }
};

const arrowFunc1 = obj1.method();

console.log(arrowFunc1());

const obj2 = {
  name: "obj2name",
  method: function(){
    return obj1.method();
  }
};

const arrowFunc2 = obj2.method();

console.log(arrowFunc2());

This gives the output -
obj1name
obj1name

As expected, 'this' inside the arrow function was lexically scoped to obj1 and hence it prints 'obj1name' no matter how we call it. All fine till here. Then instead of defining obj2.method I decided to directly copy obj1.method into it -
const obj1 = {
  name: "obj1name",
  method: function(){
    return () => {return this.name};
  }
};

const arrowFunc1 = obj1.method();

console.log(arrowFunc1());

const obj2 = {
  name: "obj2name",
  method: obj1.method
};

const arrowFunc2 = obj2.method();

console.log(arrowFunc2());

This gives the output -
obj1name
obj2name

I don't understand why it prints 'obj2name'.
My understanding is that the arrow function is defined in obj1.method and so it is lexically scoped in it. Hence it should take the value of 'this' from obj1.method which is obj1.
What am i getting wrong?

A: This:
const obj1 = {
  name: "obj1name",
  method: function(){
    return () => {return this.name};
  }
};

Should be this:

const obj1 = {
  name: "obj1name",
  method: () => {return this.name}
};

By wrapping the arrow function in a regular function the scope once again becomes the scope of the caller.

A: It is lexically scoped: you defined a function (arrow) in obj1, but called it in obj2 - the lexical scope of obj2 is obj2 - so the method you invoked there works as supposed to.
The console.logs in the snippet show the problem:

const obj1 = {
  name: "obj1name",
  method: function(){
    return () => {return this.name};
  }
};

const arrowFunc1 = obj1.method();

console.log(arrowFunc1());

const obj2 = {
  name: "obj2name",
  method: obj1.method
};

const arrowFunc2 = obj2.method();

console.log(arrowFunc2());

// these console.logs show your problem:
console.log('obj1:', obj1)
console.log('obj2:', obj2)

In your case, the function() creates the scope for this - and that function() is in obj2.
Maybe this snippet helps to understand a little more:

// extracted the function, but left the "this"
// just calling the function in itself would throw an
// error, but inside an object (that has a name property)
// it works nicely
const fn = function() {
  return () => {
    return this.name
  }
}

const obj1 = {
  name: "obj1name",
  method: fn
};

const arrowFunc1 = obj1.method();

console.log(arrowFunc1());

const obj2 = {
  name: "obj2name",
  method: fn
};

const arrowFunc2 = obj2.method();

console.log(arrowFunc2());

// these console.logs show your problem:
console.log('obj1:', obj1)
console.log('obj2:', obj2)

And my last snippet:

const obj1 = {
  name: "obj1name",
  method: function() {
    return () => {
      return this.name
    };
  }
};

const arrowFunc1 = obj1.method();

console.log(arrowFunc1());

// if you want to call with obj1, then it's not enough to add the
// function - you have to CALL (invoke) it
const obj2 = {
  name: "obj2name",
  method: obj1.method()
};

// see that there're no parantheses after obj2.method - its
// value is resolved when creating obj2 by INVOKING the function
const arrowFunc2 = obj2.method;

console.log(arrowFunc2());

// these console.logs show your problem:
console.log('obj1:', obj1)
console.log('obj2:', obj2)


text:
Q: Uncaught Reference Error JQuery I have the following JQuery code:
<script type="text/javascript">
    $(document).ready(function () {
        var $containerHeight = $('.container').height();
        if ($containerHeight < 760) {
            $('.footer').css({
                position: 'static',
                bottom: 'auto',
                left: 'auto'
            });
        }
    });
</script>

And I get the very unhelpful error message:

Uncaught ReferenceError: $ is not defined
  (anonymous function)

Any ideas where I'm going wrong?

A: You probably haven't included jQuery before running your own code.  Make sure you put this before your own <script> tag:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>


text:
Q: D3.js - Nodes appear stacked in the top left corner of the graph TLDR;
When building a force directed graph based on multiple XML datasources, all the nodes appear stacked in the top left corner of the graph. Given there are no errors showing in console and all the nodes and links are correctly loaded afaik, what D3.js incorrect configuration could cause this behaviour?
Situation
Based on Mike Bostock's example of a Force-Directed Layout from XML
https://bl.ocks.org/mbostock/1080941, I am loading multiple XML files using d3.queue and I am trying to display the force graph. When I am using one XML file the graph shows 1 node. However, when I am using multiple XML's the graph shows all the nodes in the top left corner. The console does not show any errors and all the required nodes and links objects are correctly loaded afaik.
Given
Edit: I have reduced code to a bare minimum to reproduce the problem.
Four files are needed. Two small xml files, one json file and the html file.
FileList.json
[
"City.hbm.xml",
"Country.hbm.xml"
]

City.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="nl.sander.mieras.localhost.sakila.City" table="city" catalog="sakila">
        <!-- removed for readability -->
    </class>
</hibernate-mapping>

Country.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="nl.sander.mieras.localhost.sakila.Country" table="country" catalog="sakila">
        <!-- removed for readability -->
    </class>
</hibernate-mapping>

And the signifcantly reduced html file:
<!DOCTYPE html>
<meta charset="utf-8">
<style>
    .link {
        stroke: #ccc;
    }

    .node {
        fill: #000;
        stroke: #fff;
        stroke-width: 2px;
    }
</style>
<body>
<script src="//d3js.org/d3.v3.min.js"></script>
<script src="//d3js.org/d3-queue.v2.min.js"></script>
<script>
    var width = 960,
            height = 500;

    var radius = d3.scale.sqrt()
            .domain([0, 20000])
            .range([0, 20]);

    var force = d3.layout.force()
            .charge(-240)
            .linkDistance(40)
            .size([width, height]);

    var svg = d3.select("body").append("svg")
            .attr("width", width)
            .attr("height", height);

    d3.json("FileList.json", function (error, fileArray) {
        var q = d3_queue.queue();
        fileArray.forEach(function (d) {
            q = q.defer(d3.xml, d);
        });
        q.await(analyze);
    });

    function analyze(error) {
        if (error) {
            console.log(error);
        }
        // skip 0 it's error variable
        for (i = 1; i < arguments.length; i++) {
            var xml = arguments[i];
            var nodes = [];
            var label = d3.select(xml).select("class").attr("table").charAt(0).toUpperCase() + d3.select(xml).select("class").attr("table").slice(1);
            nodes.push({
                "id": nodes.length,
                "label": label
            });

            console.log(nodes);
            node = nodes[0];
            node.x = width / 2;
            node.y = height / 2;

            force
                    .nodes(nodes)
                    .start();

            var node = svg.selectAll(".node")
                    .data(nodes)
                    .enter().append("circle")
                    .attr("class", "node")
                    .attr("r", 20)
                    .call(force.drag);

            force.on("tick", function () {
                node.attr("cx", function (d) {
                            return d.x;
                        })
                        .attr("cy", function (d) {
                            return d.y;
                        });
            });
        }
    }
</script>

Question
Using one XML as data the graph looks like this...

Using multiple XML's as data the graph looks like this...

What part of the code is causing this behaviour? I have tried to configure the x and y coordinates with hard coded values, but regardless of my attempts, the nodes just appear as a 1/4 node in the top left corner.
Reproduce
I tried to make the issue ease to reproduce using jsfiddle, but I failed to get external sources to work regardless of my attempts based on the answers from  How to add local json file in jsfiddle?
Full code on github gist:
https://gist.github.com/Weirdfishees/f1b19b43346a175bd214
and on github (small directory difference)
https://github.com/Weirdfishees/xmltoforcegraph.


text:
Q: Antd RangePicker Component with React Hook Form I currently have a react-hook-form managed form that I've added an antd RangePicker to. I'm having issues with updates to the RangePicker getting passed to the form object. Currently, the default values are passing fine but it's not taking any changes.
OnChange events seem to be being handled by the standard Controller method with the other field types (Input, etc.). My guess is I have to write something custom here but I'm not sure. Thanks in advance for any help.
Here is my current antd DatePicker that is being managed with react-hook-forms Controller method.
EDIT: Updated my code to use the render method in react-hook-form v6+ as opposed to the as method. I also noticed if I don't pass any defaultValue then the RangePicker accepts and passes both the start and end dates fine. But when I set the defaultValue it always returns the default start date twice.
<Controller
    name="materialarrivalpickup"
    control={control}
    defaultValue={[
        moment(user.project.projectmaterialarrival),
        moment(user.project.projectmaterialpickup),
    ]}
    rules={{ required: true }}
    render={(props) => (
        <RangePicker
        {...props}
        format="MM/DD/YYYY"
        onChange={(e) => {
            props.onChange(e);
            console.log("Range Picker " + e);
        }}
        />
    )}
/>

A: Figured this out. Apparently, react-hook-form was properly passing the RangePicker changes to my form object I just couldn't tell based on the log.
When I update the picker the Moment object (two dates) wasn't looking updated in the log produced by react-hook-form watch() (both look like they're 3/3/2020).

But when I expand the Moment object I'm getting my updated dates (3/3/2020 and 3/5/2020).

I'll leave my working RangePicker + react-hook-form code here for anyone else that needs it.
<Controller
    name="materialarrivalpickup"
    style={{ marginBottom: "8px" }}
    control={control}
    defaultValue={[
    moment(user.project.projectmaterialarrival),
    moment(user.project.projectmaterialpickup),
    ]}
    rules={{ required: true }}
    render={(props) => (
    <RangePicker
        {...props}
        format="MM/DD/YYYY"
        onChange={(e) => {
        props.onChange(e);
        console.log("Range Picker: " + e);
        }}
    />
    )}
    />


text:
Q: how to fix groovy.lang.MissingMethodException: No signature of method why following groovy code throw an exception: groovy.lang.MissingMethodException: No signature of method.
I am the new guy for groovy, can any body help me?
def b = {->
    c()
  }

  def c={ ->
  true
  }

  b()

Stracktrace is
groovy.lang.MissingMethodException: No signature of method: Script1.c() is applicable for argument types: () values: []
Possible solutions: a(), is(java.lang.Object), run(), run(), any(), any(groovy.lang.Closure)<i>
    at Script1$_run_closure1.doCall(Script1.groovy:7)
    at Script1.run(Script1.groovy:14)

A: It's about order
def c = { ->
    true
}

def b = { ->
    c()
}

b()


text:
Q: Router configuration push error using ansible I create a playbook to restore my router backup using ansible, but it didn't work properly.
---
- hosts: CR01
connection: network_cli
gather_facts: false

tasks:
- name: push config file
  ios_config:
    src: "home/yugan/desktop/backup/config/CR1.cfg"

- name: save running to startup
  ios_config:
    save_when: modified


text:
Q: Stop the live updates while user is editing comment? I've a got a commenting system on my blog. Thing is the comments are updated live via WebSockets. While the comments are updated, of course the owner must be able to edit their comments. I want to enable in-place editing (which means that the comment will be replaced with a textbox and Save/Discard buttons). My React app subscribes to socket events and changes the comments array in the component state. This means that while the user is editing a comment, if something new comes in, the editing would be brutally stopped.
Having this said, I thought of two possible approaches:
 1. While the user is editing a comment, stop the live updates (i.e. temporarily ignore socket events)
 2. Keep updating the comments but keep scroll on the comment editor (which I don't know how to deal with)
I think it would be stupid to stop the live updates while the user is editing a comment, so I am asking you, how should go about keeping the editor there while updating comments?
More about my application structure:
I've got the component <PostComments /> whose state contains the array comments. That array is being rendered then as a bunch of <Comment />:
renderComments = () => {
    const { comments } = this.state;

    return comments.map( comment => {
        return (
            <Comment key={comment['comment_id']} data={comment} />
        );
    } );
};

The <Comment /> component gets static data to render (i.e. an object with a standard shape
export const commentDataType = React.PropTypes.shape( {
    comment_id: React.PropTypes.number.isRequired,
    user_info: React.PropTypes.shape( {
        preferred_name: React.PropTypes.string.isRequired,
        profile_picture: React.PropTypes.string.isRequired,
    } ).isRequired,
    post_timestamp: React.PropTypes.number.isRequired,
    comment_text: React.PropTypes.string.isRequired,
} );

And this it kind of. Thank you!

A: Concluding from the brief conversation in the comments - by all means, I believe the best approach would be to save a copy of the comment separately somewhere in the state tree (possibly currentlyEditing or something similar) once the user opens it up for editing.
Then the user can edit the copy instead, and you can keep logic in the back intact as much as possible.
If the user commits, save the comment's changes for the comment with a specific comment_id.
Thinking forward, you could optionally introduce an edited_timestamp to make sure concurrent updates don't overwrite one-another and show a warning if the user doesn't have the latest changes and wants to save an edit.
This way you will keep the updates coming, the user flow and experience should not get disrupted and you will manage to re-use as much of your code as possible, while still getting the leniency and comfort of being able to discard edited changes at the click of a button, without worrying about side-effects.
You can often see similar behaviour and user-experience on forums and boards. Or blogs, very much similar to your use-case.


text:
Q: Get custom status of process I want to allow multiple processes of my application on one machine.
Projects (come from local database) can be loaded in each process and I want to ensure that a Project can only be open in one process of my application.
Therefore before opening a Project I want to check if the Project I want to open is already open in another process.
I know that this isn't best programming practice, but I it's just a temporary solution until we implement a more sophisticated locking mechanism on data Level.
I can detect another running process, but can I somehow access or cast it to something more appropriate to get the Information I want ?
Someting like that:
  Process[] allProcesses = Process.GetProcessesByName("MyApp");

  foreach (Process process in allProcesses)
  {
    var projects = process.OpenedProjects;

Have come across .net remoting, WCF, IPC but found that to be very heavyweight for this rather "simple" Task.

A: If it's a temp solution, just choose the easy way:
When a process load a project, just write a file in the app directory with the project name or ID. If the file already exists it means the project is already loaded in another process.
You can also write the process ID as file content, if you want to know which process have opened a project.
Of course you need to delete the file when the process finish.
Be sure that you handle all exceptions so that process can't finish without deleting this file. I.e. intercept AppDomain.UnhandledException.

A: If this is a temporary solution as you say, you could give each project an identifier (e.g. filename) and display it in the title of the main window, for example

C:\Project1.proj C:\Project2.proj C:\Project3.proj

Then check if the project is open with process.MainWindowTitle.Split(' ').Contains.


text:
Q: Dash Displaying Rows All Vertically Recently started dabbling in dash, specifically with bootstrap components for layout.
I'm using the following code:
from dash import Dash, html, dcc, Input, Output
import dash_bootstrap_components as dbc

app = Dash(__name__)

app.layout = dbc.Container(
    [
        dbc.Row(dbc.Col(html.Div("A single, half-width column"), width=6)),
        dbc.Row(
            dbc.Col(html.Div("An automatically sized column"), width="auto")
        ),
        dbc.Row(
            [
                dbc.Col(html.Div("One of three columns"), width=3, align='Right'),
                dbc.Col(html.Div("One of three columns")),
                dbc.Col(html.Div("One of three columns"), width=3),
            ]
        ),
    ]
)

if __name__ == '__main__':
    app.run_server(debug=True)

This was taken straight from the dbc docs and I was expecting the last row to have three horizontal columns, but they all display like this:
A single, half-width column
An automatically sized column
One of three columns
One of three columns
One of three columns

This is super basic and straightforward but I can't figure out why it won't display correctly. I've tried other examples from the docs verbatim and everything displays vertically regardless of how I have the container, rows, and columns laid out. Any idea what I'm doing wrong?
Using Dash 2.5.0 and dbc 1.2.1


text:
Q: Not able to use >= to compare user input I'm trying to code a program that when the user inputs his numerical grade, the system will give the user his letter grade. This is my code so far (would copy and paste for A,A-,B+, etc)
import java.util.*;
import java.util.Scanner;

public class LetterGrade
{
    static Scanner userInput = new Scanner(System.in);
    public static void main(String[] args)
    {
        char grade;

            System.out.println("Enter your grade in numeric form ");

            if (userInput >= 97 && grade <= 100)
            {grade = "A+";}
            System.out.println("Your letter grade is " + grade);
    }
}

The error messages that I'm getting are:
C:\Users\User\Desktop\Lab2>javac LetterGrade.java
LetterGrade.java:14: operator >= cannot be applied to java.util.Scanner,int
                        if (userInput >= 97 && grade <= 100)
                                      ^
LetterGrade.java:15: incompatible types
found   : java.lang.String
required: char
                        {grade = "A+";}
                                 ^
2 errors

I've used java for less than one week, and I don't know where the problem is.
Edit: Found the problem with the "A+". changed from char grade; -> string grade;.

A: You're trying to comapre an int to a Scanner object. This doesn't make much sense. I think you wanted to try to compare what the user enters. You can use the nextInt() method to read the numeric value of the grade. Something like:
String letterGrade = "";
int grade = userInput.nextInt();
if(grade >= 97 && grade <= 100) {
   letterGrade = "A+";
}

(Note that letterGrade must be a String not a char as it needs to be two characters)


text:
Q: Remove Image Number From Color box Slideshow In Color box,
I want to remove the image number being displayed for images i.e. image 2 of 4 from the colorbox slideshow.How am I supposed to do that?. What am I supposed to change?
For Example by adding
display:none!important in colorbox.css file is not solving my problem. I feel it can't be removed. But, we may have a solution in script programming..
So Far I have done as Follows:-

A: You add the following property to your colorbox call:
current: false
And it won't show the current number of the image.
You can refer this in the documentation here: http://www.jacklmoore.com/colorbox/


text:
Q: get hardware id using wpf tried using solutions posted here How to fast get Hardware-ID in C#? and here http://www.codeproject.com/Articles/17973/How-To-Get-Hardware-Information-CPU-ID-MainBoard-I but it seems wpf doesn't have ManagementObjectCollection. I've already add
using System.Management;
using System.Management.Instrumentation;

in my code, though. is there any way using wpf to get the cpu id and else?

A: WTF?
WPF should be able to use WMI.
Did you try manually adding a reference to System.Management (WMI)?


text:
Q: Ruby - can you tell me whats going on here Confused by this method - can someone please explain it to me?
def current_user
    @current_user ||= (login_from_session || login_from_cookie) unless @current_user == false
end

A: It says:

*

*unless current is not set (the latest unless)

*do nothing and return @current_user if @current_user is already set (the ||= part)

*else call the method/helper login_from_session and assign the result to @current_user

*else if the previous call has returned nil or false, call the method/helper login_from_cookie and assign the result to @current_user

*in any case return the value of @current_user instance variable

It could be rewritten to be more explicit in this way
def current_user
  if !(@current_user == false) # 1
    if (@current_user)
      return @current_user # 2
    end
    if (@current_user = login_from_session)
      return @current_user # 3
    end
    if (@current_user = login_from_cookie)
      return @current_user # 4
    end
  end
  return @current_user # 5
end

This is the power (and the beauty) of ruby expressiveness. Remember that in Ruby only nil and false evaluate to boolean false in if/else statements and ||, && operators
Other hints to understand better, in ruby you have the following rules:
The return value of any function is the last expression evaluated for the function, so
def foo
  any_value
end

is the same of
def foo
  return any_value
end

The if/unless statement at the end of an expression is the same of a if/unless statement, so
do something if value

is the same of
if (value)
  do_something
end

The ||= operator is a shortcut for
@a ||= some_value
# is equivalent to
if !@a
  @a = some_value
end

Combine all these rules and you've the method explained.


text:
Q: Expect() not doing the comparison when using BDD I am working with Protractor 5.4.0 and cucumber.
The protractor.conf.js file is:
global.expect = require('chai').expect;
var chai = require('chai');
var chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);

exports.config = {
    seleniumAddress: 'http://localhost:4444/wd/hub', // This is targetting your local running instance of the selenium webdriver

    specs: [
        '../Features/UI_Tests.feature'
    ],

    capabilities: {
        browserName: 'chrome' // You can use any browser you want. On a CI environment you're going to want to use PhantomJS
    },

    framework: 'custom', //We need this line to use the cucumber framework

    frameworkPath: require.resolve('protractor-cucumber-framework'), // Here it is

    cucumberOpts: {
        //format:  'pretty',
        require: '../Features/step_definitions/my_steps.js', // This is where we'll be writing our actual tests
        // tags: ['@basic'],
        strict: true,
        plugin:"json"
    },
    resultJsonOutputFile:'./testResults.json', //output file path to store the final results in .json format
    params: {
        env: {
            hostname: 'http://0.0.0.0:8000' // Whatever the address of your app is
        }
    }
};

I have this scenario defined with some examples:
Scenario Outline: dropdown boxes appear and work as expected.
    When go to "URL"
    Then application is running
    When click <box>
    Then <option> is present in <box>

    Examples:
      |box| option|
      |templateSelection| Apparent Energy |
      |templateDeliveryPathSelection| Email |
      |templateLocaleSelection| English |

I am using this piece of code to check that text of the dropdown box is the same one as the option column:
checkDropdown: function (value,dropdown) {
        var text = element(by.id(dropdown)).getText();
        expect(text).to.eventually.equal(value);
    },

It seems to be working properly because the output informs that all the scenarios have passed. However, if we change any of the values in the "option" column to make it fails, the output is the same one, all scenarios pass. Why?
Thanks in advance.

A: Try:
checkDropdown: function (value,dropdown) {
        var text = element(by.id(dropdown)).getText();
        return expect(text).to.eventually.equal(value);
}

It's because you aren't returning the expect. You always have to return a promise in your step definitions. if the function returns undefined it will pass regardless.
I highly recommend using https://github.com/canvaspixels/cucumber-protractor if you're using those two technologies to save tons of boilerplate and effort. You can keep your existing tests and migrate gradually.
There's a demo video here: https://www.youtube.com/watch?v=5vuYL4nxMXs


text:
Q: Android Studio isn't recognizing the checkSelfPermission Is it possible to run Google Sample - RuntimePermissionsBasic
On devices with OS less than MNC (Android M)?
This project comes with:
compileSdkVersion "android-MNC"
targetSdkVersion "MNC"

So far so good, running it on less than M OS will get:
INSTALL_FAILED_OLDER_SDK
But when I changed it to:
compileSdkVersion 22
targetSdkVersion "MNC"

The Android Studio isn't recognizing the checkSelfPermission (...) method

A: Try to add ContextCompat.checkSelfPermission() instead just checkSelfPermission...for me it works...

A:
So far so good, running it on less than M OS will get: INSTALL_FAILED_OLDER_SDK

That is because setting compileSdkVersion to android-MNC forces the minSdkVersion to MNC by default. There are recipes for changing that behavior.

But when I changed it to... The Android Studio isn't recognizing the checkSelfPermission (...) method

checkSelfPermission() was introduced in the M Developer Preview and does not exist on older versions of Android.


text:
Q: Durandal - Multiple routes using same VM/View I'm building an application using Durandal 2. I want to define multiple routes using the same VM/View for different context.
Exemple :

*

*/sectionA/:id/home using module ID /viewmodels/home

*/sectionB/:id/home using module ID /viewmodels/home too

At first, sectionA and sectionB are meant to use the exact same VM and Views. But, eventually, they will be different. This is not where the issue is since when they'll be different, they'll have their very own VM and shared views (using MVC partials) which will work straight out the box.
The point is, for as long as the page are the same, we don't want to duplicate the VM and Views, generating a lot of garbage for nothing.
I tried the example shown above but that doesn't seems to be possible to do this. Whether the routes are different, it seems that the router cannot make the difference between the two routes and just throw a "route not found" exception although the route is defined in our route definition file.
So the question, is it possible to define two route, with obviously different routes definitions, but using the same moduleId?
If more details are require, don't hesitate to ask for clarifications.
Thanks! :)


text:
Q: Regular Expression To Parse Shortcode data not getting closing tags I'm in the process of writing a parser for shortcodes.  I have a regular expression that I've been playing with to retrieve ALL shortcodes within given text.
For example I have shortcodes like this
[url href="http://somedomain.com" class="123"]
[snip category="spoons"]

my regex works fine for the above shortcodes but fails for this type
[widget id="23"]Body Text[/widget]

I'm looking to return an array like this...
[url href="http://somedomain.com" class="123"]
[snip category="spoons"]
[widget id="23"]Body Text[/widget]

then I'll loop through each shortcode and parse them individually with a separate function.  Below is the regex that i've been using.
"/\[(.*?)(.+?)\]/" <--works fine for no closing tags

and i tried this for the closing tags but it returns weird results
"/\[(.*?)(.+?)\](?:(.+?)?\[\/(.*?)\])?/" <--- Doesn't work well/at all

any help is appreciated.  Thanks in advance

A: WordPress has a built-in function (get_shortcode_regex()) that returns the official regex that is used to parse shortcodes. My feeling is that you'd want to use that instead of rolling your own.
You can use the regex it returns to do with what you like.


text:
Q: WI-FI connection drops when laptop screen turns-off I'm running Ubuntu LTS 22.04 on a laptop that acts as a server.
Since a couple of days I keep losing my wi-fi connection whenever my laptop screen turns off.
The screen is turned off in the power settings after 2 min to save power as it is mostly just working as server, but the laptop is not switched to low-power mode as long as the laptop is powered from the adapter. (normal situation)
(It has been running stable in this way since the installation around the time that 22.04 was released and did not show any issue until now.)
Whenever I move the mouse the wi-fi connection gets re-established and the server works as expected again.
The problem is that now the server obviously does not function because it is unreachable most of the time.
Has anyone else encountered this problem after a recent update, or can you give me any advice on how to debug or fix this?
Thanks
I have some pointers from DMESG that someone advised me to run, it is pasted below...
So it seems that I have an issue that is seen before from a search. I haven't found a solution yet and it's also not clear to me yet why it started to occur recently while no change was made in my hardware but I just started searching for the error and I could stumble upon the solution.
However if anyone has a good pointer feel free to help me ;-)
[106559.442845] wlx2cd05a59734b: associated
[106559.506142] wlx2cd05a59734b: Limiting TX power to 30 (30 - 0) dBm as advertised by 3c:84:6a:90:07:b2
[108019.154016] wlx2cd05a59734b: disconnect from AP 3c:84:6a:90:07:b2 for new auth to 3c:84:6a:90:07:c6
[108019.274182] wlx2cd05a59734b: authenticate with 3c:84:6a:90:07:c6
[108019.274222] wlx2cd05a59734b: 80 MHz not supported, disabling VHT
[108019.282464] wlx2cd05a59734b: send auth to 3c:84:6a:90:07:c6 (try 1/3)
[108019.485528] wlx2cd05a59734b: send auth to 3c:84:6a:90:07:c6 (try 2/3)
[108019.487949] wlx2cd05a59734b: authenticated
[108019.489504] wlx2cd05a59734b: associate with 3c:84:6a:90:07:c6 (try 1/3)
[108019.494782] wlx2cd05a59734b: RX ReassocResp from 3c:84:6a:90:07:c6 (capab=0x1431 status=0 aid=2)
[108019.497010] usb 1-1.4: rtl8xxxu_bss_info_changed: HT supported
[108019.500141] wlx2cd05a59734b: associated
[108019.580866] wlx2cd05a59734b: Limiting TX power to 30 (30 - 0) dBm as advertised by 3c:84:6a:90:07:c6
[108022.601033] wlx2cd05a59734b: deauthenticated from 3c:84:6a:90:07:c6 (Reason: 2=PREV_AUTH_NOT_VALID)
[113139.317091] perf: interrupt took too long (7864 > 7848), lowering kernel.perf_event_max_sample_rate to 25250
[126718.134276] audit: type=1400 audit(1677312009.899:269): apparmor="DENIED" operation="capable" class="cap" profile="/usr/sbin/cupsd" pid=27108 comm="cupsd" capability=12  capname="net_admin"
[158703.591538] wlx2cd05a59734b: authenticate with 3c:84:6a:90:07:b2
[158703.606391] wlx2cd05a59734b: send auth to 3c:84:6a:90:07:b2 (try 1/3)
[158703.612001] wlx2cd05a59734b: authenticated
[158703.614917] wlx2cd05a59734b: associate with 3c:84:6a:90:07:b2 (try 1/3)
[158703.629781] wlx2cd05a59734b: RX AssocResp from 3c:84:6a:90:07:b2 (capab=0x1431 status=0 aid=4)
[158703.631633] usb 1-1.4: rtl8xxxu_bss_info_changed: HT supported
[158703.634487] wlx2cd05a59734b: associated
[158703.685622] IPv6: ADDRCONF(NETDEV_CHANGE): wlx2cd05a59734b: link becomes ready
[158703.739770] wlx2cd05a59734b: Limiting TX power to 30 (30 - 0) dBm as advertised by 3c:84:6a:90:07:b2

Ok, I have an update of how I think it is solved in my case, fingers crossed.
First I changed the network setting to avoid power settings to affect my WIFI by changing the content of this file: /etc/NetworkManager/conf.d/default-wifi-powersafe-on.conf
In there is a section which in my case looked like this:
[connection]
wifi.powersave=3
I changed this to:
[connection]
wifi.powersave=2
Where 3 means powersave enabled and 2 means disabled according to what I found in search.
This helped keeping the connection up when the laptop went to sleep, but I still got disconnected from the internet from time to time.
Luckilly, I was at the laptop at one time when it disconnected at which point this command:
sudo journalctl  --since="-5 minutes"

gave me a crucial tip:
kernel: wlx2cd05a59734b: Limiting TX power to 30 (30 - 0) dBm as advertised by 3c:84:6a:90:07:c6
kernel: wlx2cd05a59734b: deauthenticated from 3c:84:6a:90:07:c6 (Reason: 2=PREV_AUTH_NOT_VALID)
wpa_supplicant[1162]: wlx2cd05a59734b: CTRL-EVENT-DISCONNECTED bssid=3c:84:6a:90:07:c6 reason=2
wpa_supplicant[1162]: wlx2cd05a59734b: WPA: 4-Way Handshake failed - pre-shared key may be incorrect
wpa_supplicant[1162]: wlx2cd05a59734b: CTRL-EVENT-SSID-TEMP-DISABLED id=0 ssid="WIFI" auth_failures=1 duration=10 reason=WRONG_KEY
wpa_supplicant[1162]: BSSID 3c:84:6a:90:07:c6 ignore list count incremented to 2, ignoring for 10 seconds
wpa_supplicant[1162]: wlx2cd05a59734b: CTRL-EVENT-REGDOM-CHANGE init=CORE type=WORLD
NetworkManager[1130]: <info>  [1677521293.5474] device (wlx2cd05a59734b): supplicant interface state: 4way_handshake -> disconnected
NetworkManager[1130]: <info>  [1677521293.5476] device (wlx2cd05a59734b): Activation: (wifi) disconnected during association, asking for new key
Feb 27 10:08:13 christia-Lenovo-IdeaPad-Yoga-13 NetworkManager[1130]: <info>  [1677521293.5479] device (wlx2cd05a59734b): state change: activated -> need-auth (reason 'supplicant-disconnect', sys-iface-state: 'managed')

After this I changed my router encryption to WPA3 (and later back to WPA2 as not all my devices support WPA3) to reset the network key and that at least for the last 4 hours seemed to have done the trick.
(I could probably just have selected forget network and re-apply, but telling you exactly what i did just in case it will make a difference)
Hope this helps someone that faces the same issue.


text:
Q: what's the difference between softmax_cross_entropy_with_logits and losses.log_loss? whats the primary difference between tf.nn.softmax_cross_entropy_with_logits and tf.losses.log_loss? both methods accept 1-hot labels and logits to calculate cross entropy loss for classification tasks.

A: Those methods are not so different in theory, however have number of differences in implementation:
1) tf.nn.softmax_cross_entropy_with_logitsis designed for single-class labels, while tf.losses.log_losscan be used for multi-class classification. tf.nn.softmax_cross_entropy_with_logits won't throw an error if you feed multi-class labels, however your gradients won't be calculated correctly and training most probably will fail.
From official documentation:

NOTE: While the classes are mutually exclusive, their probabilities need not be. All that is required is that each row of labels is a valid probability distribution. If they are not, the computation of the gradient will be incorrect.

2) tf.nn.softmax_cross_entropy_with_logits calculates (as it's seen from the name) soft-max function on top of your predictions first, while log_loss doesn't do this.
3) tf.losses.log_loss has a little wider functionality in a sense that you can weight each element of the loss function or you can specify epsilon, which is used in calculations, to avoid log(0) value.
4) Finally, tf.nn.softmax_cross_entropy_with_logits returns loss for every entry in the batch, while tf.losses.log_loss returns reduced (sum over all samples by default) value which can be directly used in optimizer.
UPD: Another difference is the way the calculate the loss, Logarithmic loss takes into account negative classes (those where you have 0s in the vector). Shortly, cross-enthropy loss forces network to produce maximum input for the correct class and does not care about negative classes. Logarithmic loss does both at the same time, it forces correct classes to have larger values and negative lesser. In mathematic expression it looks as following:
Cross-enthropy loss:

Logarithmic Loss:

Where i is the corresponding class.
So for example, if you have labels=[1,0] and predictions_with_softmax = [0.7,0.3], then:
1) Cross-Enthropy Loss: -(1 * log(0.7) + 0 * log(0.3)) = 0.3567
2) Logarithmic Loss: - (1*log(0.7) + (1-1) * log(1 - 0.7) +0*log(0.3) + (1-0) log (1- 0.3)) = - (log(0.7) + log (0.7)) = 0.7133
And then if you use default value for tf.losses.log_loss you then need to divide the log_loss output by the number of non-zero elements (here it's 2). So finally: tf.nn.log_loss = 0.7133 / 2  = 0.3566
In this case we got equal outputs, however it is not always the case

A: There are basically two differences between,
1) Labels used in tf.nn.softmax_cross_entropy_with_logits are the one hot version of labels used in tf.losses.log_loss.
2) tf.nn.softmax_cross_entropy_with_logits calcultes the softmax of logits internally before the calculation of the cross-entrophy.
Notice that tf.losses.log_loss also accepts one-hot encoded labels. However,  tf.nn.softmax_cross_entropy_with_logits only accepts the labels with one-hot encoding.
Hope this helps.


text:
Q: partials not being rendered express-handlebars node I am trying to use express-handlebars and use partials but I am getting the following error message

The partial header could not be found.

My app.js code looks like as follows.
var express = require('express');
var exphbs  = require('express-handlebars');

var app = express();

app.engine('handlebars', exphbs({defaultLayout: 'main'}));
app.set('view engine', 'hbs');

app.get('/', function  (req, res) {
    res.render('home');
});

app.listen(3000);

This is all working and the express app is running on localhost:3000.
My folder structure is as follows:
|_app.js
|_views_
        |_home.hbs
        |_layouts_
                  |_main.hbs
        |_partials_
                   |_header.hbs

main.hbs
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Example App</title>

    {{{body}}}

header.hbs

  Home
  Contact

home.hbs
{{> header}}

Hey world!

Everything works as expected until I try and introduce header.hbs as a partial.
Can anyone see any issue with my code?
Following further investigation I have also tried this, without any success:
// Create `ExpressHandlebars` instance with a default layout.
var hbs = exphbs.create({
    // Uses multiple partials dirs, templates in "shared/templates/" are shared
    // with the client-side of the app (see below).
    partialsDir: [
        'views/partials/'
    ]
});

// Register `hbs` as our view engine using its bound `engine()` function.
app.engine('hbs', hbs.engine);
app.set('view engine', 'hbs');

A: I believe you are missing the next line:
exphbs.registerPartials(__dirname + '/views/partials');

A: It was necessary to define the following settings for express-handlebars partials to work.
var handlebars = require('express-handlebars');
app.engine('hbs', handlebars({ extname: '.hbs' }));
app.set('view engine', 'hbs');

Here is the complete code:
var handlebars = require('express-handlebars');
app.engine('hbs', handlebars({ extname: '.hbs' }));
app.set('view engine', 'hbs');

app.get('/', function (request, response) {
    response.render('home');
});


text:
Q: Null Pointer Debugging quick summary of what I'm trying to do.
Using shared preferences so that when a user watches a video a green tick will appear beside it to mark it as complete. Currently getting a null pointer error.
Basically there are two pages - main page and video page. When user lands on the main page the if statement should check the sharepreferences to see if they have already visited the video page. If they have it should display the completedTick imageView.
Please see the code and context below.
MAIN PAGE CODE SNIPPET:
 /**
 * Shared preferences variable which is used to store the userId which is captured at the login screen.
 */
private SharedPreferences loginPref, activityPref;
private ImageView completedTick;
private Boolean activityCompleted;

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    loginPref = getContext().getSharedPreferences("loginPref", Context.MODE_PRIVATE);
    activityPref = getContext().getSharedPreferences("activityPref", Context.MODE_PRIVATE);
    activityCompleted = activityPref.getBoolean("activityCompleted", true);

    View view = inflater.inflate(R.layout.fragment_activities, container, false);

    initialiseRecyclerView(view);
    retrieveActivities();

    if(activityCompleted == false || activityCompleted == null ) {
        completedTick.setVisibility(view.INVISIBLE);
    }else{
        completedTick.setVisibility(View.VISIBLE);
    }

    return view;

}

@Override
public void onViewCreated(@NonNull final View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

}

/**
 * Method which is used to initialise the recycler view
 *
 * @param view
 */
private void initialiseRecyclerView(View view) {
    mRecyclerView = view.findViewById(R.id.recyclerViewActivities);
    mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    EmptyAdapter emptyAdapter = new EmptyAdapter();
    mRecyclerView.setAdapter(emptyAdapter);
    completedTick = view.findViewById(R.id.completedTick);
}

VIDEO PAGE CODE SNIPPET:
private SharedPreferences activityPref;
private Boolean activityCompleted;

@Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.youtube_layout);

    Log.d(TAG, "onCreateView: Starting");
    activityPref = getSharedPreferences("activityPref", MODE_PRIVATE);
    activityCompleted = activityPref.getBoolean("activityCompleted", true);

        getExtrasMethod();
        initialiseViews();
        setTextInViews();
        checkCompleteD();

 private void checkCompleteD() {

    if (activityCompleted) {
        SharedPreferences.Editor editor = activityPref.edit();
        activityCompleted = false;
        editor.putBoolean("activityCompleted", activityCompleted);
        editor.apply();

    }
}

The error is :
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setVisibility(int)' on a null object reference
        at com.example.fit.ActivitiesFragment.onCreateView(ActivitiesFragment.java:78)

UPDATE:
Made the suggedted changes
@Override
public void onViewCreated(@NonNull final View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    loginPref = getContext().getSharedPreferences("loginPref", Context.MODE_PRIVATE);
    activityPref = getContext().getSharedPreferences("activityPref", Context.MODE_PRIVATE);
    activityCompleted = activityPref.getBoolean("activityCompleted", true);

    completedTick = view.findViewById(R.id.completedTickImage);
    initialiseRecyclerView(view);
    retrieveActivities();

    if (activityCompleted == false || activityCompleted == null) {
        completedTick.setVisibility(View.INVISIBLE);
    } else {
        completedTick.setVisibility(View.VISIBLE);
    }
}

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setVisibility(int)' on a null object reference
        at com.example.feelingfit.ActivitiesFragment.onViewCreated(ActivitiesFragment.java:85)
Which is this line :  completedTick.setVisibility(View.INVISIBLE);

A: First of all, your completedTick is null. Try putting the completedTick = view.findViewById(R.id.completedTick); in your OnViewCreated above this code:
if(activityCompleted == false || activityCompleted == null ) {
        completedTick.setVisibility(View.INVISIBLE);
    }else{
        completedTick.setVisibility(View.VISIBLE);
    }

And also,  replace the view.INVISIBLE with View.INVISIBLE
Edit + Aditional Information:
If you occur again the NullPointerException please refer to this link.
Edit 2:
Rewrite your code inside the onViewCreated method like this:
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    return inflater.inflate(R.layout.fragment_activities, container, false);

}

@Override
public void onViewCreated(@NonNull final View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
 loginPref = getContext().getSharedPreferences("loginPref", Context.MODE_PRIVATE);
        activityPref = getContext().getSharedPreferences("activityPref", Context.MODE_PRIVATE);
        activityCompleted = activityPref.getBoolean("activityCompleted", true);

        initialiseRecyclerView(view);
        retrieveActivities();

        if(activityCompleted == false || activityCompleted == null ) {
            completedTick.setVisibility(View.INVISIBLE);
        }else{
            completedTick.setVisibility(View.VISIBLE);
        }
}

Edit number 3: Since it is crashing again on the same use case I assume your R.id.completedTickImage is not inside your fragment_activities

A: Do the operation of CompleteTick.setVisibility inside onActivityCreated() method and also replace the view.INVISIBLE to View.INVISIBLE


text:
Q: Flowbite navbar hamburger not working on chrome browser I'm using flow-bite on my react js project I saw the Navbar hamburger not working (dropdown) on the Chrome browser but the same hamburger is working fine in firefox.
please tell me, How to Solve the Problem.

A: Several things you need to do:

*

*Try downgrading your react app 17.0.2. If your don't know how to then check this LINK

*Use flowbite CDN script in public index.html
<script src="https://unpkg.com/flowbite@1.4.4/dist/flowbite.js"></script>
Thats it it will work now.
Or you can use flowbite-React which is still in development  . Good Luck


text:
Q: Unable to decipher nvlink error I'm attempting to build a project with nvcc. I am getting the most vexing nvlink error: messages I've ever seen.
Here is the link statement:
nvcc    -rdc=true -arch=sm_21 -O3 -Xcompiler -fPIC -I"/usr/local/ACE_wrappers" -I"/usr/local/ACE_wrappers/TAO" -I"/usr/local/DDS" -I"/usr/include/Qt" -I"/usr/include/QtCore" -I"/usr/include/QtGui" -I"../../include" -I"../../include/DDS" -I"../../include/CoordinateTransforms" -I"../../include/DDS/IDLBrokerTemplates" -I"../../def/IDL" -I"../../def/CMD" -I"../../def/XSD" -I"../../src/NetAcquire" -I"/usr/local/ACE_wrappers/TAO/orbsvcs" -I"/usr/local/include/lct.7.5.4" -L"." -L"/usr/local/ACE_wrappers/lib" -L"/usr/local/DDS/lib" -L"/usr/lib64" -L"/usr/local/lib64" -L"../../def/IDL/lib" -L"../../def/XSD" -L"/usr/local/lib" .obj/../../src/Component.o .obj/../../src/COM.o .obj/../../src/DDS/EntityManager.o .obj/../../src/IDLBrokerTemplates/CommandManager.o .obj/../../src/IDLBrokerTemplates/OptionManager.o .obj/../../include/ApplicationProcessStateReporter_moc.o .obj/../../src/Application.o .obj/../../src/CoordinateTransforms/Site.o .obj/../../src/CoordinateTransforms/Geodesy.o .obj/../../src/CoordinateTransforms/Earth.o .obj/../../src/CoordinateTransforms/StateVector.o .obj/../../src/CoordinateTransforms/KeplerianImpact.o .obj/../../src/CoordinateTransforms/GeodeticPosition.o .obj/../../src/IDLBrokerTemplates/MeasurandSubscription.o .obj/../../src/NetAcquire/NetAcquire.o .obj/DataLossFlightTimeImpl.o .obj/DataLossFlightTime.o .obj/DftTable.o .obj/OptionListener.o .obj/PrimaryListener.o .obj/MissionTimeListener.o .obj/DeadMan.o .obj/main.o .obj/../../src/XML/spline.o .obj/../../src/XML/FpTable.o -l"naps-x86_64" -l"naio-x86_64" -l"nalct-x86_64" -l"curl" -l"TAO_Messaging" -l"TAO_Valuetype" -l"TAO_PI_Server" -l"TAO_PI" -l"TAO_CodecFactory" -l"TAO_CosNaming" -l"armadillo" -l"boost_filesystem" -l"boost_system" -l"xerces-c" -l"jarssXSD" -l"OpenDDS_Tcp" -l"JARSSRTv10" -l"QtNetwork" -l"fontconfig" -l"QtGui" -l"QtCore" -l"OpenDDS_Rtps_Udp" -l"OpenDDS_Rtps" -l"OpenDDS_Multicast" -l"OpenDDS_Udp" -l"OpenDDS_InfoRepoDiscovery" -l"OpenDDS_Dcps" -l"TAO_PortableServer" -l"TAO_AnyTypeCode" -l"TAO" -l"ACE"  -o "DFT"

And I'm getting
nvlink error   : Undefined reference to '_ZN5JARSS15KeplerianImpactC1ERKdS2_S2_S2_S2_S2_'
nvlink error   : Undefined reference to '_ZNK5JARSS15KeplerianImpact9getStatusEv'
nvlink error   : Undefined reference to '_ZNK5JARSS15KeplerianImpact13getImpactTimeEv'
nvlink error   : Undefined reference to '_ZNK5JARSS15KeplerianImpact11getPlhStateEv'
nvlink error   : Undefined reference to '_ZN5JARSS15KeplerianImpactD1Ev'
nvlink error   : Undefined reference to '_ZN5JARSS7Geodesy12EFG2GeodeticERKdS2_S2_PdS3_S3_'

I'm certain that these functions/files are included in the compile. You can see from the compile that KeplerianImpact.cpp and Geodesy.cpp are in there.
Is there any way to make the link output easier to read so I can debug this?

A: Use c++filt to demangle the names. For instance:

$ c++filt _ZN5JARSS15KeplerianImpactC1ERKdS2_S2_S2_S2_S2_
  JARSS::KeplerianImpact::KeplerianImpact(double const&, double const&, double const&, double const&, double const&, double const&)

A: Faced this problem earlier, I guess you haven't linked the device object using device linker.
Generate relocatable code for the device by compiling as shown below (-dc is the device equivalent of -c, see the manual for more information)
nvcc –arch=sm_21 –dc a.cu b.cu

Link the device parts of the code by calling nvlink or dlink before the final host link
nvlink -arch=sm_21 a.o b.o -o link.o (or)
nvcc –arch=sm_21 –dlink a.o b.o –o link.o

Finally form a executable using host compiler,
g++ a.o b.o link.o –L<path> -lcudart

A: I figured this out.
I needed to define my functions in the correct files. For example, in Foo.h:
class Foo {
public:
    __host__ __device__
    Foo();
}

and the function definition in Foo.cu not Foo.cpp as I originally thought.
 Foo::Foo() {}

For the constant variables, I needed to implement a slightly different strategy.
Here is an example of the C++ class that I started with:
class Foo {
public:
    static double const epsilon;
    static void functionThatUsesEpsilon();
    /**/
}

Had to be converted to use the global namespace as the epsilon def'n
namespace foo {
    extern __constant__ double epsilon;
}

class Foo {
public:
    // same stuff as before with the addition of this function
    __host__ __device__
    static inline double getEpsilon() {
#ifdef __CUDACC__
         return foo::epsilon;
#else
         return epsilon;
#endif
    }

    static void functionThatUsesEpsilon() {
        if (bar < getEpsilon()) { // etc }
    }
};

The ifdef above will return the correct version of the variable for either the host or the device code. Everywhere I had referenced Foo::epsilon I needed to replace with Foo::getEpsilon() so the correct epsilon was returned.
Hope this helps someone in the future. Thanks to @RobertCrovella for getting me thinking.


text:
Q: Realm Sync Facebook Authentication not working I am trying to enable Facebook authentication in Realm Sync, but keep getting an error on login.
I have been using these guides:

*

*https://docs.realm.io/sync/v/3.x/using-synced-realms/user-authentication/additional-providers#facebook

*https://docs.realm.io/sync/v/3.x/self-hosted/customize/authentication/included-third-party-auth-providers/facebook-authentication
I have the Access Token provided by the Facebook API/SDK enabling me to log in/sign up a user.
When I use Realm's libraries to log in a user with the Facebook Access Token, I get an error stating the 'provider' parameter is invalid, but this parameter is defined by Realm's own classes.
I have successfully authenticated a user with an email & password so do I need to set up something else on Facebook/Realm Sync? It seems Facebook authentication just doesn't work in Realm Sync and the above help files are pretty useless.
Authentication code
func authenticateWithFacebook(facebookToken: String, completion: @escaping (RealmAuthenticationResult) -> ()) {
    let credentials = SyncCredentials.facebook(token: facebookToken)

    print("------FACEBOOK LOGIN-------")
    print("Token: \(facebookToken)")

    login(credentials) { (result, userId) in
        completion(result)
    }
}

private func login(_ credentials: SyncCredentials, completion: @escaping (RealmAuthenticationResult, String?) -> ()) {

    SyncUser.logIn(with: credentials, server: RealmConnection.AUTH_URL, onCompletion: { (user, err) in
        if let _ = user {
            print("User has logged in/signed up")
            return completion(RealmAuthenticationResult.success(true), user?.identity)
        } else if let error = err {
            print(error.localizedDescription)
            return completion(RealmAuthenticationResult.failure(error), user?.identity)
        }
    })
}

The error

Error Domain=io.realm.sync.auth Code=601 "Your request parameters did
  not validate. provider: Invalid parameter 'provider'!;"
  UserInfo={NSLocalizedDescription=Your request parameters did not
  validate. provider: Invalid parameter 'provider'!;}

Other things I have tried
I have tried directly instantiating the base provider class 'RLMIdentityProvider' and creating SyncCredentials with that, but no dice.
A workaround is to get the account information from the Facebook API/SDK and use the account's email to login/signup with a username/password setup. However, it seems to make Facebook authentication redundant.

A: That Realm Documentation link is outdated. See the 3.16.0 Documentation (or later) as a lot was changed.
At the moment Password, JWT & Firebase are the only auth options with Firebase Authentication being a very solid solution. Integrating Firebase is also covered in the Realm Documentation in the Using Sync'd Realms -> Authentication section. I won't link it as the documentation is being frequently updated now days.
As stated by the Realm Team (several times) extensive auth options are not a priority as other companies (like Firebase) handle it very well.
There were a number of posts on the Realm forums speaking to this but Ian's response to this question is very succinct.

we have and will continue to prioritize synchronization features for
  mobile

and then

This is why we recommend that a production app should outsource user
  management and authentication to a company which specialized in these
  features.


text:
Q: How to find files that don't have empty line at the end? I have files in subdirectories of the current directory that may or may not have new lines at the end; how can I find files that don't have a newline at the end?
I've tried this:
find . -name '*.styl' | while read file; do
    awk 'END{print}' $file | grep -E '^$' > /dev/null || echo $file;
done

but it doesn't work.  awk 'END{print}' $file prints the line before an empty new line, the same as tail -n 1 $file.

A: With gnu sed and a shell like zsh (or bash with shopt -s globstar):
sed -ns '${/./F}' ./**/*.styl

this checks if the last line of each file is not empty, if so it prints the filename.
If you want the opposite (print file names if the last line is empty) just replace /./ with /^$/

A: A correctly terminated text file with an empty last line ends in two \n.
Then, we expect that tail -c2 must be equal to $'\n\n'.
Sadly command expansions remove trailing new lines. We will need a bit of tweaking.
f=filename
nl='
'
t=$(tail -c2 $f; printf x)  # capture the last two characters.
r="${nl}${nl}$"                 # regex for: "ends in two newlines".
[[ ${t%x} =~ $r ]] &&  echo "file $f ends in an empty line"

We could even expand a bit to check which files fail to have a trailing new line:
nl='
'
nl=$'\n'
find . -type f -name '*.styl' | while read f; do
    t=$(tail -c2 $f; printf x); r1="${nl}$"; r2="${nl}${r1}"
    [[ ${t%x} =~ $r1 ]] || echo "file $f is missing a trailing newline"
    [[ ${t%x} =~ $r2 ]] && echo "$f"
done

Note that the newline could be changed to something like $'\r\n if needed.
In that case, also change tail -c2 to tail -c4.

A: To clarify, the LF (aka \n or newline) character is the line delimiter, it's not the line separator. A line is not finished unless it's terminated by a newline character. A file that only contains a\nb is not a valid text file because it contains characters after the last line. Same for a file that contains only a. A file that contains a\n contains one non-empty line.
So a file that ends with at least one empty line ends with two newline characters or contains a single newline character.
If:
 tail -c 2 file | od -An -vtc

Outputs \n or \n \n, then the file contains at least one trailing empty line. If it outputs nothing, then that's an empty file, if it outputs <anything-but-\0> \n, then it ends in a non-empty line. Anything else, it's not a text file.
Now, to use that to find files that end in an empty line, OK that's efficient (especially for large files) in that it only reads the last two bytes of the files, but first the output is not easily parsable programmatically especially considering that it's not consistent from one implementation of od to the next, and we'd need to run one tail and one od per file.
find . -type f -size +0 -exec gawk '
  ENDFILE{if ($0 == "") print FILENAME}' {} +

(to find files ending in an empty line) would run as few commands as possible but would mean reading the full content of all files.
Ideally, you'd need a shell that can read the end of a file by itself.
With zsh:
zmodload zsh/system
for f (**/*(D.L+0)) {
  {
    sysseek -w end -2
    sysread
    [[ $REPLY = $'\n' || $REPLY = $'\n\n' ]] && print -r -- $f
  } < $f
}


text:
Q: What is the syntax for SELECT IN statement for SQLITE? I have the following MySQL statement that runs correctly in MySQL workbench:
SELECT *, max(invoiceDate)
AS latestDate
FROM goodsreceiptrecords
WHERE (productKey, productIdentifier2)
IN ((23,'Master'),(28,'Local'),(18,'Local'),(19,'Local')) AND unitPrice > 0
GROUP BY productKey, productIdentifier1, vendorKey, storeType;

I tried using the same syntax for SQLITE but I am getting an error messase of:
sqlite3_prepare_v2 failure: row value misused

What would be the correct syntax for this SELECT statement in MySQL?  Basically, What I am trying to do is select records that matches the values of 2 columns from the table

A: The documentation says:

For a row-value IN operator, the left-hand side (hereafter "LHS") can be either a parenthesized list of values or a subquery with multiple columns. But the right-hand side (hereafter "RHS") must be a subquery expression.

But a VALUES clause can replace a subquery, so just use:
...
WHERE (productKey, productIdentifier2)
   IN (VALUES(23,'Master'),(28,'Local'),(18,'Local'),(19,'Local'))
...


text:
Q: Complex SQL Join on sub query with top 1 records I'm trying to write a query that looks something like below.
select t1.t1c1, t1.t1c2, t2.t2c3, t2.t2c4
from table1 t1
left outer join (select top 1 t2c1, t2c2, t2c3, t2c4 from table2
                 where t2c5 in (select t3c1 from table3 t3
                                where **t3c2 = t1.t1c2 and t3c3 = t1.t1c3**) t2
           on t1.t1c1 = t2.t2c1 and t1.t1c2 = t2.t2c2

What SQL Server does not allow is the highlighted text above - i.e. referencing the table1's columns in the table3 sub query.
Is there a way to achieve this?
I understand that this might not be the most optimal way, is there any other way to achieve this?

A: You seem to exactly want outer apply.  I think it would look like this:
select t1.t1c1, t1.t1c2, t2.t2c3, t2.t2c4
from table1 t1 outer apply
     (select top 1 t2c1, t2c2, t2c3, t2c4
      from table2
      where t2c5 in (select t3c1
                     from table3 t3
                     where t3c2 = t1.t1c2 and t3c3 = t1.t1c3
                    ) and
            t1.t1c1 = t2.t2c1 and t1.t1c2 = t2.t2c2
     ) t2;

APPLY is a lot like using a correlated subquery, except it goes in the FROM clause and can return multiple columns and multiple rows.
Note:  You should be using ORDER BY when you use TOP.


text:
Q: adding a file at publish time I completed my winform application.
I want to add a csv file. So my application will reach with this path.
How can I get published locastion's path?

A: I think you mean following with published locations:
Environment.CurrentDirectory
Environment.GetFolderPath(...)

with one of following parameter
SpecialFolder.ApplicationData
SpecialFolder.Desktop
...

etc.
See http://msdn.microsoft.com/en-us/library/system.environment.specialfolder.aspx

A: If you programmatically want to get your form's execution path to access your CSV, use
string path = (new System.Uri(Assembly.GetExecutingAssembly().CodeBase)).AbsolutePath;
inside your form.
and then Path.Combine(path, CSVFilename);


text:
Q: C# DateTime.ParseExact for "2012-09-03T06:35:31Z" In C# I am trying to convert "2012-09-03T06:35:31Z" into a Datetime:
Date = DateTime.ParseExact( "2012-09-03T06:35:31Z", ???);

I'm not sure how to parse the rest of the function

A: //using System.Globalization; should be at top

Date = DateTime.ParseExact("2012-09-03T06:35:31Z", "yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal)

See the custom date and time format documentation.  This is similar to the sortable format, but with a Z on the end.

A: You don't say whether the format is specified as always being in UTC and indicated with Z.
If that is the case, then
DateTime.ParseExact(
  yourDateString, @"yyyy\-MM\-ddTHH:mm:ss\Z",
  CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal)

Will do fine.
However, if UTC is not specified by the standard you are working to, the input you have to deal with could also be e.g. 2012-09-03T06:35:31+05:00 or 2012-09-03T06:35:31+0500 depending on the ISO 8601 format in use - Z is a special case within that format for +00:00. If you need to handle that possibility, then you want to first create a DateTimeOffset, and then obtain the equivalent UTC DateTime from it:
DateTimeOffset.ParseExact(yourDateString,
  new string[]{@"yyyy\-MM\-ddTHH:mm:sszzz",@"yyyy\-MM\-ddTHH:mm:ss\Z"},
  CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal).UtcDateTime

Note that we still use AssumeUniversal. This is because the second format is saying "A Z will appear here", but the method then ignores it, so we have to explicitly have this form interpreted as UTC. With the first format though, the zzz will give the timezone, and hence the AssumeUniversal is ignored. (Or to put it another way, it's assuming universal until told otherwise, and that format does indeed say otherwise).

A: Looks like you are trying to parse an Xml date.  If this is the case I would suggest using the XmlConvert class...
Date = System.Xml.XmlConvert.ToDateTime("2012-09-03T06:35:31Z", XmlDateTimeSerializationMode.Local);

You will need to change the XmlDateTimeSerializationMode to the appropriate value.


text:
Q: Is there a way to determine immediately if a function is holomorphic or not? I started complex analysis a few weeks ago and we are at the part where we are introduced to the Laurent expansions! I noticed particularly that in some of the solved exercise examples that it is immediately mentioned that "this function is holomorphic on" a certain set! I know that to prove that a function is holomorphic i guess you can use the Caushy-Goursat(dont remember if this was the name of the formula. Im talking about the one where you compare the partial derivatives) theorem but is there lets say some tricks you can use to determine if a function is holomorphic or not? In all honesty i still dont understand what it means for a complex function to be holomorphic? What does it mean and how does it help us? Can someone help me?

A: You probably mean the Cauchy-Riemann equations. This is a rather unspecific question, but here we go, at least giving some general directions. A complex function is holomorphic on a domain if it is complex differentiable in that domain. A function $f$ is is complex differentiable at a point $z$ if the complex limit
$$\lim_{h \to 0} \frac{f(z+h)-f(z)}{h}$$
exists.
One can show, and this is one of the main features of a typical introductory course in complex analysis, that holomorphicity is equivalent to analyticity. A function is analytic if it is locally equal to its Taylor expansion.
You can immediately see that a function is holomorphic if it built up from holomorphic functions by addition, subtraction, multiplication, division and composition. The elementary functions polynomials, the exponential function and trigonometric function are all holomorphic. Rational functions are also holomorphic on all domains where its denominator is non-zero. Logarithmic functions are holomorphic except at its branch cut.
I also add that a nice and applied introduction to complex analysis introducing these topics in an easily accessible manner is Saff & Snider: Fundamentals of Complex Analysis.


text:
Q: How do I highlight a bunch of files with Mousekeys in Windows Explorer? When I try to highlight a couple of files it doesn't work when I only use Mousekeys.  When I use the right-click button and try to highlight with the arrow keys of the mumberpad nothing happens...how do I highlight files in Explorer using only Mousekeys?
Win 7 Pro.

A: If you are trying to highlight or select by dragging: Press 0, then move the cursor selecting the desired area and press . to stop.
If you are trying to select multiple files: Use 5 to click on a file, then hold Ctrl and press 5 to select additional files. Or to select all files in order: click the first file, hold Shift and click the last file to select all files in between and inclusive of the clicked files (same as with using the normal mouse).
Windows documentation on using Mouse Keys


text:
Q: java.lang.NoClassDefFoundError: com.itextpdf.text.Document I have added the .jar files into my existing project as described in http://www.vogella.com/articles/Eclipse/article.html#classpath .
When I try to run the emulator I end up with "java.lang.NoClassDefFoundError: com.itextpdf.text.Document"
My .classpath file :
<classpath>
        <classpathentry kind="src" path="src"/>
        <classpathentry kind="src" path="gen"/>
        <classpathentry kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/>
        <classpathentry kind="con" path="com.android.ide.eclipse.adt.LIBRARIES"/>
        <classpathentry kind="lib" path="lib/itext-pdfa-5.3.3-javadoc.jar"/>
        <classpathentry kind="lib" path="lib/itext-pdfa-5.3.3-sources.jar"/>
        <classpathentry kind="lib" path="lib/itext-pdfa-5.3.3.jar"/>
        <classpathentry kind="lib" path="lib/itext-xtra-5.3.3-javadoc.jar"/>
        <classpathentry kind="lib" path="lib/itext-xtra-5.3.3-sources.jar"/>
        <classpathentry kind="lib" path="lib/itext-xtra-5.3.3.jar"/>
        <classpathentry kind="lib" path="lib/itextpdf-5.3.3-javadoc.jar"/>
        <classpathentry kind="lib" path="lib/itextpdf-5.3.3-sources.jar"/>
        <classpathentry kind="lib" path="lib/itextpdf-5.3.3.jar"/>
        <classpathentry kind="output" path="bin/classes"/>
</classpath>

MainActivity.java
package com.example.tmp;

import java.io.FileOutputStream;

import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfWriter;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

          String FILE = "/home/ronline/Desktop/FirstPdf.pdf";
        try {
            Document document=new Document();
              PdfWriter.getInstance(document, new FileOutputStream(FILE));
              document.open();
              document.close();
            } catch (Exception e) {
              e.printStackTrace();
            }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}

A: For unknown reason getting the jars to Java Library through eclipse interfaces doesn't work. Manual copy / past into libs folder does the trick. Thx to  Parth Doshi suggestion.

A: You should download jar from  Here and then try.


text:
Q: mock a function inside python pyramid view I have a python pyramid view and want to write a unittest.
def home(request):
    state = request.params.get('redirect', None)
    cookie = request.headers.get('Cookie')
    user = identify_session_user(cookie , request.registry.settings)
    response = HTTPFound(location=state)
    response.set_cookie('USERINFO',
                             base64.b64encode(json.dumps(user).encode('ascii')),
                             domain='test.com')

    return response

Simple unittest:-
def test_hello_world(self):
    from tutorial import home

    request = testing.DummyRequest()
    response = hello_world(request)
    self.assertEqual(response.status_code, 200)

How can I mock the idenfify_session_user function that is called inside my home view?

A: This might not be the exact answer your question, but is an alternative way to solve the problem.
Instead of mocking a view or the whole session machinery in Pyramid, you can do integration testing based on WebTest. This might be easier to set up, but tests are little bit slower to run.


text:
Q: How to use Gridsearchcv to tune BaseEstimators within AdaBoostClassifier from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import GridSearchCV
from sklearn.ensemble import AdaBoostClassifier

from sklearn.datasets import make_classification
# generate dataset
X, y = make_classification(n_samples=100, n_features=2, n_redundant=0,
    n_clusters_per_class=1, weights=[0.50], flip_y=0, random_state=4)

abc = AdaBoostClassifier(base_estimator=DecisionTreeClassifier())

parameters = {'base_estimator__max_depth':[i for i in range(2,11,2)],
              'base_estimator__min_samples_leaf':[1,2],
              'n_estimators':[10,50,250,1000],
              'learning_rate':[0.01,0.1]}

clf = GridSearchCV(abc, parameters,verbose=3,scoring='f1',n_jobs=-1)
clf.fit(X,y)

Here I am using GridsearchCV to tune AdaBoostClassifier as well as the base estimator which is
DecisionTreeClassifier. Can I use GridsearchCV to tune AdaBoostClassifier and more than one base estimator, (decisiontree and SVC,...) at the same time?**

A: Specify a list of parameter grids of every base estimator:
from sklearn.dummy import DummyClassifier
from sklearn.ensemble import AdaBoostClassifier
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import Pipeline
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier

parameters = [
    {'boost': [AdaBoostClassifier(base_estimator=DecisionTreeClassifier())],
     'boost__base_estimator__max_depth': (None, 10),
     'boost__learning_rate': (0.01, 0.1)},
    {'boost': [AdaBoostClassifier(base_estimator=SVC())],
     'boost__base_estimator__degree': (2, 3),
     'boost__learning_rate': (0.01, 0.1)},
]
boost_pipe = Pipeline([('boost', DummyClassifier())])
grid = GridSearchCV(boost_pipe, parameters)


text:
Q: Illegal character in statement label field - when compiling .f extension I tried to compile .f files using ifort.
I got following errors:
/.../wreqvr.f(2): error #5149: Illegal character in statement label field  [h]
   This file is part of the GNU C Library.
----^
From the following suggestion:
https://software.intel.com/en-us/forums/intel-visual-fortran-compiler-for-windows/topic/293662
-> says that changing the extension .f to .f90 works.
Is there any other solution? (I don't want to change the extension because the code is managed by git...)
I used the same ifort version for my old machine which works well without error.
I don't understand why this error comes out.
The only difference between my old machine and new machine is the centos version (old 6, new 7)
Does the gcc version matter regarding this error?

I added part of the code and error msg. here: coord.f file
/* Copyright (C) 1991-2012 Free Software Foundation, Inc.
   This file is part of the GNU C Library.

   The GNU C Library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.

   The GNU C Library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General Public
   License along with the GNU C Library; if not, see
   <http://www.gnu.org/licenses/>.  */

/* This header is separate from features.h so that the compiler can
   include it implicitly at the start of every compilation.  It must
   not itself include <features.h> or any other header that includes
   <features.h> because the implicit include comes before any feature
   test macros that may be defined in a source file before it first
   explicitly includes a system header.  GCC knows the name of this
   header in order to preinclude it.  */

/* We do support the IEC 559 math functionality, real and complex.  */

/* wchar_t uses ISO/IEC 10646 (2nd ed., published 2011-03-15) /
   Unicode 6.0.  */

/* We do not support C11 <threads.h>.  */

      subroutine coord(vx,vy,n,d,x,y)

c  version : 21.07.2000 16:18
c=======================================================================
      implicit none
c*** Calculate the x and y coordinates of a point located on a curve v
c*** at a distance d from the origin of the curve

*  arguments
      integer n
      real*8 vx(n),vy(n),d,x,y

*  variables locales
      integer i
      real*8 dist,distot,eps
      parameter (eps=1.e-06)

*  procedures
      intrinsic sqrt

c========================
c.. n   : number of points in the curve
c.. vx,vy: coordinates of the points in the curve
c.. d   : required distance along the curve
c.. x,y : coordinates of the found point
c.. dist: distance between 2 consecutive points on the curve
c.. distot: total distance covered
c========================

*..Initialisation.

      distot = 0.0

*..Loop over the curve segments

      do i=1, n-1 !{

         dist = sqrt((vx(i+1)-vx(i))**2 + (vy(i+1)-vy(i))**2)
         distot = distot + dist

*..Check whether the distance d is passed

         if (distot .ge. d) then !{
            x = vx(i+1) - ((distot-d)/dist)*(vx(i+1)-vx(i))
            y = vy(i+1) - ((distot-d)/dist)*(vy(i+1)-vy(i))

            return

         end if !}

      end do  !}
c*** Check whether the required distance is equal - within tolerance -
c*** to the total curve length

      if (abs(distot - d) .lt. eps) then !{
         x = vx(n)
         y = vy(n)

         return

      end if !}

*..Error: required distance greater than the total curve length.

      print *, 'coord: required distance greater than the total length'
      print*,'distot=',distot
      print*,'d=',d
      call pltend
      stop  'Check the target specification'

      end

$ ifort coord.f
coord.f(1): error #5149: Illegal character in statement label field  [/]
/* Copyright (C) 1991-2012 Free Software Foundation, Inc.
^
coord.f(1): error #5149: Illegal character in statement label field  [*]
/* Copyright (C) 1991-2012 Free Software Foundation, Inc.
-^
coord.f(1): error #5149: Illegal character in statement label field  [C]
/* Copyright (C) 1991-2012 Free Software Foundation, Inc.
---^
coord.f(1): error #5149: Illegal character in statement label field  [o]
/* Copyright (C) 1991-2012 Free Software Foundation, Inc.
----^
coord.f(1): error #5118: First statement in file must not be continued
/* Copyright (C) 1991-2012 Free Software Foundation, Inc.
-----^
coord.f(2): error #5149: Illegal character in statement label field  [T]
   This file is part of the GNU C Library.
---^
coord.f(2): error #5149: Illegal character in statement label field  [h]
   This file is part of the GNU C Library.
----^
coord.f(4): error #5149: Illegal character in statement label field  [T]
   The GNU C Library is free software; you can redistribute it and/or
---^
coord.f(4): error #5149: Illegal character in statement label field  [h]
   The GNU C Library is free software; you can redistribute it and/or

$ ifort -free coord.f
or
$ ifort coord.f90
coord.f(1): error #5082: Syntax error, found '/' when expecting one of: <LABEL> <END-OF-STATEMENT> ; BLOCK BLOCKDATA PROGRAM MODULE TYPE BYTE CHARACTER ...
/* Copyright (C) 1991-2012 Free Software Foundation, Inc.
^
coord.f(16): error #5145: Invalid blank/tab
   <http://www.gnu.org/licenses/>.  */
----------------------------------^
coord.f(20): error #5145: Invalid blank/tab
   include it implicitly at the start of every compilation.  It must
-----------------------------------------------------------^
coord.f(29): error #5143: Missing mandatory separating blank
/* wchar_t uses ISO/IEC 10646 (2nd ed., published 2011-03-15) /
--------------------------------^
coord.f(30): error #5145: Invalid blank/tab
   Unicode 6.0.  */
---------------^

A: If the files are the original files you are compiling then you should delete the C style comments.
They begin with /* and end with */.
These blocks are not legal Fortran. C preprocessor discards them, but even if you enable pre-processing by ifort -fpp they will not be discarded. Only the C pre-processor discards them.
See also How do I compile this Fortran code with new 2017 ifort? for a similar problem.
It is almost certain that someone created those files by using the C preprocessor before. And that is wrong. Don't use the C preprocessor on its own for Fortran source files.
And don't use gcc to preprocess Fortran sources, it is a C preprocessor and it uses the C preprocessor in a wrong mode. You can use the preprocessor through Fortran compilers (gfortran -cpp or ifort -fpp - be careful cpp and fpp slightly differ), but don't use the C preprocessor directly and don't use C compilers.

A: Even though this has been answered, I just ran into the same issue.
What helped is this tread and also this:
https://software.intel.com/en-us/forums/intel-visual-fortran-compiler-for-windows/topic/293662 (even though I'm on linux)
The combination of .f90 and the usage if ifort instead of f77 helped.
If the build system relies on setting FC, F77, etc. (also MPIF77) make sure to set them to ifort (and mpiifort) accordingly.
If different sub-steps default to different tools for consecutive tasks you generally run into issues, so rather control them explicitly, according to your build system.


text:
Q: What is the purpose of using php inside css link tag? I've come across this recently and don't understand. I've Googled, but not sure what I should be Googleing to find answers to my questions.
<link type="text/css" rel="stylesheet" href="css/global.css<?=$debug?'?'.rand():''?>" />

I noticed something like this broke an entire website's styles.

A: This appends a random number to the CSS URL if debug mode is on.
It's done to break caching.

A: That particular php code intends to avoid that CSS resource being stored in a browser's cache. That's because you add a random string as a parameter to the HTTP request, (more technical details)... in the end it always looks as a different file to the browser, so it downloads it again