text:
Q: How to Save Data With User Auth id In Table Using Laravel Ajax
I have to save data in a database table with userid using laravel ajax. Can anyone please help me to solve this issue
my controller code
public function store(Request $request)
    {

        $rearcameras = new Rearcameras();
        $rearcameras->user_id = auth()->id();
        $rearcameras->name = $request->name;
        $rearcameras->size = $request->size;
        $rearcameras->type = $request->type;

        return $this->sendResponse($rearcameras->toArray(), 'Command Send Successfully successfully.');
    }

and the response it getting is
{"success":true,"data":{"user_id":null,"name":null,"size":null,"type":"f-camera"},"message":"Command Send Successfully successfully."}

I have to save logged userId on submitting....I'm getting user_id null how can I store user_id please help me.

Thanks in advance

A: Update your controller code
public function store(Request $request)
{
    $rearcameras = new Rearcameras();
    $rearcameras->user_id = Auth::user()->id;
    $rearcameras->name = $request->name;
    $rearcameras->size = $request->size;
    $rearcameras->type = $request->type;
    $rearcameras->save();
    return $this->sendResponse($rearcameras->toArray(), 'Command Send Successfully successfully.');
}

Don't forget to use use Auth at the top of the controller


text:
Q: Issue to create jpa - hibernate inner join query i am new to jpa hibernate, i have an inner join query in sql but not sure how to create the same query in jpa-hibernate syntax:
Basically i have 3 tables:
ORDERTBL(ORDERID(PK),ORDERDATE,ORDERSTATUS),
   PRODUCT(PRODUCTID(PK),PRODUCT_NAME),
   ORDERLINKPRODUCTS(ORDERID(PK),PRODUCTID(FK),QUANTITY,ORDERLINKPRODUCTID(FK))
I want to get all the product name from the products tables for a specific order which i should query from ORDERLINKPRODUCT since it contains all the orders.
Please find my Products class below:
@Table(name = "PRODUCTS")
@Entity
public class Products { /**
 *
 */
private static final long serialVersionUID = -3882913429956818022L;

@Column(name = "PRODUCTID")
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@Column(name = "PRODUCT_NAME")
private String productName;

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getProductName() {
    return productName;
}

public void setProductName(String productName) {
    this.productName = productName;
}

}
Please find my Orderclass below:
    @Table(name = "ORDERTBL")
@Entity
public class Order {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "ORDERID")
private Long id;

@Column(name = "ORDERDATE")
private Date orderdate;

@Column(name = "ORDERSTATUS")
private String orderSatus;

public String getOrderSatus() {
    return orderSatus;
}

public void setOrderSatus(String orderSatus) {
    this.orderSatus = orderSatus;
}

public Long getId() {
    return id;
}

public void setId(Long id) {
    this.id = id;
}

public Date getOrderdate() {
    return orderdate;
}

public void setOrderdate(Date orderdate) {
    this.orderdate = orderdate;
}

}
Please find my ProductOder  class below:
    @Entity
@Table(name = "ORDERLINKPRODUCTS")
public class ProductOder implements Serializable {

/**
 *
 */
private static final long serialVersionUID = 8420487251416906739L;

@Column(name = "ORDERLINKID")
@Id
private int orderLinkId;
@Column(name = "ORDERID")
@GeneratedValue(strategy = GenerationType.AUTO)
private int orderId;
@Column(name = "PRODUCTID")
private int productId;
@Column(name = "QUANTITY")
private int quantity;

public int getOrderLinkId() {
    return orderLinkId;
}

public void setOrderLinkId(int orderLinkId) {
    this.orderLinkId = orderLinkId;
}

public int getOrderId() {
    return orderId;
}

public void setOrderId(int orderId) {
    this.orderId = orderId;
}

public int getProductId() {
    return productId;
}

public void setProductId(int productId) {
    this.productId = productId;
}

public int getQuantity() {
    return quantity;
}

public void setQuantity(int quantity) {
    this.quantity = quantity;
}

}
Please find below my sql query that i want to create in JPA-Hibernate:
SELECT prod.PRODUCT_NAME
    FROM ORDERTBL ord
    INNER JOIN ORDERLINKPRODUCTS link ON ord.ORDERID = link.ORDERID
    INNER JOIN products prod ON link.PRODUCTID = prod.PRODUCTID
    WHERE ord.ORDERID = 1

Please find below my method with no implementation that will contains the jpa-hibernate query:
@Override
@SuppressWarnings("unchecked")
public List<Order> getOrderDetailsById(int id) {
    // TODO Auto-generated method stub
    //String hql = "from Person p, where p.firstName = :firsName and p.password //password";
    //return entityManager.createQuery("select o from Products o")
            //.getResultList();
}

Any suggestion how to do it please?
Thanks in advance.

A: Try changing you entities to:
Order
@Entity
@Table(name = "ORDER")
public class Order {

    @Id
    @Column(name = "ORDERID")
    private Long id;

    @Column(name = "ORDERDATE")
    private Date orderdate;

    @Column(name = "ORDERSTATUS")
    private String orderStatus;

    @OneToMany(mappedBy = "order", fetch = FetchType.EAGER)
    private List<OrderItem> items;
}

OrderItem
@Entity
@Table(name = "ORDERITEM")
public class OrderItem {

    @Id
    @Column(name = "ORDERITEMID")
    private Long id;

    @ManyToOne
    @JoinColumn(name = "ORDERID")
    private Order order;

    @ManyToOne
    @JoinColumn(name = "PRODUCTID")
    private Product product;

    @Column(name = "QUANTITY")
    private int quantity;
}

Product
@Entity
@Table(name = "PRODUCT")
public class Product {

    @Id
    @Column(name = "PRODUCTID")
    private Long id;

    @Column(name = "NAME")
    private String name;
}

And the query:
public List<OrderItem> getOrderDetailsById(Long id) {
    Product product = entityManager.find(Product.class, id);
    return product.getOrderItems();
}

public void showProductsInOrder(Long id) {
    List<OrderItem> items = getOrderDetailsById(id);
    for (OrderItem item: items) {
        Product product = item.getProduct();
        System.out.println("Product: " + product.getName() + ", Quantity: " + product.getQuantity());
    }

Database:
ORDER (ORDERID (PK), ORDERDATE, ORDERSTATUS)
ORDERITEM (ORDERITEMID (PK), ORDERID (FK), PRODUCTID (FK), QUANTITY)
PRODUCT (PRODUCTID (PK), NAME)

It's untested, but I hope it will work.

redpajama_set_name: RedPajamaStackExchange


text:
Q: adding default values to item x group pairs that don't have a value (df %>% spread %>% gather seems strange) Short version
How to do the operation
df1 %>% spread(groupid, value, fill = 0) %>% gather(groupid, value, one, two)

in a more natural way?
Long version
Given a data frame
df1 <- data.frame(groupid = c("one","one","one","two","two","two", "one"),
                  value = c(3,2,1,2,3,1,22),
                  itemid = c(1:6, 6))

for many itemid and groupid pairs we have a value, for some itemids
there are groupids where there is no value.  I want to add a default
value for those cases.  E.g. for the itemid 1 and groupid "two" there
is no value, I want to add a row where this gets a default value.
The following tidyr code achieves this, but it feels like a strange
way to do it (the default value added here is 0).
df1 %>% spread(groupid, value, fill = 0) %>% gather(groupid, value, one, two)

I am looking for suggestions on how to do this in a more natural way.
Since in some weeks looking at the above code I would likely be confused
about its effect I wrote a function wrapping it:
#' Add default values for missing groups
#'
#' Given data about items where each item is identified by an id, and every
#' item can have a value in every group; add a default value for all groups
#' where an item doesn't have a value yet.
add_default_value <- function(data, id, group, value, default) {
  id = as.character(substitute(id))
  group = as.character(substitute(group))
  value = as.character(substitute(value))
  groups <- unique(as.character(data[[group]]))

  # spread checks that the columns outside of group and value uniquely
  # determine the row.  Here we check that that already is the case within
  # each group using only id.  I.e. there is no repeated (id, group).
  id_group_cts <- data %>% group_by_(id, group) %>% do(data.frame(.ct = nrow(.)))
  if (any(id_group_cts$.ct > 1)) {
    badline <- id_group_cts %>% filter(.ct > 1) %>% top_n(1, .ct)
    stop("There is at least one (", id, ", ", group, ")",
         " combination with two members: (",
         as.character(badline[[id]]), ", ", as.character(badline[[group]]), ")")
  }

  gather_(spread_(data, group, value, fill = default), group, value, groups)
}

Last note: reason for wanting this is, my groups are ordered (week1, week2, ...)
and I am looking to have every id have a value in every group so that after
sorting the groups per id I can use cumsum to get a weekly running total that
is also shown in the weeks where the running total didn't increase.

A: There is a new function complete in the development version of tidyr that does this.
df1 %>% complete(itemid, groupid, fill = list(value = 0))
##    itemid groupid value
## 1       1     one     3
## 2       1     two     0
## 3       2     one     2
## 4       2     two     0
## 5       3     one     1
## 6       3     two     0
## 7       4     one     0
## 8       4     two     2
## 9       5     one     0
## 10      5     two     3
## 11      6     one    22
## 12      6     two     1

A: One possibility is to use expand from tidyr. This approach is very similar to the expand.grid idea of @akrun (it actually uses expand.grid internally). I used the dplyr package for the housekeeping after joining the expanded data with the original data.
This approach is longer than the spread/gather approach. Personally I find it a bit more clear what is going on. In my (rather small) benchmark test, spread/gather performed slightly better than expand/join.
# expand first
expand(df1, itemid, groupid) %>%
  # then join back to data
  left_join(df1, by = c("itemid", "groupid")) %>%
  # because there is no fill argument in join
  mutate(value = ifelse(is.na(value), 0, value)) %>%
  # rearange
  arrange(groupid, itemid)


text:
Q: What specifications of RAM module should I use for this PC? I want to upgrade my PC RAM module from 4GB to 8GB and I am a bit confused of the speed the 8GB module should be.
The instructions on the manual I downloaded says this:
Except I am misunderstanding something, the current 4GB module concurs:

But the specifications of the PC says something different:

What I know:
The 8GB RAM I want to buy should be: PC3L, 12800.
What I don't know
The speed. Please is it 1600-MHz or 1333MHz?
EDIT
More of the PC info:

A: It could run at 1600 MHz but for whatever reason your system is using 1333 MHz. This usually can be changed in the BIOS (if possible). Your CPU doesn't seem support anything other than 1333 MHz. Faster modules are clocked down.

A: Yes, as Seth says, it will be clocked down.
However, you could benefit from adding maximum amount of RAM. Your motherboard supports up to 16GB RAM.

A: If you put RAM with a higher frequency but your Computer does not support the higher frequency the RAM will run at a lower speed. The answers before this one suggested the same.


text:
Q: Probability Question: In what region must the center lie to ensure that the disk lies entirely on one tile? I am reading this problem of the ninth edition of Probability and Statistical Inference written by by Robert Hogg, Elliot Tanis and Dale Zimmerman. According to the explanation, the probability is 4/16 = 1/4. In my perspective, the answer should be the area of a disk divided by the area of a tile. The probabiity would be pi/16. Would you agree? Disagree? Thank you for your wisdom!
The problem is in the chapter 1, section 1.1 of the book. I am wondering if that is the reason why the authors put 1/4.
Here is the problem:


text:
Q: Extract integers from 2D Arraylist whose sum is between a range I'm writing code for a .NETMF application and need to create a function which accepts 2 params int min, int max and returns an array of integers returnedArr from a generated 2D Arraylist arr were the sum of integers inside returnedArr will be between min and max and also I will not know what the size or contents of arr will be prior to calling the method. Only 1 integer per Arraylist inside arr will be selected.
        public ArrayList GetNums(int min, int max)
        {
            //arr will be structured like this
            //var arr = new ArrayList
            //{
            //    new ArrayList {10, 34, 56, 60},
            //    new ArrayList {3, 23, 56, 78, 65, 42},
            //    new ArrayList {53, 56, 76}
            //};

            var returnedArr = new ArrayList();

            var arr = GenerateArraylistValues();

            //solution code here...

            return returnedArr;
        }

        var returnedArr = new ArrayList();

        var arr = GenerateArraylistValues();

        //solution code here...

        return returnedArr;
    }

A sample would be GetNums(130,140);
Return arraylist could be Arraylist{56,23,53}
Also bear in mind that I'm confined to using Arraylists so I can't use generic lists, I was thinking that some sort of foreach loop would do the job but can't get my head around how this would work since I no idea what the size of arr will be before hand
-----------SAMPLE 'arr' VALUES---------
var arr = new ArrayList
{
    new ArrayList { 21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,55,56,59,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,90,93,96,99,102},
    new ArrayList { 21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,55,56,59,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,90,93,96,99,102},
    new ArrayList { 39,40,41,42,43,44,45,46,47,48,49,53,54,55,59,60,61,77,78,79,80,81,82,83,84,85,86,87,88,89,91,92,94,95,97,98,100,101,115,117,118,119,120,121,122,123,124,125,126,127,129,132,135,138,141},
    new ArrayList { 60,100,140,180},
    new ArrayList { 41,43,45,55,81,83,85,95,121,123,125,135},
    new ArrayList { 39,40,41,42,43,44,45,46,47,48,49,53,54,55,59,60,61,77,78,79,80,81,82,83,84,85,86,87,88,89,91,92,94,95,97,98,100,101,115,117,118,119,120,121,122,123,124,125,126,127,129,132,135,138,141},
    new ArrayList { 3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43,45,47,49,51,57,63}
};

A: If the 'arr' is not huge, using recursion and brute force:
    public ArrayList GetNums(int min, int max, ArrayList arr)
    {
        var results = new ArrayList();

        //nothing in the arr?
        if (arr.Count == 0)
            return results;

        //arr has only one list inside
        if(arr.Count == 1)
        {
            foreach(int a in (ArrayList)arr[0])
            {
                if(a >= min && a <= max)
                {
                    var r = new ArrayList();
                    r.Add(a);
                    results.Add(r);
                }
            }
            return results;
        }

        //arr has two or more lists inside
        ArrayList firstList = (ArrayList)arr[0];
        ArrayList remainingArr = new ArrayList();
        for(int i = 1; i < arr.Count; i++)
        {
            remainingArr.Add(arr[i]);
        }

        foreach (int a in firstList)
        {
            var tempResults = GetNums(min - a, max - a, remainingArr);
            foreach(ArrayList result in tempResults)
            {
                var newResult = new ArrayList();
                newResult.Add(a);
                newResult.AddRange(result);
                results.Add(newResult);
            }
        }
        return results;
    }

The result is a list of solutions. First valid solution for your example arr is {10, 65, 56}

A: If it is acceptable to have the same result, of the minimum values, each and every time, then what you could do is to:

*

*start with the smallest value of each sub-array,

*sort the remaining values, tracking their source sub-array,

*and move up the sorted values until you've met or exceeded the specified min
An example of such functionality (using LINQ for brevity, and converting back to ArrayList) would be as such:
public static ArrayList GetNums(int min, int max)
{
    var arr = GenerateArraylistValues();

    // Initialize our results with the minimum values from each array.
    var results = arr.Cast<ArrayList>().Select(sub => sub.Cast<int>().Min()).ToList();
    var others = new List<UnionItem>();

    for (int i = 0; i < arr.Count; i++)
    {
        others = new List<UnionItem>(others
                    // Concatenate the arrays together.
                    .Union(((ArrayList)arr[i]).Cast<int>()
                    // Don't need the min value, which we will start at already. (Optional)
                    .Where(val => val != results[i])
                    // Create the UnionItem, to hold the value and the original array source.
                    .Select(val => new UnionItem(val, i))));
    }

    // Order our combined values.
    others = new List<UnionItem>(others.OrderBy(val => val.Value));
    using (var next = others.GetEnumerator())
    {
        // Progress through the combined values until we (a) meet or exceed min, or (b) run out of values.
        while ((results.Sum() < min) && (next.MoveNext()))
        {
            // Update the list of result values according to the UnionItem source.
            results[next.Current.Source] = next.Current.Value;
        }
    }

    // Once through our calculation, check now if we've successfully met the conditions.
    int sum = results.Sum();
    if (sum >= min && sum <= max)
    {
        return new ArrayList(results);
    }
    else
    {
        // Whatever happens if no valid match.
        return new ArrayList();
    }
}

private class UnionItem
{
    public readonly int Value;   // Holds the value from the array.
    public readonly int Source;  // Holds the index of the source array.
    public UnionItem(int value, int source)
    {
        Value = value;
        Source = source;
    }
}

I've created the UnionItem class, simply so we can do the tracking of the source array for each value, to substitute back correctly our results.


text:
Q: email validation jquery
Possible Duplicate:
JQuery validate e-mail address regex

hi i have an input filed in a form referencing to an email input field , and when the user clicked the submit button i want to ensure that the email input field value has the formal like this
example@hotmail.com

or
example@gmail.com

or
example@yahoo.com

and the input field is this

            Email
            <input type="text" name="Email"/>

jquery code
$(document).ready(function(){
    $('#suform').on('submit', function(e){
        e.preventDefault();
        var errorCount = 0;
        $('span.errorMessage').text(''); // reset all error mesaage
        $('input').each(function(){
            var $this = $(this);
            if($this.val() === ''){
                var error = 'Please fill ' + $this.prev('label').text(); // take the input field from label
                $this.next('span').text(error);
                errorCount = errorCount + 1;
            }
        });
        if(errorCount === 0){
            var mobileNumber = $('input[name=MNumber]');
            var email = $('input[name=Email]');
            if(isNaN(parseFloat(mobileNumber )) && !isFinite(mobileNumber )) {
                var error = 'Mobile number incorect.';
                $('input[name=MNumber]').next('span').text(error);
                errorCount = errorCount + 1;
            }else{
                var password= $('input[name="Password"]').val();
                var repass= $('input[name="RePassword"]').val();
                if(password!=repass){ // ensrue the two passwords are the same
                    var error2 = 'Password not matching';
                    $('input[name="RePassword"]').next('span').text(error2)
                    errorCount = errorCount + 1;
                }else{
                    $(this)[0].submit(); // submit form if no error
                }
            }
        }
    });
});

my html , css and jquery code is here
code

A: Regular expression is one way to validate :
function validateEmail(email) {
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\
".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA
-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(email);
}

Pass a user entered email to this function it will check its formate and return true or false accordingly

A: If I understand you correctly, you want to validate the email address filled on the form:
ADD TO YOUR FUNCTION
// validate proper email address
var reg = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i;

if (reg.test(value) == false) {
  // email invalid, do stuff
} else {
  // email valid, do stuff
}

This Regular expression checks the email provided for many many many issues!
EDITED:
You're function had some typos, here it is fully functional: and a working Fiddle!
$(document).ready(function(){

    // form submit
    $('#suform').on('submit', function(e){

        // prevent default behavior
        e.preventDefault();

        // reset errors counter
        var errorCount = 0;

        // clear error message
        $('span.errorMessage').text('');

        // run by each input field to check if they are filled
        $('input').each(function(){

            var $this = $(this);

            if($this.val() === ''){
                // take the input field from label
                var error = 'Please fill ' + $this.prev('label').text();
                $this.next('span').text(error);
                errorCount = errorCount + 1;
            }
        });

        // no errors so far, let continue and validate the contents
        if(errorCount === 0){

            // get mobile number
            var mobileNumber = $('input[name=MNumber]').val();

            // get email address
            var email = $('input[name=Email]').val();

            // get password and password repeat
            var password= $('input[name="Password"]').val();
            var repass= $('input[name="RePassword"]').val();

            // regular expression to validate the email address
            var reg = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i;

            // try to validate the email
            if (reg.test(email) == false) {
              $('input[name=Email]').next('span').text('Email address is invalid!');
              errorCount = errorCount + 1;
            } else {

                if(isNaN(parseFloat(mobileNumber )) && !isFinite(mobileNumber )) {
                    var error = 'Mobile number incorect.';
                    $('input[name=MNumber]').next('span').text(error);
                    errorCount = errorCount + 1;
                } else {
                    // ensrue the two passwords are the same
                    if(password!=repass){
                        var error2 = 'Password not matching';
                        $('input[name="RePassword"]').next('span').text(error2);
                        errorCount = errorCount + 1;
                    }else{
                        $(this)[0].submit(); // submit form if no error
                    }
                }
            }
        }
    });
});

A: You can use this function:
function validateEmail(email) {
    var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
    if( !emailReg.test( email ) ) {
        return false;
    } else {
        return true;
    }
}


text:
Q: datepicker send data to database How i can get picked data in inline mode.
With popup its easy to do with input tag
<input type="hidden" id="defaultInlineDatepicker" size="60">. And when i can write data to database. But i need calendar on my page inline.

A: The datepicker is not an input tag, it is a UI enhancement plugin. SO you need to change the span to an input field.

     <input id="defaultInlineDatepicke" class="datepicker" type="text"/>

A: Here is working code for you:
Script::
$(function() {
 $('#datepicker').datepicker({
    altField: '#datepicker_pick',
    onSelect: function() {
         alert($("#datepicker_pick").val());
    }
 });
});

HTML:
Date:

<input type="hidden" id="datepicker_pick" name="datepicker_pick">


text:
Q: Redirect a Subdomain to a URL I would like to redirect a subdomain to another URL.
For example, a user visits https://fun.mydomain.com and I want to redirect them to https://google.com/fun. What's the best way to make this?
I'm a complete beginner at domains and cloud hosting.
Many thanks.


text:
Q: How to set root password? I followed installation instruction in Linux container homepage.
After lxc-create command, I selected Ubuntu, Trusty, i386 and then a message was shown:

Use lxc-attach or chroot directly into the rootfs to set a root password
  or create user accounts.

So, I moved to ~/.local/share/lxc_03/rootfs and ran sudo chroot . Then I tried to change password but failed:
root@user_id:/# passwd
Enter new UNIX password:
Retype new UNIX password:
passwd: System error
passwd: password unchanged

What could be causing this?
My environment: Ubuntu 14.04 running on Parallels

A: Go up a level. Try 'chroot rootfs'
Then type 'passwd'
Regards, kevkiller


text:
Q: How would I go about uniquely identifying a computer in node.js? Simple question, I'm new to using node.js and was curious as to how I should uniquely identify a computer?

A: As with most operations you have no way to identify uniquely a computer. All data is sent stateless and wihout any information of the computer.
But you can change your (x)html application to store unique cookies so the client side part can authenticate to the server with the cookie, perfectly identifying two open tabs of one user.

A: If you're working with web sockets you can assign each client an id using a random uuid, here's one that'll work on both client and server:
http://www.broofa.com/Tools/Math.uuid.js
and speed benchmarks for each flavor:
http://jsperf.com/uuid-from-broofa-com


text:
Q: How to make a field editable while creating, but read only in existing objects? I've a django Model, and want to be able to set an id while creating. But once created, the id of existing object shouldn't be editable.
class Vehicle:
    id = models.UUIDField(primary_key=True, default=uuid.uuid4)

I see that I need to turn do "editable=True" (which is the default) on the id field, but this would allow editing the id field later on as well.


text:
Q: $stateProvider redirecting to param based url instead of provided url in angularJs routing I am trying to create routes in my angular app like:

*

*baseURL/123 (123 will be resolved using /:opportunityId param)

*baseURL/analysis (analysis is provided in the state URL)

I have tried with the code below to create it:
$stateProvider
        .state('analysis', {
            url: '/analysis',
            controller: 'FileAnalysisController',
            template: fileAnalysisTemplate,
            params: {
                data: "null"
            }
        })
        .state('dashboard', {
            url: "/:opportunityId",
            controller: 'DashboardController',
            template: dashboardTemplate
        })

But, when I am hitting the url like: 'baseURL/analysis', it is calling dashboard state. I don't know what exactly I am doing wrong.

A: This happens because in route baseURL/123 123 can be anything, it can be number, text even object. So in your case when you are calling baseURL/analysis analysis is consider in baseURL/:opportunityId param and angular routes you to this route instead of what you have define.
To solve this solution us one more base path in  you route where you want to accept using URL param like:
Instead of baseURL/123 use baseURL/xyz/123 so that anything after baseURL/ will be resolved as per route define.


text:
Q: text property of ui:inputSelectOption with aura:iteration not working correctly My understanding of the text-property from the ui:inputSelectOption is that I can add underlaying data (in difference to the label-property which displays the data on the GUI-Interface).
In my opinion this example should work without any issues:
<aura:component>

<aura:attribute name="dataProvider" type="Object[]" access="global"
    default="[{name: 'Tom'}, {name: 'Bob'}, {name: 'Tim'}]" />

<ui:inputSelect>
    <aura:iteration items="{!v.dataProvider}" var="dataItem" indexVar="dataIndex">
            <ui:inputSelectOption label="{!dataItem.name}" text="{!dataIndex}" />
    </aura:iteration>
</ui:inputSelect>

But I cannot change the selection of the input select - it always jumps back to the first entry (Mac OS X, Chrome, Lightning Experience):

Is this a bug? When I hardcode the inputSelectOptions by not using aura:iteration everything works fine. Same when I do not assign the text-property.

A: Trying it on my end... something funky definitely happening there, having to do with binding a numeric value to that text field. Here is my stupid hack of a fix:
<aura:attribute name="dataProvider" type="Map[]" access="global"
                default="[{name: 'Tom'}, {name: 'Bob'}, {name: 'Tim'}]" />

<ui:inputSelect>
    <aura:iteration items="{!v.dataProvider}" var="dataItem" indexVar="dataIndex">
        <ui:inputSelectOption label="{!dataItem.name}" text="{!''+dataIndex}" />
    </aura:iteration>
</ui:inputSelect>

Adding '' + the index ensures it treats it as a string and that seems to unbreak the select list.
Note also that you can bind a Map[] directly to the items property of ui:inputSelect. For example:
<aura:attribute name="items" type="Map[]" access="global"
                default="[{label: 'Tom', value:0}, {label: 'Bob', value:1}, {label: 'Tim', value:2}]" />

<ui:inputSelect options="{!v.items}" />

A: I would use the same value for the label and the text attributes:
<aura:attribute name="dataProvider" type="Map[]" access="global"
            default="[{name: 'Tom'}, {name: 'Bob'}, {name: 'Tim'}]" />

<ui:inputSelect>
    <aura:iteration items="{!v.dataProvider}" var="dataItem" indexVar="dataIndex">
        <ui:inputSelectOption label="{!dataItem.name}" text="{!dataItem.Name}" />
    </aura:iteration>
</ui:inputSelect>


text:
Q: AEM: links transform/rewrite in a page In my current project the dam assets are being moved to CDN server and my current src attributes in img elements should refer the corresponding cdn server image and not the one in the dam.
eg: my current img element looks like this:
< img src="/content/dam/myproject/123.jpg">
I have a corresponding 123.jpg image in CDN server. NOW, the src should be changed to refer the CDN server image.
< img src="https://cdn-aem.com/content/dam/myproject/123.jpg ">
I can change this at the component level But I'm looking to change this at a more global level using OSGi service or something!
Any inputs ?

A: You can use a Sling Rewriter. The documents are available on the Apache Sling website. I'm including a sample Sling Transformer below. You also need to add a configuration node. You can find an additional example in the ACS Commons Versioned Clientlibs feature.
Add this Transformer and update the StartElement method to handle your path updates:
import java.io.IOException;
import java.util.Map;

import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.rewriter.ProcessingComponentConfiguration;
import org.apache.sling.rewriter.ProcessingContext;
import org.apache.sling.rewriter.Transformer;
import org.apache.sling.rewriter.TransformerFactory;
import org.osgi.service.component.ComponentContext;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;

@Component
@Service
@Property(name="pipeline.type", value="linkrewriter", propertyPrivate=true)
public class LinkRewriterTransformerFactory implements TransformerFactory {

    public Transformer createTransformer() {
        return new LinkRewriterTransformer();
    }

    @Activate
    protected void activate(Map<String, Object> properties) {
    }

    @Deactivate
    protected void deactivate(ComponentContext ctx) {
    }

    private class LinkRewriterTransformer implements Transformer {
        private ContentHandler contentHandler;
        private SlingHttpServletRequest request;

        public void characters(char[] ch, int start, int length) throws SAXException {
            contentHandler.characters(ch, start, length);
        }

        public void dispose() {
        }

        public void endDocument() throws SAXException {
            contentHandler.endDocument();
        }

        public void endElement(String uri, String localName, String qName) throws SAXException {
            contentHandler.endElement(uri, localName, qName);
        }

        public void endPrefixMapping(String prefix) throws SAXException {
            contentHandler.endPrefixMapping(prefix);
        }

        public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {
            contentHandler.ignorableWhitespace(ch, start, length);
        }

        public void init(ProcessingContext context, ProcessingComponentConfiguration config) throws IOException {
            request = context.getRequest();
        }

        public void processingInstruction(String target, String data) throws SAXException {
            contentHandler.processingInstruction(target, data);
        }

        public void setContentHandler(ContentHandler handler) {
            this.contentHandler = handler;
        }

        public void setDocumentLocator(Locator locator) {
            contentHandler.setDocumentLocator(locator);
        }

        public void skippedEntity(String name) throws SAXException {
            contentHandler.skippedEntity(name);
        }

        public void startDocument() throws SAXException {
            contentHandler.startDocument();
        }

        public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
            final AttributesImpl attributes = new AttributesImpl(atts);

            final String href = attributes.getValue("href");

            if (href != null) {
                for (int i = 0; i < attributes.getLength(); i++) {
                    if ("href".equalsIgnoreCase(attributes.getQName(i))) {
                        String cdnPath = /* process your path here */;
                        attributes.setValue(i, cdnPath);
                        break;
                    }
                }
            }

            contentHandler.startElement(uri, localName, qName, attributes);
        }

        public void startPrefixMapping(String prefix, String uri) throws SAXException {
            contentHandler.startPrefixMapping(prefix, uri);
        }
    }
}

Add this configuration node to /apps/myapp/config/rewriter/myapp.xml:
<?xml version="1.0" encoding="UTF-8"?>
<jcr:root xmlns:jcr="http://www.jcp.org/jcr/1.0" xmlns:nt="http://www.jcp.org/jcr/nt/1.0"
    jcr:primaryType="nt:unstructured"
    contentTypes="[text/html]"
    enabled="{Boolean}true"
    generatorType="htmlparser"
    order="1"
    paths="[/content/myapp]"
    serializerType="htmlwriter"
    transformerTypes="[linkchecker,linkrewriter]">
    <generator-htmlparser
        jcr:primaryType="nt:unstructured"
        includeTags="[META,/META,A,/A,IMG,AREA,FORM,BASE,LINK,SCRIPT,BODY,/BODY,VIDEO,/VIDEO,ASIDE,/ASIDE,SECTION,/SECTION]"/>
</jcr:root>

A: I wanted to achieve the same as you described.
You may want to have a look here: https://adobe-consulting-services.github.io/acs-aem-commons/features/utils-and-apis/static-reference-rewriter/index.html
Steps:
A. Download and install AEM ACS Commons package on your instance (get zip package from the above website, install in package manager)
B. Go to apps/<yourapp>/config and create a file named com.adobe.acs.commons.rewriter.impl.StaticReferenceRewriteTransformerFactory-<your-custom-name>.xml with contents similar to these:
<?xml version="1.0" encoding="UTF-8"?>
<jcr:root xmlns:sling="http://sling.apache.org/jcr/sling/1.0"     xmlns:cq="http://www.day.com/jcr/cq/1.0"
xmlns:jcr="http://www.jcp.org/jcr/1.0" xmlns:nt="http://www.jcp.org/jcr/nt/1.0"
    jcr:primaryType="sling:OsgiConfig"
    pipeline.type="your-custom-pipeline-name"
    attributes="[img:src\,srcset,link:href,script:src]"
    matchingPatterns="[img:srcset;(\/content\/dam\/.+?[jpg|png]) .+?w]"
    host.pattern="your.domain.com"
    prefixes="[/etc/designs,/content/dam]"
/>

C.Under apps/<yourapp>/config/rewriter create a file <another-custom-name>.xml containing this:
<?xml version="1.0" encoding="UTF-8"?>
<jcr:root xmlns:sling="http://sling.apache.org/jcr/sling/1.0" xmlns:jcr="http://www.jcp.org/jcr/1.0"
    jcr:primaryType="sling:Folder"
    contentTypes="[text/html]"
    enabled="{Boolean}true"
    generatorType="htmlparser"
    order="{Long}1"
    serializerType="htmlwriter"
    transformerTypes="[linkchecker,your-custom-pipeline-name]"
/>

Reinstall the bundle on your instance and test. Good luck!


text:
Q: Заданное приведение является недопустимым, задание значения двухмерному массиву Я пытаюсь скопировать значения таблицы в двухмерный массив:
int[,] arr = new int[,] { { }, { } };
for (int i = 0; i < numericUpDown1.Value; i++)
{
    for(int j = 0; j < numericUpDown2.Value; j++)
    {
        Console.WriteLine(i + " " + j);
        arr[i, j] = (int)dataGridView1.Rows[i].Cells[j].Value;
    }
}

Вот как выглядит интерфейс:

Но показывает ошибку Заданное приведение является недопустимым.

Что делать?

A: В ячейке в данном конкретном случае string, а не int.
int rows = dataGridView1.RowCount;
int cols = dataGridView1.ColumnCount;
int[,] arr = new int[rows, cols];
for (int i = 0; i < rows; i++)
{
    for (int j = 0; j < cols; j++)
    {
        Debug.WriteLine(i + " " + j);
        if (int.TryParse(dataGridView1.Rows[i].Cells[j].Value.ToString(), out int value)
        {
            arr[i, j] = value;
        }
    }
}


text:
Q: To create numericinput for all columns in a data set using renderui I am trying to create numeric boxes for all column names in a data set. I have written below code but this displays a blank page. Not sure what the error is. Any suggestions?
library(shiny)
library(readr)

shinyApp(
  ui <- fluidPage(
    uiOutput("TestColumns")
  ),
  server <- function(input, output) {
    data_set <- read.csv("Data/170210_Flat_File.csv")
    output$TestColumns <- renderUI({

      for(i in names(data_set)){
        numericInput(i, i,30)
      }}
      )})

A: First off, when you ask questions you should ALWAYS post a minimal reproducible example. That is basically something that we can run to replicate the issue you are having so that it is much easier for us to help you. This way we don't have to go about using different data, trying to figure out exactly what your error is. See this link for a good intro: How to make a great R reproducible example?
Next to your question - since you didn't explicitly post an error you were seeing or explicitly state what your issue was I'm going to go ahead and assume that your issue is that you don't see any UI's popping up when you run your Shiny App (this is what I got when I tried running your code with different sample data).
The reason you aren't seeing anything is because you aren't returning any objects from your for loop. If you really wanted to do a for loop you would have to loop through, store everything in a list, then return that list. Note that I had to use R's built in data because you didn't provide any. Something like this would work:
shinyApp(
  ui <- fluidPage(
    #numericInput("test","test",30),
    uiOutput("TestColumns")
  ),
  server <- function(input, output) {
    data_set <- mtcars

    output$TestColumns <- renderUI({
      L<-vector("list",length(names(data_set)))
      for(i in names(data_set)){
        L[[i]]<-numericInput(i, i,30)
      }
      return(L)
    })})

This should give you your desired result. However, the above is unnecessarily complicated. I suggest you use an lapply instead. Something like this is much better in my opinion:
shinyApp(
  ui <- fluidPage(
    #numericInput("test","test",30),
    uiOutput("TestColumns")
  ),
  server <- function(input, output) {
    data_set <- mtcars

    output$TestColumns <- renderUI({
      lapply(names(data_set),function(x){numericInput(x,x,30)})
    })})

A: ui <- bootstrapPage(
  fluidRow(
    column(4,offset = 2,
           tags$h4("numeric inputs"),
           uiOutput('mtcars_numerics') # These will be all the numeric inputs for mtcars
    ),
    column(6,
           tags$h4("current input values"),
           verbatimTextOutput('show_vals') # This will show the current value and id of the inputs
    )
  )
)

server <- function(input, output, session){

  # creates the output UI elements in the loop
  output$mtcars_numerics <- renderUI({
    tagList(lapply(colnames(mtcars), function(i){ # must use `tagList` `
      column(3,
             numericInput(
               inputId = sprintf("mt_col_%s",i), # Set the id to the column name
               label = toupper(i), # Label is upper case of the col name
               min = min(mtcars[[i]]), # min value is the minimum of the column
               max = max(mtcars[[i]]), # max is the max of the column
               value = mtcars[[i]][[1]] # first value set to the first row of the column
             ))
      })
    )
  })

  # So we can see the values and ids in the ui for testing
  output$show_vals <- renderPrint({
    all_inputs <- names(session$input)
    input_vals <- plyr::ldply(all_inputs, function(i){
      data.frame(input_name = i, input_value = input[[i]],stringsAsFactors = FALSE)
    })

    input_vals
  })
}

shinyApp(ui, server)

Results in:


text:
Q: How to compare two oracle sql object type with common base super class Example:

*

*Figure_t base class (super class)

*sphere_t under figure_t

*pyramid_t under figure_t

*both has volume.

*How to do objects comparison using map or order function?

What I am doing is using the map member function in the super class for comparing using the volume. I have tried with/without override of the map function in the subclass but still no luck. I can compare if I create the same object twice but not if I create different ones.
In example below I paste just the sphere since it is almost the same for both sphere and pyramid.
This is my super class:
CREATE OR REPLACE TYPE figure_t AS OBJECT (
    v_volume   NUMBER,
    v_area      NUMBER,
    MAP MEMBER FUNCTION compare RETURN NUMBER, PRAGMA restrict_references ( compare, wnds, trust )
);
/

CREATE OR REPLACE TYPE BODY figure_t AS
    MAP MEMBER FUNCTION compare RETURN NUMBER IS
    BEGIN
        RETURN v_volume;
    END;

END;
/

ALTER TYPE figure_t NOT FINAL
    CASCADE;
/

Then, this is my subtype:
CREATE OR REPLACE TYPE sphere_t UNDER figure_t (
    v_radio NUMBER,
    CONSTRUCTOR FUNCTION sphere_t (
           radio NUMBER
       ) RETURN SELF AS RESULT,
    MEMBER FUNCTION get_volume RETURN NUMBER,
    MEMBER FUNCTION get_area RETURN NUMBER,
    OVERRIDING MAP MEMBER FUNCTION compare RETURN NUMBER
);
/

CREATE OR REPLACE TYPE BODY sphere_t AS
    CONSTRUCTOR FUNCTION sphere_t (
        radio NUMBER
    ) RETURN SELF AS RESULT IS
    BEGIN
        self.v_radio := radio;
        self.v_volume := ( 4 / 3 ) * 3.141592654 * power(radio, 3);

        self.v_area := 4 * 3.141592654 * power(radio, 2);
        return;
    END;

    MEMBER FUNCTION get_volume RETURN NUMBER IS
    BEGIN
        RETURN v_volume;
    END;

    MEMBER FUNCTION get_area RETURN NUMBER IS
    BEGIN
        RETURN v_area;
    END;

OVERRIDING
    MAP MEMBER FUNCTION compare RETURN NUMBER IS
    BEGIN
        RETURN self.v_volume;
    END;

END;
/

For doing the comparison it looks like:
DECLARE
    sphere_v   sphere_t;
    pyramid_v   pyramid_t;
BEGIN
    pyramid_v := pyramid_t(120, 90, 30);
    sphere_v := sphere_t(10);
    IF ( sphere_v != pyramid_v ) THEN
        dbms_output.put_line('NOT EQUAL');
    END IF;
END;

There should be a way for this comparison since figures have a super class in common.

A:
There should be a way for this comparison since figures have a super
  class in common

Am not very sure as what you wanted to achieve here. Also what is definition of pyramid_t which you are using in your comparison.

IF ( sphere_v != pyramid_v ) THEN

The above condition looks dicey to me as this will always be the case.
When you do sphere_v := sphere_t(10); means you try to get all the return of the sphere_t to sphere_v.
So it would be good if you could compare the volume and area of the Sphere and pyramid separately. See below demo how you could take these value:
DECLARE
    sphere_v   sphere_t;
   -- pyramid_v   pyramid_t;

BEGIN
    sphere_v := sphere_t(10);

    dbms_output.put_line('Input Radio     -->'||sphere_v.v_radio);
    dbms_output.put_line('Volume of Sphere-->'||sphere_v.v_volume);
    dbms_output.put_line('Area Of Sphere  -->'||sphere_v.v_area);

  --Similarly you can take the values of `volume` and `area`
  --of pyramid and get it compared with that of Sphere.

  -- pyramid_v := pyramid_t(120, 90, 30);
  --  dbms_output.put_line('Input Radio Pyramid -->'||pyramid_v.v_radio);
  --  dbms_output.put_line('Volume of Pyramid    -->'||pyramid_v.v_volume);
  --  dbms_output.put_line('Area Of Pyramid      -->'||pyramid_v.v_area);

  -- If sphere_v.v_volume = pyramid_v.v_volume then
  --   dbms_output.put_line('Equal');
  -- Else
  --   dbms_output.put_line('Not Equal');

END;

Assumption: pyramid_t also have the same Object Body definition having volume and area calculation.

A:
There should be a way for this comparison since figures have a super class in common.

There is a way, it's just not obvious.
When the types are exactly the same e.g. two instances of the same subtype we can invoke the map function implicitly. So we can compare two spheres like this:
 IF ( sphere_1 != sphere_2 ) THEN ...

However, to compare two different subtypes we need to invoke the parent map function, and to make this happen we must reference it explicitly:
 IF ( sphere_v.compare() != pyramid_v.compare() ) THEN ...

Yes, this is clunky. But Oracle is an RDBMS not an ORDBMS (whatever they claimed back in the version 8.0 days).


text:
Q: Uncaught Error: Call to a member function getSomething() on null in phtml ViewModel magento2 I have created a ViewModel, when I am calling it in the phtml it giving me the below error
Fatal error: Uncaught Error: Call to a member function getSomething() on null in Magento_Catalog/templates/product/list/items.phtml:16 Stack trace: #0
here is my catalog_product_view.xml
<block name="product.info.upsell.customviewmodel"
                   class="Magento\Framework\View\Element\Template"
                   template="Magento_Catalog::product/list/items.phtml">
                <arguments>
                        <argument name="view_model" xsi:type="object">Noshad\VMpractice\ViewModel\PreparePostData</argument>
                    </arguments>
            </block>

here is my ViewModel class
<?php

namespace Noshad\VMpractice\ViewModel;

use Magento\Framework\View\Element\Block\ArgumentInterface;

class PreparePostData implements ArgumentInterface
{

    public function getSomething()
    {
        echo 'find me';
    }

}

here are my items.phtml code
/* @var Noshad\VMpractice\ViewModel\PreparePostData $viewModel */

$viewModel =  $block->getData('view_model');

echo $viewModel->getSomething();

whenever I load the product detail page I gets the below error:
Fatal error: Uncaught Error: Call to a member function getSomething() on null in /var/www/html/practice234/app/design/frontend/Smartwave/porto_child/Magento_Catalog/templates/product/list/items.phtml:16 Stack trace: #0

A: Try this below code :-
ViewModel/Custom.php
<?php

namespace Mage\Mohit\ViewModel;

class Custom implements \Magento\Framework\View\Element\Block\ArgumentInterface
{

    public function __construct(

    ) {
    }

    public function getSomething() {
        return "Hello Magento Stackexchange";
    }
}

items.phtml
<?php

$viewModel = $block->getData('view_model');
echo $viewModel->getSomething();

catalog_product_view.xml
<block name="product.info.upsell.customviewmodel"
                   class="Magento\Framework\View\Element\Template"
                   template="Mag_Mohit::items.phtml">
                <arguments>
                        <argument name="view_model" xsi:type="object">Mage\Mohit\ViewModel\Custom</argument>
                    </arguments>
            </block>

After below commmands run :-
php bin/magento s:up
php bin/magento s:s:d -f
php bin/magento c:c
php bin/magento c:f

THANKS.

A: You need to add the \ in your xml before your class


text:
Q: Static labels on graph within a ScrollPane JavaFX I'm trying to draw multiple graphs next to each other where the the axis of the graphs can be outside the viewport. I draw each graph within a HBox which is nested within a ScrollPane. This is fine for just drawing the Y axis of the graphs, however I want to keep the labels of the X axis fixed on the screen so when some scrolls vertically the labels will always be visible.
I've tried creating a StackPane where I nested the ScrollPane and HBox mentioned above and a second HBox to create a sort of static layer. This unfortunately broke the scrolling capability of the ScrollPane.
Is there a way to keep the labels fixed on the Y axis while still being scrollable in the X direction?
The FXML currently:
<VBox>
    <ScrollPane>
        <HBox>

        </HBox>
    </ScrollPane>
</VBox>

What I tried:
<VBox>
    <StackPane>
        <ScrollPane>
            <HBox>

            </HBox>
        </ScrollPane>
        <HBox>

        </HBox>
    <StackPane>
</VBox>

A: One way I can think of is to deal with ScrollBar(s) instead of ScrollPane. You can set the scrollBar min/max value with axis lower/upper bounds. And on change in scroll value update the axis bounds accordingly. Something like..
final AreaChart chart = new AreaChart(xAxis, yAxis);
        ScrollBar scroll = new ScrollBar();
        scroll.setMin(chartLowerBound);
        scroll.setMax(chartUpperBound);
        scroll.setVisibleAmount(10 * tickUnit);
        scroll.valueProperty().addListener((obs, old, nxtLb) -> {
            double nxtUb = nxtLb.doubleValue() + (10 * tickUnit);
            xAxis.setUpperBound(nxtUb);
            xAxis.setLowerBound(nxtLb.doubleValue());
        });

A quick working example is below. Try to understand the base logic and implement as per your needs.
import java.util.Random;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.chart.AreaChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart.Data;
import javafx.scene.chart.XYChart.Series;
import javafx.scene.control.ScrollBar;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class ScrollableChartDemo extends Application {

    public static void main(String... args) {
        launch(args);
    }

    @Override
    public void start(Stage stage) throws Exception {
        stage.setTitle("Scrollable Chart");
        Random random = new Random(12);

        double tickUnit = .04;
        double chartLowerBound = 0;
        double chartUpperBound = 4;

        final ObservableList<Data> seriesData = FXCollections.observableArrayList();
        Series series = new Series("Series 1", seriesData);

        final ObservableList<Data> series2Data = FXCollections.observableArrayList();
        Series series2 = new Series("Series 2", series2Data);

        double tempoXAxis = 0.0;
        for (int i = 0; i < 100; i++) {
            seriesData.add(new Data(tempoXAxis, random.nextInt(12)));
            series2Data.add(new Data(tempoXAxis, random.nextInt(12)));
            tempoXAxis += tickUnit;
        }

        final ObservableList<Series> allSeriesData = FXCollections.observableArrayList(series, series2);

        NumberAxis xAxis = new NumberAxis("Time", 0, (10 * tickUnit), tickUnit);
        NumberAxis yAxis = new NumberAxis();

        final AreaChart chart = new AreaChart(xAxis, yAxis);
        chart.getData().addAll(allSeriesData);
        VBox.setVgrow(chart, Priority.ALWAYS);
        ScrollBar scroll = new ScrollBar();
        scroll.setMin(chartLowerBound);
        scroll.setMax(chartUpperBound - (10 * tickUnit));
        scroll.setVisibleAmount(10 * tickUnit);
        scroll.valueProperty().addListener((obs, old, nxtLb) -> {
            double nxtUb = nxtLb.doubleValue() + (10 * tickUnit);
            xAxis.setUpperBound(nxtUb);
            xAxis.setLowerBound(nxtLb.doubleValue());
        });

        chart.setOnScroll((ev) -> {
            double nxtUb;
            double nxtLb;
            if (ev.getDeltaY() > 0) {
                nxtUb = xAxis.getUpperBound() + tickUnit;
                if (nxtUb > chartUpperBound) {
                    nxtUb = chartUpperBound;
                }
                nxtLb = nxtUb - (10 * tickUnit);
            } else {
                nxtLb = xAxis.getLowerBound() - tickUnit;
                if (nxtLb < chartLowerBound) {
                    nxtLb = chartLowerBound;
                }
                nxtUb = nxtLb + (10 * tickUnit);
            }
            xAxis.setUpperBound(nxtUb);
            xAxis.setLowerBound(nxtLb);
            scroll.setValue(nxtLb);
            ev.consume();
        });

        VBox vb = new VBox();
        vb.setSpacing(5);
        vb.getChildren().addAll(chart, scroll);
        Scene scene = new Scene(vb);
        stage.setScene(scene);
        stage.setWidth(1000);
        stage.setHeight(700);
        stage.show();
    }
}


text:
Q: Application is extracting itself every time when runs I have created an application with WPF and code is used C# but it gives a problem that whenever setup is silently installed with cmd command e.g.
setup.exe /s /v/qn

it works perfectly to extract all the items containing in it after above given lines. But once setup is completed we try to run this application, it executes but shows below given image

Setup is created in installshield and it has the option not extract msi cache in local computer. Please help me to find why this problem is occuring.

A: That has to do with the auto-repair features of Windows Installer.
I guess you are using advertised shortcuts. Every time a user uses this special kind of shortcut to run a application, the Windows Installer performs an integrity check of it. If there are any detected problems, the installer performs an "Repair" before the launch of your application. This seems to be the case.
You can detect advertised shortcuts in the property-dialog of the start-menu. The target-field will be disabled and does not contain a path to a executable.
A possible workaround is to use regular shortcuts but this will not solve the real problem which causes the dialog to appear.
You could try to investigate further with ProcMon (https://technet.microsoft.com/en-us/library/bb896645.aspx) and see if there are any problems during the startup. Another option you have is to force logging (https://support.microsoft.com/en-us/kb/2545723) and see if there are any information that will help you finding the cause of this error.
Another entry-point for the self-repair is the creation of COM-objects which come with your installer-package.


text:
Q: Clarification on pointer to non-static class member When I need a pointer to member of class, I do as following
struct MyStruct
{
    int foo();
};

int (MyStruct::*p)() = &MyStruct::foo;

My question is why do I need to use & operator to take the address which may be ignored if it were a static function. Also, I've heard pointer to members aren't really a pointer, Can someone clarify that?

A: If it's a static function, it works just as a regular non-member function pointer: the function name itself can be implicitly converted to a function pointer.
If it's a non-static member function, it's no longer the same thing as a non-member function:

*

*It has a hidden this parameter;

*In a multiple inheritance scenario, converting a pointer to one of the base classes may produce a pointer to a different address. This means that if the member function is inherited, the this pointer may need to be adjusted before the call. This already makes it impossible to use a pointer to store a pointer-to-member-function.

Raymond Chen wrote an interesting article about this with more details and examples.

A:
why do I need to use & operator to take the address which may be
  ignored if it were a static function

You are right, in the case of pointer to member function syntax ideally & can be omitted. I think, & syntax is there may be due to historical convention.

I've heard pointer to members aren't really a pointer, Can someone
  clarify that?

That's not correct. The only difference is that they are pointer to member function. Since, class non-static member contain an implicit this pointer as their argument, they have a special signature. Also, they are not inter-convertible with normal function pointer with same signature.
In your code example, theoritically p is pointing to:
int MyStruct::foo (MyStruct* const);


text:
Q: Control Custom Post Type template from a plugin I can control the custom template to be used on custom post type pages but the template file would still need to have the markup of the theme. I was wondering if I could make it theme independent?
Example: I have a plugin that registers my custom post type. I have the post meta info that I want to show in a custom template. I have that template working on my custom post type pages but the max I could do is to use get_header() & get_footer() calls but I can't deal out the need of having the theme markup between header & footer.
Did that make any sense? Any ideas?

A: I have got it working by the following code:
add_action( 'template_redirect', 'ft_job_cpt_template' );

function ft_job_cpt_template() {
    global $wp, $wp_query;

    if ( isset( $wp->query_vars['post_type'] ) && $wp->query_vars['post_type'] == 'job' ) {
        if ( have_posts() ) {
            add_filter( 'the_content', 'ft_job_cpt_template_filter' );
        }
        else {
            $wp_query->is_404 = true;
        }
    }
}

function ft_job_cpt_template_filter( $content ) {

    global $wp_query;
    $jobID = $wp_query->post->ID;

    $output = ''; // Build markup fetching info from postmeta

    return $output;
}

Feel free to comment on any suggestions.


text:
Q: how to display variable on smarty tpl this is my tpl code
the {$video_link} when i use it with other (meta or FB: like etc) it work normal
inf fact in html code source page they display the coorect url ( seo)
but this scirpt don't
    {literal}<script>
  function postlike()
  {
     FB.api(
  'me/video.watches',
  'post',
  {
    video : "{$video_link}"
  },
        function(response) {
           if (!response || response.error) {
              alert('Post was not published.');
           } else {
              alert('Post was published. Action ID: ' + response.id);
           }
        });
  }
  </script>{/literal}

normally they must be
  'post',
  {
    video: "http://zdig1.biz/video/one-piece/611-video_942e07e26.html"
  },

but on page still appear
video : "{$video_link}"

so i thinked that my be there is a proble on the { before the $ !!!

A: If you're using smarty 3, just remove the {literal} tag and it should work fine. If not, and you don't want to be opening and closing literal tags, declare all the variables you need outside the literal section ie:
<script>
var video_link = "{$video_link}";

{literal}

function postlike()
  {...

    video : video_link

A: solution
{ video : "{/literal}{$video_link}{literal}" },`


text:
Q: Can we use JDBC connector to get data in Power BI Usually we can get data using ODBC connector in Power BI. Is there any way to get the data using the JDBC connector?

A: Unfortunately there is no native support for JDBC.
You can upvote the feature request for JDBC at this link
There are options that convert your JDBC connection in to an ODBC one, known as JDBC to ODBC bridges. Oracle has one and here is a Progress option. Once configured you can then use the PowerBI ODBC connector.

A: Since Power BI is not coded in java its not easy to support JDBC (you will see only ODBC or .net based connectors in PBI). If Microsoft ever wants to add support for JAVA in Power BI then they might have to do via some sort of bridge.
If you are open for 3rd party solution then here is one option by ZappySys
This same problem happens in many non java apps like Excel, MS Access, Informatica PowerCenter they all are not coded in JAVA so cant support loading java libs / runtime.


text:
Q: Output 2d Array in Java I have a piece of Java code that I want to output in appropriate rows and columns. How to do it?
public static void main(String[] args) {
        String[][] txt = {{"test","test2"},
                          {"test3","test4"}};

I want it to display like this:
test test2
test3 test4
(Really appreciate any help...)

A: You can use this logic:
public static void main(String[] args) {
        String[][] txt = {{"test","test2"},
                          {"test3","test4"}};

        for (int i = 0; i < txt.length; i++) {
            for (int j = 0; j < txt[i].length; j++) {
                System.out.print(txt[i][j]);
                System.out.print("\t");
            }
            System.out.println();
        }
    }

A: If you're using Java 8, you can make use of Lambdas and Streams to get the desired output.
Code:
Arrays.stream(txt).forEach(row -> {
    Arrays.stream(row).forEach(element -> {
        System.out.print(element);
        System.out.print("\t");
    });
    System.out.println();
});


text:
Q: what does $X_{s-}$ mean in the integration by parts formula for the Ito integral? The integration by parts formula for the Itō integral is

If $X$ and $Y$ are semimartingales then
  $$
    X_tY_t = X_0Y_0+\int_0^t X_{s-}\,dY_s + \int_0^t Y_{s-}\,dX_s + [X,Y]_t
$$
  where $[X, Y]$ is the quadratic covariation process.

I was wondering what $X_{s-}$ means? Thanks and regards!

A: It's defined pointwise by
$$
X_{s-}=\lim_{t\to s,t<s} X_t
$$


text:
Q: google tv emulator zip code field disabled I'm trying to run the ChannelChanging example on the googletv dev site and it's returning and empty channel list.   I went ahead and tried to configure the emulator video source in the emulator's video input settings but its now allowing me to type in a zip code.  The field appears to be disabled.  Has anyone experienced this problem? I'm running an x86 emulator on a ubuntu 64 bit installation configured with kvm.
Thanks

A: The current release of emulator does have some bugs but they are fixed in the upcoming release. There will be a new emulator release soon which will fix this and other issues.


text:
Q: Addin custom menu in Microsoft Office I want to add a custom menu (addin) inside FileMenu after "New" menu in office 2010.
Previously i have the similar add-in for Office 2007 but custumUI.xml has changed for office 2010 and 2013.
I tried required changes but couldn't get the Menu in Office 2010 and 2013.
Office 2007 :
<customUI xmlns="http://schemas.microsoft.com/office/2006/01/customui" onLoad="OnRibbonLoaded" loadImage="GetImage"><ribbon><OfficeMenu><menu id="MenuName" label="&MenuName" insertAfterMso="FileSaveAsMenu" image="menu.png" itemSize="large"
Office 2010: :
<customUI xmlns="http://schemas.microsoft.com/office/2009/07/customui" onLoad="OnRibbonLoaded" loadImage="GetImage"><ribbon><FileMenu><menu id="MenuName" label="&Menuname" insertAfterMso="FileSaveAsMenu" image="menu.png" itemSize="large">

A: You need to use the backstage element instead of the ribbon one. For example:
<customUI xmlns="http://schemas.microsoft.com/office/2009/07/customui" onLoad="OnLoad">
  <backstage>
    <tab id="testArea">

You can read more about the Backstage UI in the following articles in MSDN:

*

*Introduction to the Office 2010 Backstage View for Developers

*Customizing the Office 2010 Backstage View for Developers


text:
Q: data.table: cumulative values by grouping variable I have data
set.seed(42)
dat <- data.table(id=1:8, group=c(1,1,2,2,2,3,3,3), val=rnorm(8))

> dat
   id group         val
1:  1     1  1.37095845
2:  2     1 -0.56469817
3:  3     2  0.36312841
4:  4     2  0.63286260
5:  5     2  0.40426832
6:  6     3 -0.10612452
7:  7     3  1.51152200
8:  8     3 -0.09465904

and I would like to obtain the cumulative values of val within each level of group.
> res
   id group         cum
1:  1     1  1.37095845
2:  2     1  0.80626037
3:  3     2  0.36312841
4:  4     2  0.995991
5:  5     2  1.400259
6:  6     3 -0.10612452
7:  7     3  1.405397
8:  8     3  1.310738

I am always astonished by the efficiency of data.table, so I 'm wondering about a way to get this done in data.table but of course any other efficient solution is just as welcome.

A: You can do it using cumsum:
dat[, cum:= cumsum(val), by = group]
dat[, val := NULL]

   id group        cum
1:  1     1  1.3709584
2:  2     1  0.8062603
3:  3     2  0.3631284
4:  4     2  0.9959910
5:  5     2  1.4002593
6:  6     3 -0.1061245
7:  7     3  1.4053975
8:  8     3  1.3107384


text:
Q: Static initialization of array of struct A, where struct A contains a pointer to array of struct B (in C) Given the following typedefs:
// Structures for kana to romaji conversion lookup
typedef struct {
  const u16 kana; // Kana codepoint
  const char* romaji;
} KanaSuffix;

typedef struct {
  // Kana codepoint is implied by position in array
  const char* romaji;
  const KanaSuffix* suffixes;
} KanaPrefix;

Is it possible to initialize an array of KanaPrefix statically in a single step, where some elements of the array have suffixes pointing to a static array of KanaSuffix?
Now I'm doing this:
const KanaSuffix KANA_SUFFIXES_KI[] = {
  { 0x3030, "kya" },
  { 0x3032, "kyo" }
};

const KanaPrefix KANA_TO_ROMAJI[] = {
  { NULL, NULL },
  { "a", NULL },
  { "ki", KANA_SUFFIXES_KI }
};

But I want to do something more like this:
const KanaPrefix KANA_TO_ROMAJI[] = {
  { NULL, NULL },
  { "a", NULL },
  { "ki", {
    { 0x3030, "kya" },
    { 0x3032, "kyo" }
  } }
};

A: You can do something like:
const KanaPrefix KANA_TO_ROMAJI[] = {
  { NULL, NULL },
  { "a", NULL },
  { "ki",  (KanaSuffix [2]) {
      { 0x3030, "kya" },
      { 0x3032, "kyo" }
    }
  }
};

EDIT:
I can [now] confirm this is defined behaviour, since the lifetime [or duration] of that compound literal is the same as of static storage:

C99 §6.5.2.5 Compound literals
The value of the compound literal is that of an unnamed object
  initialized by the initializer list. If the compound literal occurs
  outside the body of a function, the object has static storage
  duration; otherwise, it has automatic storage duration associated with
  the enclosing block.

References:
What is the lifetime of compound literals passed as arguments?

A: If all you need is a static object, then you can use compound literals, since if defined outside of a function scope, have static storage duration.
Of course since the member suffixes of the struct KanaPrefix is pointing to more than one element you will need to store the count too:
typedef struct {
  const char* romaji;
  const KanaSuffix* suffixes;
  const size_t count;
} KanaPrefix;

const KanaPrefix KANA_TO_ROMAJI[] = {
  { NULL, NULL , 0 },
  { "a", NULL , 0 },
  { "ki", ( KanaSuffix[2] ){ //this is a compound literal
    { 0x3030, "kya" },
    { 0x3032, "kyo" }
  } , 2 }  //count is here
};


text:
Q: Is there any faster way to get this output file in linux cat file_1

my colour is red
my rose is red
my colour is blue
my rose id blue

cat file_2
red
blue

cat output_file should be
my colour is red
my colour is blue

here i am using
cat file_2 | while read line;do cat file_1 | grep "$line" | head -1;done

here i am trying to get the top most line containing the pattern "red" and "blue" which is present in the file_2
is there any other way  to do , as fast as possible, while loop is taking time

A: You can use a while construct to loop over the patterns from file2 and then use -m 1 with grep to stop after first match on file1:
while IFS= read -r i; do grep -Fm1 "$i" file1; done <file2

*

*-F treats the pattern literally

*-m 1 makes grep to exit after first match

Shell loops are usually not efficient, but given the pattern list is small it is usable in this case.
Faster alternative, xargs:
xargs -a file2 -n1 -P2 -I'{}' grep -Fm1 {} file1

Use more parallel processes (-P) for more patterns.
Example:
% while IFS= read -r i; do grep -Fm1 "$i" file1; done <file2
my colour is red
my colour is blue

% xargs -a file2 -n1 -P2 -I'{}' grep -Fm1 {} file1
my colour is blue
my colour is red

A: To print the first line from file_1 that matches a line in file_2:
$ awk 'FNR==NR{a[$0];next} {for (line in a) if ($0~line) {print; delete a[line]}}' file_2 file_1
my colour is red
my colour is blue

This approach reads through each file just once.
How it works

*

*FNR==NR{a[$0];next}
This saves every line in file_2 as a key in associative array a.

*for (line in a) if ($0~line) {print; delete a[line]}
For every line in file_1, we check to see if it matches a key in array a.  If it does, we print the line and delete the key.


text:
Q: Can't access collection from the shell - SyntaxError: missing ; before statement (shell):1 I wrote a script that uses mongoimport to load csv files into mongodb. When I run this for two similar csv files (of the same type) both upload fine, however I can only access one of them from the mongodb shell. Here is a transcript of a mongodb shell session:
> show collections
3mLgQAYJCq6_20110802
eTByWMY7zO6_20110802NonUniCode
system.indexes
> db.3mLgQAYJCq6_20110802
Thu Aug 18 18:44:49 SyntaxError: missing ; before statement (shell):1
> db.eTByWMY7zO6_20110802NonUniCode
vh.eTByWMY7zO6_20110802NonUniCode

However, I can access both collections from a python script and using mongoexport. I suspect there is a problem with the 3mLgQAYJCq6_20110802 file but I don't know where to start looking. Any ideas?

A: The collection name should start with a letter or the underscore.You can get the info about the naming convention for the collections in mongodb from below link-
http://www.mongodb.org/display/DOCS/Collections

A: This works for me when my collection names include special characters:
db["3mLgQAYJCq6_20110802"].findOne();

A: lovely collection names... it's probably because it's starts with a 3.


text:
Q: Kendo Binding to DataTable with additional custom column Someone pointed me to Kendo Bind to Data Table, which has this code in the grid builder:
.Columns(columns =>
{
    foreach (System.Data.DataColumn column in Model.Columns)
    {
        columns.Bound(column.ColumnName);
    }
})

This works, but I also want to add an "edit" column, so I added this line before the foreach:
columns.Command(command => command.Edit().Text("Edit").UpdateText("Submit")).Width(70).HtmlAttributes(new { style = "text-align: right;" });

which throws "Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions."
How can I add an Edit column?

A: As it turns out, "How can I add an Edit column?" is the wrong question.  There is nothing wrong with the code to add the Edit command; however, adding it surfaced the problem that was reported.  In other words, the "Template" in the error message is the Edit template which doesn't know what column in the DataTable to use for its Id.
When defining the DataSource for the grid, I had this code:
                .Model(model =>
                {
                    foreach (System.Data.DataColumn column in Model.Columns)
                    {
                        model.Field(column.ColumnName, column.DataType);
                    }
                })

as defined in a sample in a Telerik support forum.  This was OK for simply displaying the data in a grid, but when I introduced the idea of Editing, it then mattered that there was no Model.Id.  The question then became, how do I define an Id when the Model is a DataTable.  That is a separate question, which I have posted here.


text:
Q: I'm creating coins system and i want the data to be per server, how to do that? The data is the same in all the servers (for example if I'm print the amount of coins in my server, and then in other server that the bot in it shows the same amount because the data is the same), how to do it per server? (new coins data for every other server). (I created a coins.json file that saves the user ID and his amount of coins and command in the main (index.js) that adds coins to the user amount of coins in the JSON file).

A: Add the guild ID with the player ID into the JSON file and then when you call the player from the code, add a check to make sure that the guild the command was executed in (<message>.guild.id) is the same as the one in the database.
I would also recommend switching from JSON to MongoDB. In the past, my JSON files have corrupted multiple times.


text:
Q: Setting new value for key/setting if it exists in sbt build? Is it possible to check whether a key exists, and only define a new value for that key if it exists in the build?
The use case is that eclipse users on our team use sbteclipse (installed as a local plugin), and non-eclipse users do not install the plugin.  As soon as I define sbteclipse-specific keys in the build script, it breaks for the non-eclipse users.
The needed definition is:
EclipseKeys.createSrc := EclipseCreateSrc.Default + EclipseCreateSrc.Resource

This definition belongs to the build script (as opposed to being defined by individual users) because the build classpath is a property of the build/project.

A: You can use ? to see if there was a previous value of a setting when defining that setting.
The real issue here is that you need the types from the Eclipse plugin, which means that if it's not on the classpath, you can't reference the .createSrc key at all, because Scala will choke on any import of the plugin.
You have two options currently:

*

*Install the sbteclipse plugin on the project itself.  Only Eclipse users will call the tasks.

*Use reflection to grab the sbteclipse key off the classpath and do some dirty magic.

The sbt team is working on/proposing two solutions to fix this:

*

*AutoPlugins -  Releasing with sbt 0.13.5
With AutoPlugins you can specify a bunch of settings and dependencies on other plugins that get automatically included. Once the sbteclipse plugin is updated for AutoPlugins, you'll be able to do the following:
object MyCompanyPlugin extends AutoPlugin {
  override def requires: Plugins = EclipsePlugin
  override def trigger = allRequirements
  override def projectSettings = Seq(
    EclipseKeys.createSrc := EclipseCreateSrc.Default + EclipseCreateSrc.Resource
  )
}

Then, have your Eclipse users depend on this "company" plugin which will automatically "enhance" the existing sbteclipse plugin with your desired settings.

*There's a proposal for a notion of "build level" where you can optionally enable/disable .sbt files from being compiled/loaded such that you could, e.g., drop the sbteclipse plugin and have it only enabled for users who want it.


text:
Q: Nhibernate 3.0: problems with Future<> and Restrictions on a join table I can't figure out what the problem with nHibernate.
My domain is quite simple. Since most of my data is show in a paginated grid (jqGrid) I need to use Future<> to get the total number of rows.
If I run this chunk of code here it works properly:
ICriteria FiltersCriteriaCount = session.CreateCriteria<Domain.Reminder>();
ICriteria FiltersCriteria = session.CreateCriteria<Domain.Reminder>();

var TotalRecords = FiltersCriteriaCount
    .SetProjection(Projections.RowCount())
    .FutureValue<Int32>();

var sResult = FiltersCriteria
    .CreateAlias("Company", "Company")
    .CreateAlias("PlanType", "PlanType")
    .CreateAlias("OperationsManager", "OperationsManager")
    .CreateAlias("Schedules", "Schedules", NHibernate.SqlCommand.JoinType.LeftOuterJoin)
    .SetFirstResult(0)
    .SetMaxResults(100)
    .Future<Domain.Reminder>()
    .ToList<Domain.Reminder>();

but if I add a restriction I get an exception could not resolve property: Schedules.Notes of: BpReminders.Domain.Reminder:
ICriteria FiltersCriteriaCount = session.CreateCriteria<Domain.Reminder>();
ICriteria FiltersCriteria = session.CreateCriteria<Domain.Reminder>();

FiltersCriteriaCount.Add(Restrictions.Eq("Schedules.Notes", ""));
FiltersCriteria.Add(Restrictions.Eq("Schedules.Notes", ""));

var TotalRecords = FiltersCriteriaCount
    .SetProjection(Projections.RowCount())
    .FutureValue<Int32>();

var sResult = FiltersCriteria
    .CreateAlias("Company", "Company")
    .CreateAlias("PlanType", "PlanType")
    .CreateAlias("OperationsManager", "OperationsManager")
    .CreateAlias("Schedules", "Schedules", NHibernate.SqlCommand.JoinType.LeftOuterJoin)
    .SetFirstResult(0)
    .SetMaxResults(100)
    .Future<Domain.Reminder>()
    .ToList<Domain.Reminder>();

If I get rid of Future<> and trasform my code like this everything works fine:
ICriteria FiltersCriteria = session.CreateCriteria<Domain.Reminder>();
FiltersCriteria.Add(Restrictions.Eq("Schedules.Notes", ""));

var sResult = FiltersCriteria
    .CreateAlias("Company", "Company")
    .CreateAlias("PlanType", "PlanType")
    .CreateAlias("OperationsManager", "OperationsManager")
    .CreateAlias("Schedules", "Schedules", NHibernate.SqlCommand.JoinType.LeftOuterJoin)
    .SetFirstResult(0)
    .SetMaxResults(100)
    .List<Domain.Reminder>();

I can't find the reason for that.
Any help would be really really appreciated.

A: I'd say, try this:
var TotalRecords = FiltersCriteriaCount
    .CreateAlias("Schedules", "Schedules", NHibernate.SqlCommand.JoinType.LeftOuterJoin)
    .SetProjection(Projections.RowCount())
    .FutureValue<Int32>();


text:
Q: Data Refinery states I have maxed out my data limits. any way to clear/reset? I am trying to set up a data connection for Watson Analytics and IBM Data Refinery states I have maxed out my data limits. Is there a way to clear or reset?

A: The default IBM Cloud account type, known as a Lite account, provides access to all IBM Cloud based services that provide a Lite plan option. Those plans provide free, but limited, access to services. For Data Refinery (part of the Watson Knowledge Catalog & Watson Studio services), the lite plan has a limit of 50 Capacity Unit Hours per month. The message you're seeing appears when you have reached the limit of the free usage the plan provides. The limit is reset each calendar month and can be removed by upgrading your IBM Cloud account and associated service plan(s)
You can check which plan your services are on via this link:
https://dataplatform.ibm.com/console/overview
For information on account types, see here:
https://console.bluemix.net/docs/account/index.html#accounts
For information on changing service plans, see here:
https://console.bluemix.net/docs/account/change-plan.html#changing
For information on Capacity Unit Hours in relation to Data Flows (which Data Refinery creates), see here:
https://www.ibm.com/cloud/watson-knowledge-catalog/faq


text:
Q: GoogleMap: center or defaultCenter property must be defined My project is using the GoogleMapReact component and when I start the application my map doesn't load and I receive the following warnings:
GoogleMap: center or defaultCenter property must be defined
Google Maps already loaded outside @googlemaps/js-api-loader. This may result in undesirable behavior as options and script parameters may not match.
I dont know if this is an issue within the GoogleMapReactComponent or the Map component in app.js so I will post both if anyone can help me break down why the map isn't loading it would be a big help. Thank you in advance.
import React from 'react';
import GoogleMapReact from 'google-map-react';
import { Paper, Typography, useMediaQuery } from '@material-ui/core';
import LocationOnOutlinedIcon from '@material-ui/icons/LocationOnOutlined';
import Rating from '@material-ui/lab/Rating';

import useStyles from './styles';

import mapStyles from './mapStyles'

const Map = ({coords, setCoords, setBounds, places, setChildClicked, weatherData}) => {
    const classes = useStyles();
    const matches = useMediaQuery('(min-width:600px)');

    return (

            <GoogleMapReact
                bootstrapURLKeys={{ key: process.env.REACT_APP_GOOGLE_MAPS_API_KEY }}
                defaultCenter={coords}
                center={coords}
                defaultZoom={14}
                margin={[50, 50, 50, 50,]}
                options={{ disableDefaultUI: true, zoomControl: true, styles: mapStyles }}
                onChange={(e) => {
                    setCoords({ lat: e.center.lat, lng: e.center.lng });
                    setBounds({ ne: e.marginBounds.ne, sw: e.marginBounds.sw });
                }}

                onChildClick={(child) => setChildClicked(child)}

            >
                {places?.length && places?.map((place, i) => (

                        {!matches ?
                            <LocationOnOutlinedIcon color="primary" fontSize="large" />
                            : (
                                <Paper elevation={3} className={classes.paper}>
                                    <Typography className={classes.typography} variant="subtitle2" gutterBottom> {place.name}</Typography>

                                    <Rating size="small" value={Number(place.rating)} name="read-only" />

                                </Paper>
                            )}

                ))}

                {weatherData?.list?.length && weatherData.list.map((data, i) => (

                        <img src={`https://openweathermap.org/img/w/${data.weather[0].icon}.png`} height="70px" alt="map"/>

                ))}

            </GoogleMapReact>

    );
}

export default Map;

import React, { useState, useEffect } from 'react';
import { CssBaseline, Grid } from '@material-ui/core';

import { getPlacesData, getWeatherData } from './api/index'

import Header from './components/Header/Header';
import List from './components/List/List';
import Map from './components/Map/Map';

const App = () => {
    const [type, setType] = useState('restaurants');
    const [rating, setRating] = useState('');

    const [coords, setCoords] = useState({});
    const [bounds, setBounds] = useState(null);

    const [weatherData, setWeatherData] = useState([]);
    const [filteredPlaces, setFilteredPlaces] = useState([]);
    const [places, setPlaces] = useState([]);

    const [autocomplete, setAutocomplete] = useState(null);
    const [childClicked, setChildClicked] = useState(null);
    const [isLoading, setIsLoading] = useState(false);

    useEffect(() => {
        navigator.geolocation.getCurrentPosition(({ coords: {latitude, longitude} }) => {
            setCoords({ lat: latitude, lng: longitude});

        });

    }, []);

    useEffect(() => {
        const filtered = places.filter((place) => Number(place.rating) > rating);

        setFilteredPlaces(filtered);
    }, [rating]);

    useEffect(() => {
        if(bounds) {
        setIsLoading(true);

        getWeatherData(coords.lat, coords.lng)
        .then((data) => setWeatherData(data));

        getPlacesData(type, bounds.sw, bounds.ne)
        .then((data) => {
            setPlaces(data.filter((place) => place.name && place.num_reviews > 0));
            setFilteredPlaces([]);
            setRating('');
            setIsLoading(false);
        });
    }

    },[bounds, type]);

    const onLoad = (autoC) => setAutocomplete(autoC);

    const onPlaceChanged = () => {
        const lat = autocomplete.getPlace().geometry.location.lat();
        const lng = autocomplete.getPlace().geometry.location.lng();

        setCoords({ lat, lng });
    };

    return (
     <>
     <CssBaseline />

     <Grid container spacing ={3} style={{ width: '100%' }}>
         <Grid item xs={12} md={4}>
             <List
             places={filteredPlaces.length ? filteredPlaces : places}
             childClicked={childClicked}
             isLoading={isLoading}
             type={type}
             setType={setType}
             setRating={setRating}
             rating={rating}

             />

         </Grid>
         <Grid item xs={12} md={8} style={{display: 'flex', justfiyContent: 'center', alignItems: 'center' }}>
             <Map
             setChildClicked={setChildClicked}
             setCoordinates={setCoords}
             setBounds={setBounds}
             coordinates={coords}
             places={filteredPlaces?.length ? filteredPlaces : places}
             weatherData={weatherData}
             />

         </Grid>

     </Grid>

     </>
    );
};

export default App;

A: On the initial mount of your components, coords is just an empty object.  The useEffect that populates it doesn't run until after the first render.  A typical pattern to deal with this is to render nothing or a loading component when the required props are not available.  The simplest route would be to set the initial state of coords to something falsey and only render Map when it isn't falsey
const [coords, setCoords] = useState({});
...
{coords && <Map ... />}

Another option would be to keep track of whether coords has been loaded within state -
const [coords, setCoords] = useState({});
const [coordsLoaded, setCoordsLoaded] = useState(false);

useEffect(() => {
    navigator.geolocation.getCurrentPosition(({ coords: {latitude, longitude} }) => {
        setCoords({ lat: latitude, lng: longitude});
        setCoordsLoaded(true);
    });
}, []);

...
{coordsLoaded && <Map ... />}


text:
Q: rails 3.1, how to calculate answers number using foreign key? I have the following tables:
class FinalExam < ActiveRecord::Base
  belongs_to :course
  has_many :pages, :as => :course_unit, :dependent => :destroy
end

class Page < ActiveRecord::Base
  belongs_to :course_unit, :polymorphic => true
  has_one :quiz
  has_one :slide
end

class Quiz < ActiveRecord::Base
  belongs_to :page
end

class Answers < ActiveRecord::Base
  belongs_to :quiz
end

So, we have Answer.Quiz.Page.FinalExam
Given the FianlExam id, what is the fastest way to find all Answers count ? how to get it ?
I can re-design the DB to have belongs_to :final_exam in Answers
class Answers < ActiveRecord::Base
  belongs_to :quiz
  belongs_to :final_exam
end

this way, I can say Answers.where(:final_exam_id=> params[:id]).count
Do I have to change the DB design ? or its a matter of a query ?
I need an expert advice please.

A: First of all I'm guessing that Quiz should read:
class Quiz < ActiveRecord::Base
  belongs_to :page
  has_many :answers
end

If so you can add these lines to your FinalExam model:
has_many :quizzes, :through => :pages
has_many :answers, :through => :quizzes

Allowing you to then call
FinalExam.first.answer.count

(Note: if you're on a version of Rails < 3.1, you'll need this plugin)
The drawback to this approach is that it becomes slow with a lot of data. In this case, you'd want to set up a counter cache in the FinalExam that updates every time an answer is added. It'd a little more complicated because of the many-layered relationships you have; see this post for more info:
counter_cache has_many_through sql optimisation, reduce number of sql queries


text:
Q: update table using nested subqueries I have two table where I want to update one of the tables using info from another table.
create table CUSTOMER
(CID number(6),
First_Name varchar2(12),
Last_Name varchar2(12),
Category varchar2(7),
Balance_Due number(4,2),
SponsorID number(6),
CONSTRAINT pkCID PRIMARY KEY (CID),
CONSTRAINT fkCUSTOMER foreign key (sponsorID) references customer);

And the table I want to update:
create table BOOK_COPY
(Copy_Num number(5),
Bookid  number(5),
out_to_CID number(6),
Date_Out date,
Date_Due date,
Held_Until date,
held_for_CID number(6),
CONSTRAINT PKCOPY PRIMARY KEY (Copy_Num,Bookid),
CONSTRAINT FKCID FOREIGN KEY (out_to_CID) references CUSTOMER (CID),
CONSTRAINT FKHeld FOREIGN KEY (held_for_CID) references CUSTOMER (CID),
CONSTRAINT FKBookid FOREIGN KEY (Bookid) references BOOK (Bookid));

What I want to do is update BOOK_COPY so date_due = Date_out + 90 where category=faculty
Also I would like to be able to update more than one category using a case when.
I can update if I dont have the "where category='faculty'" clause in my statement. But I get an syntax error when I try to get the customer table.

A: If you want to have different periods for different categories, I would suggest:
update book_copy b
    set date_due = (case (select category from customer c where c.cid= b.out_to_cid)
                        when 'faculty' then date_out + 90
                        when 'administrator' then date_out + 120
                        when 'student' then date_out - 10
                        else date_due
                    end);


text:
Q: MSBuild Batching on Three Independent Variables I have been writing a build system based on MSBuild, and am to the end of the project where I need to essentially run the one msbuild file 88 times by batching over three variables:
Configuration = Debug; Beta; Release; Evaluation
Platform = x86; x64
Language = CN; CS; DE; EN; ES; FR; IT; JP; KO; PL; TW
I want to build:
"Debug x86 CN", "Debug x86 CS", ... "Debug x86 TW"
"Debug x64 CN", ...
I can, of course, define 88 of these:
<ItemGroup>
  <ToBuild Include="Debug_x86_CN">
    <Configuration>Debug</Configuration>
    <Platform>x86</Platform>
    <Language>EN</Language>
  </ToBuild>
<ItemGroup>

And then batch based on metadata. But what a drag! Can I create the 88 permutations in code, so adding a language is as easy as adding three characters to an ItemGroup:
<ItemGroup>
  <AllConfigurations Include="Beta; Release; Evaluation;"/>
  <AllPlatforms Include="x86; x64" />
  <AllLanguages Include="CN; CS; DE; EN; ES; FR; IT; JP; KO; PL; TW" />
</ItemGroup>

A: Thanks to Anders Ljusberg for posting an answer to this years ago. The solution is to use the CreateItem task to combine the individual ItemGroups into one ItemGroup. The cross product of each item needs to be done one at a time into a new ItemGroup (in this case _Config_X_Language and _Config_X_Language_X_Platform) to prevent empty metadata from leaking in (if you try to reuse _Config_X_Language, you'll get items with empty Platform, n addition to the platforms in $(Platform).
<ItemGroup>
  <Configuration Include="Beta; Release; Evaluation;"/>
  <Platform Include="x86; x64" />
  <Language Include="CN; CS; DE; EN; ES; FR; IT; JP; KO; PL; TW" />
</ItemGroup>

<!-- Create an ItemGroup that is the cross product of Configuration and Language: -->
<CreateItem Include="@(Configuration)" AdditionalMetadata="Language=%(Language.Identity);" >
  <Output ItemName="_Config_X_Language" TaskParameter="Include"/>
</CreateItem>
<!-- Create another ItemGroup that is the cross product of _Configuration_X_Language and Platform: -->
<CreateItem Include="@(_Config_X_Language)" AdditionalMetadata="Platform=%(Platform.Identity);" >
  <Output ItemName="_Config_X_Language_X_Platform" TaskParameter="Include"/>
</CreateItem>

<!-- Task batch over each unique set of metadata on AllBuilds -->
<MSBuild Projects="myproject.msbuild"
          Properties="Configuration=%(_Config_X_Language_X_Platform.Identity);
                      Platform=%(_Config_X_Language_X_Platform.Platform);
                      Language=%(_Config_X_Language_X_Platform.Language);"
          Targets="MyTarget"
          BuildInParallel="true" />

A: It is a good idea to combine the individual ItemGroups into one ItemGroup.
However, when using this method MSBuild builds projects ignoring attribute BuildInParallel (all projects building consistently).
So you need something to supplement script:
<ItemGroup>
  <Configuration Include="Beta; Release; Evaluation;"/>
  <Platform Include="x86; x64" />
  <Language Include="CN; CS; DE; EN; ES; FR; IT; JP; KO; PL; TW" />
</ItemGroup>

<!-- Create an ItemGroup that is the cross product of Configuration and Language: -->
<CreateItem Include="@(Configuration)" AdditionalMetadata="Language=%(Language.Identity);" >
  <Output ItemName="_Config_X_Language" TaskParameter="Include"/>
</CreateItem>
<!-- Create another ItemGroup that is the cross product of _Configuration_X_Language and Platform: -->
<CreateItem Include="@(_Config_X_Language)" AdditionalMetadata="Platform=%(Platform.Identity);" >
  <Output ItemName="_Config_X_Language_X_Platform" TaskParameter="Include"/>
</CreateItem>

<!--Creating groups for projects to build-->
<!--In the attribute AdditionalMetadata sign '=' is changed to '%3D', and the sign ';'' changed to '%3B'-->
<CreateItem Include="myproject.msbuild" AdditionalMetadata="Properties=
                                                            Configuration%3D%(_Config_X_Language_X_Platform.Identity)%3B
                                                            Platform%3D%(_Config_X_Language_X_Platform.Platform)%3B
                                                            Language%3D%(_Config_X_Language_X_Platform.Language)" >
  <Output ItemName="ProjectToBuild" TaskParameter="Include"/>
</CreateItem>

<!--Task batch build all projects parallel -->
<MSBuild Projects="@(ProjectToBuild)"
         Targets="MyTarget"
         BuildInParallel="true"
         StopOnFirstFailure="true" />


text:
Q: Function to create new array producing undefined I am trying to write a program that creates an array and populates it with a range of numbers. The function  range's x, y, z variables correlates to the start number, the end number, and the number value of each step. My goal is produce an array with all the numbers between (and including) x and y that is created with each step. Here is the code:

let newarray = []

function range (x, y, z){
  if (x === undefined || y === undefined || z === undefined || (x > y) || (z < 0)) {
    return newarray;                          // returns empty array if x, y, or z is undefined, x is greater than y or z is a negative integer
  }
  else if (y > x) {
    for (x; x < y; x = x += z) {
      newarray.push(x);                       //pushes x into an array then adds z into x and loops until x exceeds y
    }
  }
  else {
    return newarray;                          //prints out new array
  }
}

console.log(range(0, 10, 2));
console.log(range(10, 30, 5));
console.log(range(-5, 2, 3));

right now it is producing undefined for all three numbers. My research suggests something about asynchronicity? I'm not sure what that means.

A: A few things are at play here:

*

*newArray should be defined inside the function scope rather than as a global variable. Otherwise, subsequent calls to the function will keep appending onto the same array, which is likely not your intention (and if it was, there's array.concat() for that).

*Your last else is unreachable, so the function will either return an empty array for input failing your validation or return undefined when control reaches the end of the function after populating the array in the else if block.

*x = x += z is probably intended as x += z.

*You should disallow z === 0 otherwise you'll wind up with an infinite loop.

*Normal JS style is to camelCase variable names.
Additionally, I find it's easier to write positive conditionals than negative conditionals. In this case, enumerating what arguments are allowed seems cleanest. This approach enables you to only have one return statement and fewer conditional branches, mitigating potential confusion.
Here's a version that addresses these issues:

function range(x, y, z) {
  const newArray = [];

  if ([x, y, z].indexOf(undefined) < 0 && x < y && z > 0) {
    for (; x < y; x += z) {
      newArray.push(x);
    }
  }

  return newArray;
}

console.log(range(0, 10, 2));
console.log(range(10, 30, 5));
console.log(range(-5, 2, 3));

A: Note that the section where you check else if (y > x) does not have a return. When this condition is true, your function returns undefined. To fix the problem, just add return newarray; as the last line in the function. Then remove all other lines with return new array;.

A: *

*The else block is not required as it will be unreachable and will
return undefined.

*Corrected x = x + z from x = x += z.

*The array declaration was outside, so every time the old data will be
appended with newer data from the for loop.

 function range (x, y, z){

      let newarray = [];

      if (x === undefined || y === undefined || z === undefined ||  (x > y) || (z < 0)){
        return newarray;
      }
      else if (y > x) {
       for (x; x < y; x = x + z){
           newarray.push(x);
        }
      }
    return newarray;

    }
    console.log(range(0, 10, 2));
    console.log(range(10, 30, 5));
    console.log(range(-5, 2, 3));