text:
Q: Problems creating hyperlinks on Excel Mac with xlsx r package I am trying to create an Excel File with r which should include hyperlinks to a website. Everything works fine and can be tested on Windows, but on my Mac it somehow fails... I get the message that

Unable to open "LINK". Cannot locate the internet server or proxy server.

I am not sure if the problem is my excel, my mac or whatever. Could somebody help me to narrow the problem down?
EDIT: I just figured out, google works for example. Updated my example.
Here is a reproducible example
library(xlsx)

df <- data.frame(
  Protein.IDs=c("A0A024QZN2;Q8WXX5;Q2VIL4",
                "A0A024QZY5;Q13523;B4DZQ5;H0YDJ3;D3DWH5"),
  stringsAsFactors=FALSE
)

df$Uniprot <-
  sprintf('https://www.uniprot.org/uniprot/?query=%s',
          sapply(strsplit(df$Protein.IDs, ';'), paste, collapse='+OR+'))

df <- rbind(df, c('google link', 'https://google.de')) # EDIT: google works?

excel_wb <- createWorkbook()
sheet <- xlsx::createSheet(excel_wb, sheetName='proteins')
addDataFrame(df, sheet, col.names = TRUE, row.names = FALSE)

rows <- getRows(sheet)
cells <- getCells(rows, colIndex=grep('^Uniprot$', names(df)))

invisible(sapply(cells[-1], function(x) {
  addHyperlink(x, getCellValue(x))
  setCellValue(x, 'Uniprot Link')
}))

rMQanalysis::saveWorkbookMQ(excel_wb, 'uniprottest.xlsx')

A: For some reason, after a restart of the computer, everything works. Not sure what and if something changed.


text:
Q: Printf does not work unless another printf is present I was trying to solve a challenge in C on HackerRank. There is a square matrix with n rows and columns.The challenge is to print the absolute difference between the two sums of the matrix's diagonals as a single integer.
Here's the link:
https://www.hackerrank.com/challenges/diagonal-difference
I'm able to get the correct answer but the printf() statement at the end of the code does not work unless I add an unnecessary  printf("") before the for loop statement.
Could someone explain why this is happening?
Thanks in advance
Here's the code:
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>

int main()
{
    int n;
    scanf("%d",&n);
    int a[n][n],sum_d1=0,sum_d2=0,a_i,a_j;
    for( a_i = 1; a_i <= n; a_i++)
    {
       for(a_j = 1; a_j <= n; a_j++)
       {
           scanf("%d",&a[a_i][a_j]);
           if(a_j==a_i)
               sum_d1=sum_d1+a[a_i][a_j];
       }
    }
    printf("");// the last printf works only when this statement is present
    for(a_i=1;a_i<=n;a_i++)
    {
        for(a_j=n;a_j>0;a_j--)
        {
            if((a_i+a_j)==(n+1))
                sum_d2=sum_d2+a[a_i][a_j];
        }
    }
    printf("%d",abs(sum_d1-sum_d2)); //this doesn't work if there is no printf above
    return 0;
}

A: The trailing newline is the key here.  Standard out only flushes when it encounters a line ending for performance reasons.  If you change to fprintf(stderr, ...) then your code will work as is. You could also use fflush(stdout) after your printf's.

A: As a couple of other people have mentioned, your main issue is your array declaration / use. Arrays in C have their first index from 0, not from 1. As such, when you try and store things in your array, or access them again, it is out of the boundary of the array, and may act in a way unintended.
Array example: Array[2][3]
    0  1
0  a|  b |
1  c|  d |
2  e|  f |

Array[0][0] == a
Array[1][1] == d
Array[1][2] == f

In your code, if someone enters "1", an array of size [1][1] is created - a single element. This should be accessed using a[0][0], but in the code is being accessed by a[1][1], which is an invalid element, as it is not a part of the array.
Without knowing exactly what you intend your code to do, I cannot fix it entirely, but a good start would be as below:
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>

int main(){
    int n;
    scanf("%d",&n);
    int a[n][n],sum_d1=0,sum_d2=0,a_i,a_j;
    for( a_i = 0; a_i < n; a_i++){
       for(a_j = 0; a_j < n; a_j++){
           scanf("%d",&a[a_i][a_j]);
           if(a_j==a_i)
               sum_d1=sum_d1+a[a_i][a_j];
       }
    }
    //printf("");// the last printf works only when this statement is present
    for(a_i=0;a_i<n;a_i++)
    {
        for(a_j=n-1;a_j>=0;a_j--)
        {
            if((a_i+a_j)==(n+1))
                sum_d2=sum_d2+a[a_i][a_j];
        }
    }
    printf("%d",abs(sum_d1-sum_d2)); //this doesn't work if there is no printf above
    return 0;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Taking a range as a struct field There are multiple Range types. Some Range types implement Iterator. I want to take all Range types that implement Iterator as a struct field.
This is my approach:
pub trait RangeBoundsExt<T: PartialOrd<T>>: Iterator<Item = T> {
    // some methods
}

impl<T: PartialOrd<T>> RangeBoundsExt<T> for std::ops::Range<T> {}

impl<T: PartialOrd<T>> RangeBoundsExt<T> for std::ops::RangeFrom<T> {}

impl<T: PartialOrd<T>> RangeBoundsExt<T> for std::ops::RangeInclusive<T> {}

pub struct Foo<T> {
    range: Box<dyn RangeBoundsExt<T>>
}

Playground
But I am getting this error:
  Compiling playground v0.0.1 (/playground)
error[E0277]: the trait bound `T: std::iter::Step` is not satisfied
 --> src/lib.rs:7:24
  |
7 | impl<T: PartialOrd<T>> RangeBoundsExt<T> for std::ops::Range<T> {}
  |                        ^^^^^^^^^^^^^^^^^ the trait `std::iter::Step` is not implemented for `T`
  |
  = note: required because of the requirements on the impl of `std::iter::Iterator` for `std::ops::Range<T>`
help: consider further restricting this bound
  |
7 | impl<T: PartialOrd<T> + std::iter::Step> RangeBoundsExt<T> for std::ops::Range<T> {}
  |                       ^^^^^^^^^^^^^^^^^

error[E0277]: the trait bound `T: std::iter::Step` is not satisfied
 --> src/lib.rs:9:24
  |
9 | impl<T: PartialOrd<T>> RangeBoundsExt<T> for std::ops::RangeFrom<T> {}
  |                        ^^^^^^^^^^^^^^^^^ the trait `std::iter::Step` is not implemented for `T`
  |
  = note: required because of the requirements on the impl of `std::iter::Iterator` for `std::ops::RangeFrom<T>`
help: consider further restricting this bound
  |
9 | impl<T: PartialOrd<T> + std::iter::Step> RangeBoundsExt<T> for std::ops::RangeFrom<T> {}
  |                       ^^^^^^^^^^^^^^^^^

error[E0277]: the trait bound `T: std::iter::Step` is not satisfied
  --> src/lib.rs:11:24
   |
11 | impl<T: PartialOrd<T>> RangeBoundsExt<T> for std::ops::RangeInclusive<T> {}
   |                        ^^^^^^^^^^^^^^^^^ the trait `std::iter::Step` is not implemented for `T`
   |
   = note: required because of the requirements on the impl of `std::iter::Iterator` for `std::ops::RangeInclusive<T>`
help: consider further restricting this bound
   |
11 | impl<T: PartialOrd<T> + std::iter::Step> RangeBoundsExt<T> for std::ops::RangeInclusive<T> {}
   |                       ^^^^^^^^^^^^^^^^^

error: aborting due to 3 previous errors

For more information about this error, try `rustc --explain E0277`.
error: could not compile `playground`.

To learn more, run the command again with --verbose.

A: Range does not guarantee an Iterator implementation. It only provides one if the type implements Step. Likewise, RangeTo does not guarantee a lack of an Iterator implementation. It simply just doesn't provide one by default. To fix your error, you simply have to require that there is an iterator definition for the range:
// note the additional 'where' requirement
impl<T: PartialOrd<T>> RangeBoundsExt<T> for std::ops::Range<T> where
    std::ops::Range<T>: Iterator<Item = T>
{
}

impl<T: PartialOrd<T>> RangeBoundsExt<T> for std::ops::RangeFrom<T> where
    std::ops::RangeFrom<T>: Iterator<Item = T>
{
}

impl<T: PartialOrd<T>> RangeBoundsExt<T> for std::ops::RangeInclusive<T> where
    std::ops::RangeInclusive<T>: Iterator<Item = T>
{
}


text:
Q: How to access the meaning of a OID variable (Linux)? I am using snmpwalk to derive a subtree of management values. One of the lines reads, for example,
iso.3.6.1.2.1.25.1.5.0 = Gauge32: 10

but what does it mean? What device/function, ... corresponds to the OID iso.3.6.1.2.1.25.1.5.0, and what does the number '10' stand for?
How to find out completly general for ANY OID (not just for this exemplary one)?

A: You can use the snmptranslate command:
$ snmptranslate iso.3.6.1.2.1.25.1.5.0
HOST-RESOURCES-MIB::hrSystemNumUsers.0

Or you can do the lookup in reverse with -On:
$ snmptranslate -On HOST-RESOURCES-MIB::hrSystemNumUsers.0
.1.3.6.1.2.1.25.1.5.0

(Note that the iso. in the first look-up means the same as the .1. that the reverse translate shows)
As noted in the comments, yes, you need the MIB installed in order to do these lookups, see your device vendor for the MIB file download. From what I've seen with a generic install of net-snmp, you get most of what you already are looking for.

A: iso.3.6.1.2.1.25.1.5.0  OID provide number of logged in Users info.
Gauge32 is OID type, Gauge32 you can expect the data increases and decreases based on what real world information it tries to provide
10 means number of users currently logged in your system.


text:
Q: Ordering by category id and price on index page I'm having trouble with ordering my houses. I have a houses that belong_to category (category has_many houses) and I want to order the houses on the index based on their category_id, but whatever I try it doesn't seem to change the order. It's a mystery to me. Maybe you could help me out?
class HousesController < ApplicationController
  skip_before_action :authenticate_user!, only: [:index, :show]
  before_action :set_house, only: [ :show, :edit, :update, :destroy, :inquiry ]

  def index
    # byebug
    @houses = policy_scope(House).order(:name)
    @houses = params.has_key?(:h) ? index_result(@houses) : @houses
    # split_categories(@houses)
  end

  def index_result(houses)
    # byebug
    wall_thickness = params[:h].to_i
    if wall_thickness == 1
      houses.order(:name)
      render "results_index_all"
    elsif wall_thickness == 28 || 40
      houses = houses.where(:wall => wall_thickness)
      houses.order(:name)
      render "results_index"
    else
    end
  end

  def split_categories(houses)
    # @houses_1 = @houses.where(price_cents: 0...260000)
    # @houses_2 = @houses.where(price_cents: 260000..1000000)
    # byebug
    category = Category.find_by(id: params[:category])
    houses = @category.present? ? category.houses.order(price_cents: :asc) : houses
  end

  def show
  end

  def new
    @house = House.new
    authorize @house
  end

  def create
    @house = House.new(house_params)
    @house.user = current_user
    authorize @house
    if @house.save
      redirect_to house_path(@house)
    else
      render :new
    end
  end

  def edit
  end

  def update
    if @house.update(house_params)
      redirect_to house_path(@house)
    else
      render :edit
    end
  end

  def destroy
    @house.destroy
    redirect_to root_path
  end

  private

  def set_house
    @house = House.friendly.find(params[:id])
    authorize @house
  end

  def house_params
    params.require(:house).permit(:sku, :name, :price_cents, :width, :length, :wall, pictures: [])
  end

end

Below is the normal index where I split houses up in categories starting with category_id: 2 (normal garden houses), then 1 (gazebos) and finally 3 (garages). This is partial which is rendered app/views/houses/index.html.erb
<% if !@category %>
<%= render 'first-banner-home' %>

    <%= render "filter_buttons" %>

      <% @houses.where(category_id: 2).each do |house| %>

          <% if house.pictures? %>

              <%= cl_image_tag(house.pictures[0], :quality=>50, :width=>1800, :crop=>"scale", class: "card-img-top", alt: house.name + " " + house.category.name) %>
              <%= link_to "", house_path(house), class: "card-link" %>

          <% end %>

<%= house.name %>

<%= house.length.to_f / 100 %> x <%= house.width.to_f.to_f / 100 %> m

            <% if house.price_present == false %>

<%= t('show.consult') %>

            <% else %>

<%= humanized_money_with_symbol(house.original_price) %> - 15% = <%= humanized_money_with_symbol(house.price) %>

              <% end %>

            <% if policy(house).update? %>
              <%= link_to "Edit", edit_house_path(house) %>
            <% end %>
            <% if policy(house).destroy? %>
              <%= link_to "Remove", house_path(house), method: :delete, data: { confirm: "Are you sure?" } %>
            <% end %>

      <% end %>

<%= t('home.gazebos') %>

      <% @houses.where(category_id: 1).each do |house| %>

          <% if house.pictures? %>

              <%= cl_image_tag(house.pictures[0], :quality=>50, :width=>1800, :crop=>"scale", class: "card-img-top-alt", alt: house.name + " " + house.category.name) %>
              <%= link_to "", house_path(house), class: "card-link" %>

          <% end %>

<%= house.name %>

<%= house.length.to_f / 100 %> x <%= house.width.to_f.to_f / 100 %> m

            <% if house.price_present == false %>

<%= t('show.consult') %>

            <% else %>

<%= humanized_money_with_symbol(house.original_price) %> - 15% = <%= humanized_money_with_symbol(house.price) %>

              <% end %>

            <% if policy(house).update? %>
              <%= link_to "Edit", edit_house_path(house) %>
            <% end %>
            <% if policy(house).destroy? %>
              <%= link_to "Remove", house_path(house), method: :delete, data: { confirm: "Are you sure?" } %>
            <% end %>

      <% end %>

<%= t('home.garages') %>

      <% @houses.where(category_id: 3).each do |house| %>

          <% if house.pictures? %>

              <%= cl_image_tag(house.pictures[0], :quality=>50, :width=>1800, :crop=>"scale", class: "card-img-top-alt", alt: house.name + " " + house.category.name) %>
              <%= link_to "", house_path(house), class: "card-link" %>

          <% end %>

<%= house.name %>

<%= house.length.to_f / 100 %> x <%= house.width.to_f.to_f / 100 %> m

            <% if house.price_present == false %>

<%= t('show.consult') %>

            <% else %>

<%= humanized_money_with_symbol(house.original_price) %> - 15% = <%= humanized_money_with_symbol(house.price) %>

              <% end %>

            <% if policy(house).update? %>
              <%= link_to "Edit", edit_house_path(house) %>
            <% end %>
            <% if policy(house).destroy? %>
              <%= link_to "Remove", house_path(house), method: :delete, data: { confirm: "Are you sure?" } %>
            <% end %>

      <% end %>

  <%= render "last-banner" %>
<% elsif params[:h].present? %>
  <%= render "results_index" %>
<% else %>
  <%= render "category_index" %>
<% end %>

This is the index where the houses are filtered based on their wall thickness (see in app/controllers/houses_controller.rb ). This is where I want the house to order based on their category_id, which doesn't work at the moment.
<% content_for(:title) do %><%= t('topbar.brand') %><% end %>
<% content_for(:og_site_name) do %><%= t('topbar.brand') %><% end %>
<% content_for(:description) do %><%= t('garden_houses.meta_description') %><% end %>
<% content_for(:og_image) do %><%= cl_image_path("https://res.cloudinary.com/www-ibizagardenhouses-com/image/upload/c_scale,h_630,w_1200/v1558696079/ibi-3/image.jpg") %><% end %>
<% content_for(:og_description) do %><%= t('garden_houses.meta_description') %><% end %>
<%= render 'first-banner-results' %>
<% if @houses.count >= 4 %>

    <%= render "filter_buttons" %>

      <% @houses.each do |house| %>

          <% if house.pictures? %>

              <%= cl_image_tag(house.pictures[0], :quality=>50, :width=>1800, :crop=>"scale", class: "card-img-top", alt: house.name + " " + house.category.name) %>
              <%= link_to "", house_path(house), class: "card-link" %>

          <% end %>

<%= house.name %>

<%= house.length.to_f / 100 %> x <%= house.width.to_f.to_f / 100 %> m

            <% if house.price_present == false %>

<%= t('show.consult') %>

            <% else %>

<%= humanized_money_with_symbol(house.original_price) %> - 15% = <%= humanized_money_with_symbol(house.price) %>

              <% end %>

            <% if policy(house).update? %>
              <%= link_to "Edit", edit_house_path(house) %>
            <% end %>
            <% if policy(house).destroy? %>
              <%= link_to "Remove", house_path(house), method: :delete, data: { confirm: "Are you sure?" } %>
            <% end %>

      <% end %>

  <%= render "last-banner" %>
<% else %>

    <%= render "filter_buttons" %>

      <% @houses.each do |house| %>

          <% if house.pictures? %>

              <%= cl_image_tag(house.pictures[0], :quality=>50, :width=>1800, :crop=>"scale", class: "card-img-top-alt", alt: house.name + " " + house.category.name) %>
              <%= link_to "", house_path(house), class: "card-link" %>

          <% end %>

<%= house.name %>

<%= house.length.to_f / 100 %> x <%= house.width.to_f.to_f / 100 %> m

            <% if house.price_present == false %>

<%= t('show.consult') %>

            <% else %>

<%= humanized_money_with_symbol(house.original_price) %> - 15% = <%= humanized_money_with_symbol(house.price) %>

              <% end %>

            <% if policy(house).update? %>
              <%= link_to "Edit", edit_house_path(house) %>
            <% end %>
            <% if policy(house).destroy? %>
              <%= link_to "Remove", house_path(house), method: :delete, data: { confirm: "Are you sure?" } %>
            <% end %>

      <% end %>

  <%= render "last-banner" %>
<% end %>

This is exactly the same html as app/views/houses/results_index.html.erb , but where I show all the houses (params[h: 1]) in a layout that's not the same as the home page. Same problem here as on the filtered results page.
<% content_for(:title) do %><%= t('topbar.brand') %><% end %>
<% content_for(:og_site_name) do %><%= t('topbar.brand') %><% end %>
<% content_for(:description) do %><%= t('garden_houses.meta_description') %><% end %>
<% content_for(:og_image) do %><%= cl_image_path("https://res.cloudinary.com/www-ibizagardenhouses-com/image/upload/c_scale,h_630,w_1200/v1558696079/ibi-3/image.jpg") %><% end %>
<% content_for(:og_description) do %><%= t('garden_houses.meta_description') %><% end %>
<%= render 'first-banner-all' %>
<% if @houses.count >= 4 %>

    <%= render "filter_buttons" %>

      <% @houses.each do |house| %>

          <% if house.pictures? %>

              <%= cl_image_tag(house.pictures[0], :quality=>50, :width=>1800, :crop=>"scale", class: "card-img-top", alt: house.name + " " + house.category.name) %>
              <%= link_to "", house_path(house), class: "card-link" %>

          <% end %>

<%= house.name %>

<%= house.length.to_f / 100 %> x <%= house.width.to_f.to_f / 100 %> m

            <% if house.price_present == false %>

<%= t('show.consult') %>

            <% else %>

<%= humanized_money_with_symbol(house.original_price) %> - 15% = <%= humanized_money_with_symbol(house.price) %>

              <% end %>

            <% if policy(house).update? %>
              <%= link_to "Edit", edit_house_path(house) %>
            <% end %>
            <% if policy(house).destroy? %>
              <%= link_to "Remove", house_path(house), method: :delete, data: { confirm: "Are you sure?" } %>
            <% end %>

      <% end %>

  <%= render "last-banner" %>
<% else %>

    <%= render "filter_buttons" %>

      <% @houses.each do |house| %>

          <% if house.pictures? %>

              <%= cl_image_tag(house.pictures[0], :quality=>50, :width=>1800, :crop=>"scale", class: "card-img-top-alt", alt: house.name + " " + house.category.name) %>
              <%= link_to "", house_path(house), class: "card-link" %>

          <% end %>

<%= house.name %>

<%= house.length.to_f / 100 %> x <%= house.width.to_f.to_f / 100 %> m

            <% if house.price_present == false %>

<%= t('show.consult') %>

            <% else %>

<%= humanized_money_with_symbol(house.original_price) %> - 15% = <%= humanized_money_with_symbol(house.price) %>

              <% end %>

            <% if policy(house).update? %>
              <%= link_to "Edit", edit_house_path(house) %>
            <% end %>
            <% if policy(house).destroy? %>
              <%= link_to "Remove", house_path(house), method: :delete, data: { confirm: "Are you sure?" } %>
            <% end %>

      <% end %>

  <%= render "last-banner" %>
<% end %>

As you can see, there's a lot of duplication of code (not very DRY) and so I'd like a little help in getting more DRY and have the houses be ordered by category_id and then by price.
I'd appreciate your help.

A: It's not clear to me what you tried so far, but if all you need is to sort by category_id, I think you can define a scope within your house model as follow:
scope :sort_by_category_id_asc, ->{
    order(arel_table[:category_id].asc)
  }

Then you can use that scope as follow: House.where(...).sort_by_category_id_asc, also you can use desc, depends on how you want to order the result.
Hope this helps!

A: I created a method that can sort houses by its category_id. If you want to sort it by other things just change category_id to your desired thing. You can sort it ascending or descending order. Here it is:
def sort_by_category_id(houses, order)
  case order_by
    when "asc"
      houses = houses.sort_by{ |house|
        house[:category_id]
      }

    when "desc"
      house= house.sort_by{ |house|
        house[:category_id]
      }.reverse!
  end
  house
end

Don't forget to call this method wherever you want it to be worked. Below code will sort your houses by category_id and save it in sorted_houses variable. I
sorted_houses_asc = sort_by_category_id(@houses, "asc")
sorted_houses_desc = sort_by_category_id(@houses, "desc")

Hope this helped you somehow.


text:
Q: Getting TypeError: unsupported operand type(s) for %: 'NoneType' and 'float' with a print statement I am getting a TypeError for the following code:
print ("Intercept = %f") % (intercept)
print ("Slope = %f") % (gradient)

The error message is

unsupported operand type(s) for %: 'NoneType' and 'float'.

How do I fix this?

A: You used the Python 2 syntax of print in Python 3. In effect, you're applying the % operator to the result of print(...) instead of its argument.
Use this instead:
print(("Intercept = %f") % (intercept))
print(("Slope = %f") % (gradient))


text:
Q: How do I position a div relative to the mouse pointer using jQuery? Suppose I have one link in my page and I want that when I place my mouse just over the link, a div will show there according to mouse x,y.
How can I accomplish this using jQuery?

A: var mouseX;
var mouseY;
$(document).mousemove( function(e) {
   mouseX = e.pageX;
   mouseY = e.pageY;
});
$(".classForHoverEffect").mouseover(function(){
  $('#DivToShow').css({'top':mouseY,'left':mouseX}).fadeIn('slow');
});

the function above will make the DIV appear over the link wherever that may be on the page. It will fade in slowly when the link is hovered. You could also use .hover() instead. From there the DIV will stay, so if you would like the DIV to disappear when the mouse moves away, then,
$(".classForHoverEffect").mouseout(function(){
  $('#DivToShow').fadeOut('slow');
});

If you DIV is already positioned, you can simply use
$('.classForHoverEffect').hover(function(){
  $('#DivToShow').fadeIn('slow');
});

Also, keep in mind, your DIV style needs to be set to display:none; in order for it to fadeIn or show.

A: You don not need to create a $(document).mousemove( function(e) {}) to handle mouse x,y. Get the event in the $.hover function and from there it is possible to get x and y positions of the mouse. See the code below:
$('foo').hover(function(e){
    var pos = [e.pageX-150,e.pageY];
    $('foo1').dialog( "option", "position", pos );
    $('foo1').dialog('open');
},function(){
    $('foo1').dialog('close');
});

A: There are plenty of examples of using JQuery to retrieve the mouse coordinates, but none fixed my issue.
The Body of my webpage is 1000 pixels wide, and I centre it in the middle of the user's browser window.
body {
    position:absolute;
    width:1000px;
    left: 50%;
    margin-left:-500px;
}

Now, in my JavaScript code, when the user right-clicked on my page, I wanted a div to appear at the mouse position.
Problem is, just using e.pageX value wasn't quite right.  It'd work fine if I resized my browser window to be about 1000 pixels wide.  Then, the pop div would appear at the correct position.
But if increased the size of my browser window to, say, 1200 pixels wide, then the div would appear about 100 pixels to the right of where the user had clicked.
The solution is to combine e.pageX with the bounding rectangle of the body element.  When the user changes the size of their browser window, the "left" value of body element changes, and we need to take this into account:
// Temporary variables to hold the mouse x and y position
var tempX = 0;
var tempY = 0;

jQuery(document).ready(function () {
    $(document).mousemove(function (e) {
        var bodyOffsets = document.body.getBoundingClientRect();
        tempX = e.pageX - bodyOffsets.left;
        tempY = e.pageY;
    });
})

Phew.  That took me a while to fix !  I hope this is useful to other developers !

A:

[show on mouseover, hide on mouseout]

  Content goes here.


text:
Q: how to format date dd-MMM-yyy in laravel? Hi I would like to ask you a question I would like to format date "01-Sep-2017" in laravel the below is my code.
$toDate = Carbon::now()->format('dd-MMM-yyyy');

A: Try this.
$toDate = date('d-M-y', strtotime("01-Sep-2017"));

From the stackoverflow answer below


text:
Q: I am getting two errors in my socket.io when I am connecting it to my client side Javascript I am getting two errors:

*

*connection refused

*io is not defined.

const io = require("socket.io")(8000);

This is how I expose Socket.io for JavaScript:
<script src="http://localhost:8000/socket.io/socket.io.js"></script>

On my client-side JavaScript, I inserted Socket.io.
const socket = io('http://localhost:8000');

I tried even this way.
const socket = io.connect('http://localhost:8000/');

But the problem was still there.
This is my server side code.
const io = require('socket.io')(8000);
const users = {};
io.on('connection',socket=>{
    socket.on('new-user-joined',name=>{
        users[socket.id] = name;
        socket.broadcast.emit('user-joined',name)
    })
    socket.on('send',message=>{
        socket.broadcast.emit('recieve',message:message,name:users[socket.id]})
    })
})
socket.on('disconnect',()=>{
    socket.broadcast.emit('left',users[socket.id])
    delete users[socket.id]
})

I even changed my port number 8080 but this also not helped me. I switched back to port 8000. I was not getting any solution.I left those errors and start writing my script and after some time those errors was gone I don't know how? After some time I faced that errors again. And again after some time those errors was gone and this happens to me for 3 to 4 times.

A: For io is not defined issue,
Add this below CDNs :
<script src="https://cdn.socket.io/socket.io-1.0.0.js"></script>
<script src="http://localhost:8000/socket.io/socket.io.js"></script>

Keeping the localhost link below is a better choice.
and
socket.on('disconnect' event should be inside the io.on('connection' event.


text:
Q: i want to read a text file again and again for a specified time interval in jQuery/javascript unless a condition is satisfied After a lot of digging i came up with using $.get() method and implemented it as follow -
var id = setInterval(frame, 1000);
    function frame()
        {
            if (progressBar.dataset.size == 100)
            {
                clearInterval(id);
            }
            else {
                $.get('Progress1.txt', function (data1) {
                    progressBar.dataset.size = data1;
                    foreground.style.width = data1 + '%';
                    foreground.className += ' ' + newClass;
                    progressPercent.innerHTML = data1 + '%';

                });
            }

        }

e.g if the text file content is 40 then i have to set the width of my progress bar as 40%. The value of text file keeps changing dynamically in my backend(C#). so i have to keep checking it until the content of text file reaches 100 in frontend(jQuery/JavaScript).
Now, the page runs fine for the first time. But when i try to change the content of text file manually it is not reflected in my progress bar. Moreover after running it again for second time i get the same content that i used first time in my text file.

A: Thanks for the above suggestions. But i figured out that I have to abort the file after the end of loop using-
 $.get('Progress1.txt').abort();

So that everytime the loop starts it loads the server file again rather than using the old copy which was in the case when we did not used abort().


text:
Q: Password Validation Using mysql and php
Is there any reason / value when checking a password to query the database using the user name and password (after sanitizing, of course) and recording a failed attempt when no rows are returned vs querying the database using the user name and then comparing the return password string?
EDIT: To those who mentioned it below, yes the password is hashed up in the database.

A: If I'm understanding you correctly, you're wondering if there's a difference between comparing the results of:
$results = mysql_query("SELECT name FROM users WHERE name = $properlyEscapedName AND pass = $properlyEscapedPassword");
if (mysql_num_rows($result) == 1)
    $authenticated = true;

versus
$results = mysql_query("SELECT name, pass FROM users WHERE name = $properlyEscapedName");
$array = mysql_fetch_assoc($results);
if ($array["pass"] == $unescapedPass)
    $authenticated = true;

I would note that it's better to store password hashes than plaintext passwords for security reasons, but otherwise the only difference I see is that in the first case you will return one less field, which may mean more efficient use of bandwidth between your server and the database.  On the other hand, your query is several bytes larger, so that probably mitigates the small benefit of the smaller result set.

A: I see 2 questions here.

*

*The general way to check any info against database is to make database to do it. So, put both login and password into query. Especially if we store a hash, not a password itself

*Password guessing protection is valuable addition to the any authorization system.

A: You have a trade-off between information given to the user and protection against attacks.
If you query your database checking for corresponding login and password and it fails, you can only tell the user that either the login or the password is erroneous. Not helping if he does not remember which login you used to register (was it "Arkh01", "arkh" or "Arkh1").
If you query your database for the login, getting the hash and salt you can tell the user if the login is wrong or the password. The user is happy. But someone attacking your website can learn easily that the user "aa" does not exists, but the user "ab" does. As lot of websites give access to a userlist, you can almost always dismiss this concern.
To prevent bruteforce, log the number of attempts made by an IP or on a login and block any further attempt after 5ish errors. Preferably block the IP used, not the account.
About storing hashed passwords, use salts and hmac + sha512 in php : hash_hmac

A: There's basically no difference between the two methods. Both methods will let you know if the password doesn't match the name.

A: The more work you do / the longer you hold open a connection after a failed login attempt, the more you you leave yourself open to a DOS attack. OTOH you need to balance this against preventing brute force searches.
A smarter solution is to push the number of failed attempts client side in an encrypted cookie (drop the cookie before the user gets to the login page - if they try to post a username and password without a cookie - fail it automaticaly - with a message that cookies must be enabled). Increment the failures and re-encrypt to drop a new cookie if the login fails, after 3 consecutive failures fail any attempt.
It doesn't completely prevent brute force attacks but makes them a lot more difficult.
C.


text:
Q: Unexpected behavior when using JAXB to marshal a Map into a JSON Object I Have a Map object using the HashMap Implementation and Jersey's Jackson provider. When I try to convert the map I get the following output:
{"entry":{"key":"192.168.2.184","value":{"ip":"192.168.2.184","value":1.93,"lastReceivedMillis":1391419392506}},

"entry":{"key":192.168.2.186,"value":{"ip":"192.168.2.186","value":0.79,"lastReceivedMillis":1391419395874}}}

As you can see, the second entry has a key that is not enclosed inside quotes as the first entry's key and my json validator throws an error.

A: I would first double-check that you are using Jackson provider. There shouldn't be a way to produce invalid JSON via data-binding, which makes me suspect that you might be using one of alternate providers (Jettison based, or so-called "natural" json).


text:
Q: Equivalence of statements about a linear map I need someone to help me solve the following exercise:

Let $(X, \|\cdot\|_X)$ and $(Y, \|\cdot\|_Y)$ be normed vector spaces over a common field $\mathbb K$ $(\mathbb R$ or $\mathbb C)$. For a linear map $A: X\to Y$, show that the following statements are equivalent:

a) $A$ is continuous
b) There is a $\xi \in X$, such that $A$ is continuous in $\xi$
c) $A$ is Lipschitz-continuous
Of course you have to use the properties of $A$ being a linear map, but I can't really see what I am supposed to do. Maybe someone can give me the solution.
Can someone help? Still didn't find a solution.

A: Hints:
$$(x_n\to\xi\implies A(x_n)\to A(\xi))\implies(x_n\to x \implies A(x_n) = A(x_n-x+\xi+x-\xi) = A(x_n-x+\xi) + A(x-\xi)\to\cdots)$$
$A$ bounded in a neighbourhood of zero implies $A$ continuous in zero.


text:
Q: Count function in HQL causing null results? I have the following HQL query that is attempting to return 2 object instances as well as an aggregate count based upon a 3rd object instance.
SELECT
    client,
    clientCampaign,
    count( formData )
FROM
    FormData as formData
    JOIN formData.deliveryResults as deliveryResults
    JOIN formData.leadForm as leadForm
    JOIN leadForm.campaignForms as campaignForms
    JOIN campaignForms.clientCampaignForms.clientCampaign as clientCampaign
    JOIN clientCampaign.client as client
WHERE
    client.id = ?
GROUP BY
    client.id, clientCampaign.id

The results always return with the clientCampaign instance being null.  However, if I remove the count( formData ) line from the SELECT clause, the clientCampaign instance is no longer null.  I have checked the data set and there are 5 total formData records ... 3 for one clientCampaign and 2 for another.  So, I believe this query should be returning 2 results, both with non-null clientCampaign instances.
Can anybody tell if there is something obvious I am missing here?
TIA

A: *

*Can you post your object mappings? It's hard to say without them but it feels (judging by names) that you're walking up the hierarchy (from collection to owner) instead of down, which is somewhat unnatural using Hibernate.

*JOIN formData.deliveryResults as deliveryResults is unnecessary (it's not used anywhere). Most other joins may be unnecessary as well - for "to-one" associations you can write properties using nested dot notation without explicit joins.

*Your GROUP BY clause only lists IDs whereas you're selecting full entities (client and clientCampaign). That's not going to work - you have to explicitly list fields to group by.
Depending on your mappings, you may be able to rewrite this query using parent-to-child joins; you may than be able to use size() function on your deliveryResults collection without need for GROUP BY.

A: Before other comment, I like the way you present your HQL request at first, with each JOIN on its own line. It is very readable. I suggest you refactor the clientCampaign the same way, even if you don't use the aliases...  This might also change some results (who knows what code could be triggered in the inners of Hibernate with your original request !?).
You request seem to move between tables going up and down (judging from names, if they end with an 's' or not). It is a bit hard to read. I would probably be easier for you and for us to switch to a single order (for example going down, starting from leadForm). In particular, we would detect other "joins" going up, and examine them more carefully (I'm suspicious at clientCampaignForms.clientCampaign...)


text:
Q: Get Foreign Key objects in the query I have two models.
The first one represents different Projects with a name, an ID and a description
The second one is for tracking which user is in which Project.
So my models look like this:
from django.contrib.auth.models import User

# Create your models here.
class Project(models.Model):

    id = models.AutoField(db_column = 'db_ID', primary_key = True)
    name = models.CharField(max_length=500, default = None)
    descriptor = models.CharField(max_length = 1000, null = True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = 'projects'

    def __str__(self):
        return self.name

class Userproject(models.Model):
    id = models.AutoField(db_column = 'db_ID', primary_key = True)
    user = models.ForeignKey(User, on_delete= models.SET_NULL, null = True)
    project = models.ForeignKey('Project', on_delete = models.SET_NULL, null = True)
    created_at = models.DateTimeField(auto_now_add=True, null=True)
    updated_at = models.DateTimeField(auto_now=True, null = True)

    class Meta:
        db_table = 'UserProjects'
    def __str__(self):
        return self.id

In the Userproject there there is only the UserID and the ProjectID, both are ForeignKeys to the other models.
When I get a GET-Request with a username, I can get the userID , then I can filter all the Userprojects by the userID and serialize all those where the given user is present. But How would I include the Project data as well If I want to send the name of the Project as well?

A: So you can run a query with power operators to filter data based on foreign object values.
user_projects = Userproject.objects.filter(user_id=user_id, project__name='yourproject')

Now to access project data from user_project you can use . operator.
if user_projects.exists():
    print(user_projects[0].user_id)
    print(user_projects[0].project.name)
    print(user_projects[0].project.descriptor)

To get values directly from the ORM, use .values().
user_projects = Userproject.objects.filter(user_id=user_id, project__name='yourproject').values('project__name', 'project__descriptor)

This will fetch only the columns you specify as parameters.


text:
Q: Does missing logout event in SQL Server trace mean connection leak? (originally asked this question on StackOverflow was told that this community is a right one).
I am investigating possibility of unreleased SQL Server database connections. I ran SQL Server Profiler and collected event traces. Typically after an executed SQL command, I see "Audit Logout" event and often exec sp_reset_connection that indicates that connection is reused for a new command.
However, I track some SPIDs and see that after some SQL command (e.g. INSERT), there are no more events for the given SPID. Does this mean that connection is not released, stays open and can not be reused?

A: Great question! To find out if the connection is still open right now, look in sys.sysprocesses:
SELECT * FROM sys.sysprocesses;

Generally, as long as they're not doing anything, open connections aren't a problem for SQL Server - it can handle tens of thousands. Connection pooling - keeping a connection open and ready for reuse - is fine, and doesn't consume that many resources on a SQL Server.
I'm generally more worried about sleeping sessions - someone who started a request minutes ago and didn't finish - and you can find those with Adam Machanic's free sp_WhoIsActive:
sp_WhoIsActive @ShowSleepingSpids = 1


text:
Q: How to iterate through a list and edit is content? var courses = _repository.GetAllCoursesDetailsByCourseId(id);
var result = (from s in courses select new {  id = s.Course_ID,  name=s.Course_Date}).Distinct().ToList();

Now what i want to do is to iterate through result and edit all of its "name" content . .
a rough idea is below :
foreach (var i in result)
{
     string[] temp = i.name.Split(',');
     string[] token = temp[0].Split(' ');
     string newtemp = token[1] + " " + temp[1];
     i.name = newtemp;
}

But this is not working. How can i edit the content in var result?

A: Try something like this:

foreach (var i in result)
{
 string temp = i.name.Split(',');
 string token = temp.Split(' ');
 string newtemp = token + " " + temp;
 i.name = newtemp;
 }

A: Anonymous objects are immutable, that's why you're getting the Readonly error message.
I suggest you look here for some more information: Why are the properties of anonymous types in C# read-only?

A: Anonymous type properties are readonly.
Build a function that does the name generation and then use it directly in the LINQ:
private string GenerateNewName(string name) {
    string temp = name.Split(',');
    string token = temp.Split(' ');
    return token + " " + temp;
}

var result = (from s in courses select new {  id = s.Course_ID,  name=GenerateNewName(s.Course_Date)}).Distinct().ToList();

A: This should fix your problem. (I didn't change your code, but you should be careful with your index, if you didn't found any ',' or ' ' you will throw an exception)
var result = (from s in courses select new {  id = s.Course_ID,  name= splitName(s.Course_Date) }).Distinct().ToList();

private string splitName(string value)
{
     string[] temp = i.name.Split(',');
     string[] token = temp[0].Split(' ');
     return (token[1] + " " + temp[1]);
}

A: When you use foreach ,whatever changes you do, the changes are in the temp var i, not in the actual list, try using the traditonal for or an iterator.

A: As @Muhammad said, you need another list with updated values. You can extend your list search through Where extension method on any list, then apply your changes like below,
var newResult = result.Where(q=> q.name == "ValueToUpdate").ToList().ForEach(i => i.name = "NewValue");


text:
Q: How can I print an integer number displaying 4 decimal digits? print(round(mas[i],4))

This only works with float numbers, not integers.

A: Format your number using format():
format(mas[i], '.4f')

This formats numbers (including integers) to 4 decimal places. See the Format Specification Mini-Language documentation.
Demo:
>>> print(format(16, '.4f'))
16.0000
>>> print(format(4.242422, '.4f'))
4.2424

If the number is part of a larger string, you can use the format specification in a str.format() format string, using placeholders:
'Your frobnar has been opfritzed to {:.4f} hafnavz'.format(mas[i])

A: To be complete, you can also use the printf style formating:
>>> '%0.4f' % 4
'4.0000'
>>> '%0.4f' % 4.56789
'4.5679'
>>> '%0.4f' % .1
'0.1000'

As stated in the documents, it can be quirky with tuples, but can also be faster.


text:
Q: Advantages of using Lightning Connect as opposed to APIs? As far as I can tell, the price for Lightning Connect is just shy of $50,000 per year. I'm just curious, in consideration of this cost, why would one be better served using Lightning Connect as opposed to the various APIs provided by Salesforce?

A: I am not sure on pricing, but what I can confirm is that Lightning Connect follows OData Protocol and it is getting better with each release.

*

*Big players like Microsoft, SAP are supporting this out of box.

*Data is not saved in SFDC so you will save cost on space .

*Data will be always realtime.

*You dont need any developement effort to connect SFDC with external applications, Even business users or Admins can use point and click to integrate.

*If you have ligtning connect license, you can connect to external system anytime without any code.

If we choose custom developement over ligtning connect, It may cost sometime more and any change will need developement, you may need consider cost of ETL tool as well if go with developement.


text:
Q: Proof $ \cosh x=1 \Leftrightarrow x=0 $ I just calculated the function value in $x=0$. Is that ok? If not, what am I suppose to do then?

A: Showing that $\cosh 0=1$ is one direction of the $\iff$ arrow. The other direction amounts to showing this:

No other real number $x$ has $\cosh x=1$.

There are several approaches to solve this, most conventionally through derivatives or the geometric definition of $\cosh$.

A: Hint
To prove $$\cosh x=1\iff x=0$$ is like to prove$$\exp x=1\iff x=0$$

A: It seems that you have proved that$$x=0\implies\cosh(x)=1.$$It remains to prove that$$\cosh(x)=1\implies x=0.$$In order to do that, use the fact that\begin{align}\cosh(x)=1&\iff e^x+e^{-x}=2\\&\iff e^{-x}(e^x-1)^2=0.\end{align}

A: No, that's not enough. I suggest the AM-GM inequality. since $\cosh x$ is the arithmetic mean of $e^{\pm x}$, whose geometric mean is $1$, it's $\ge1$ with equality iff $e^x=e^{-x}$, which is equivalent to $e^x=1$, or to $x=0$.


text:
Q: adding big and dynamic org chart in gwt I need to add to my GWT site a dynamic org chart which:

*

*List item

*can handle large number of nodes.

*can be changed dynamically, e.g. selecting a specific node will draw it's children in case they were hidden. (preferably without redrawing the whole graph)

*a small orientation window would be great.

*nodes have to be clickable.

I'm now using OrgChart and I have many problems with it, e.g. in Explorer it shows maximum ~100 nodes (because of the table column limitation in tables). When I add a node, I need to refresh the whole chart causing the user to lose orientation and some more.
What should I use to be able to create it?


text:
Q: Full Height, fluid 100% width and height, 2 column Bootstrap 3 layout with header I am trying to replicate a desktop application layout that my client wants. I need help with space between divs and the min-height of tables. I have zero experience with customizing bootstrap so if I have done this the wrong way please share how it should be done. I tried to setup a plunker but i can't get it to work?
plunker

                            Master

Customer

                            New

Job

                        ll

No	Name

                                {{currentItem.JobNumber}}
                                {{currentItem.JobName}}

Home

Change Order

Purchase Order

Here is what the client wants

Here is what I have so far

Update
.my-container {
position: absolute;
top: 0;
bottom: 0;
}

A: There's no design pattern like that in Bootstrap. I have something that may work.
DEMO: http://jsbin.com/lopej
Look at the code: http://jsbin.com/lopej/edit?html,css,js
jQuery:
$(window).on('load resize', function() {

    var navbarht = $('.navbar').outerHeight();

 function columnHeight() {
     // Column heights should equal the document height minus the header height
     var newHeight = $(document).height() - (navbarht) -20 + "px";
   console.log($(window).height(), (navbarht));
     $(".primary-col").css("height", newHeight);
     $(".secondary-col").css("height", newHeight);
 }

 columnHeight();

 });

CSS:
html,
body {
    background: #777
}
.site-main.row {
    margin: 0
}
.header {
    background: #C5E0DC
}
.primary-col,.secondary-col {
    background-color: #ddd;
    padding:10px;
}
.navbar {
    margin: 0 0 10px 0
}
.inner {
  min-height:100%;
  background:#fff;
  border:1px solid #ccc;
}

/* needed to override jQuery */
@media (max-width:767px) {
    .primary-col,
    .secondary-col {
        height: auto!important
    }
    .site-main {
        padding-bottom: 0px!important
    }
}

/* larger viewport layout */
@media (min-width:768px) {
    html,
    body {
        height: 100%;
        width: 100%;
    }
    #page {
        height: 100%;
        height: auto !important;
        min-height: 100%;
    }
    .site-main {
        height: 100%;
        padding:0 10px;
    }
    .secondary-col {
        border-right: 10px solid #777
    }
}

HTML:

              <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
              Toggle navigation

              </button>
              Project name

Home

About

Contact

                    Dropdown

Action

Another action

Something else here

Nav header

Separated link

One more separated link

Default

Static top

secondary

primary

A: In terms of the height issue try
.my-container {
    position: absolute;
    top: 0;
    bottom: 0;
}


text:
Q: Add 3D models to JavaFX group In javaFX I can create rectangle/circles... and other 2D geometric figures.
In the Group i can add them with:
group.getChildren().add("Name");

Also I can check collision:
hero = character.localToScene(character.getBoundsInLocal());
yewTree = yew.localToScene( yew.getBoundsInLocal());

                if ( yewTree.intersects(hero) )
                {

                }

... and perform action if it happens.
There is another amazing thing:
AnimationTimer and TranslateTransition. It not only lets me to do periodic/continous animation, but also it checks some states.
( I can make few game loops without making major game loop, as they works independend. )
AND THE QUESTION COMES.

Can I add 3d models ( stl, obj, 3ds...) to the group and manimulate them ( scaling, changing coordinates, check collision, use them as a node in animation timer or Translatetransition )?
Im not sure about http://www.interactivemesh.org/
. I expect there is some kind of alternative, as it is confusing, lack of documentation, few examples on the Internet I found - do not works.


text:
Q: Как создать массив вещественных чисел с рандомными значениями при помощь итераторов Чтобы создать массив случайных вещественных значений в Ruby  можно использовать циклы. И тогда код будет выглядеть примерно так:
n = 10
a = []
rnd = Random.new
index = 0
while index < n
    p a[index] = rnd.rand(-10.99..10.99)
    index += 1
end

Не могу разобраться, как достичь подобного результата при помощи итераторов.

A: Попробуй так:
a = 10.times.map{ Random.rand(-10.99..10.99) }

В a будет нужный массив.

A: Array(10){ rand(-10.99..10.99) }

A: arr = Array.new(5) {Array.new(4, rand(1..5))}


text:
Q: Selenium Grid: install chrome extensions on session I need to use one chrome extension from Chrome Store in my test on Selenium Grid in Chrome browser, but I have some troubles :(

*

*I tried to go to extension URL in browser (https://chrome.google.com/webstore/detail/...) and press key Install, but I can't confirm install in popup browser window

*I tried to download crx extension file, but then i open it in browser I saw confirm windows and do not understand how to confirm installation

*I tried to use this method - https://developer.chrome.com/extensions/external_extensions add JSON file and run browser - don't work, but I try it on Mac, not Linux

*webdriver.remote can use only FireFox options (seleniumhq.github.io/selenium/docs/api/py/webdriver_remote/selenium.webdriver.remote.webdriver.html)

If I use Selenium Grid I can't change Chrome browser start settings, can't add any keys :(
Maybe you know another method to install the extension on Selenium Grid browser session?

A: You can use ChromeOptions.
ChromeOptions options = new ChromeOptions();
options.addExtensions(new File("/path/to/extension.crx"));
ChromeDriver driver = new ChromeDriver(options);

Alternatively, you can add the options to an already existing DesiredCapabilities object.
// Add ChromeDriver-specific capabilities through ChromeOptions.
ChromeOptions options = new ChromeOptions();
options.addExtensions(new File("/path/to/extension.crx"));
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
ChromeDriver driver = new ChromeDriver(capabilities);

You could also use a remote web driver:
DesiredCapabilities capability = DesiredCapabilities.chrome();
// above code goes here...
WebDriver driver = new RemoteWebDriver(new URL(hubUrl), capability);


text:
Q: Silverstripe Unit Tests modify live database (postgres module) I have a site that was version 3.1.12 and using postgres module version 0.92.
I just upgraded everything to 3.5.3 and 1.2 respectively. All is well except some odd behaviour from my existing and unchanged unit tests. Seems to happen when the tests create objects programatically, like so:
$page=new Page();
$page->Title='Read only success';
$page->write();

On 3.1 and 0.92, the test would run and then return a success. Doing the above work in a tmp database.
After the upgrade the same test, without any modification, runs and returns a success. Only this time, the work is done in the current live database. In the above case, there is a new draft page in my admin site tree.
Anyone seen this before? I've exhausted my hunt for answers and ability to track what exactly is causing this ver dangerous behaviour.

A: If you don't use a fixture file for your test, you need to ensure you tell SapphireTest to use a test database:
protected $usesDatabase = true;

Otherwise creating DataObjects like that will write directly to your main database.
If you're using a fixture file this is implied anyway, so is only necessary when you're not.
Here's the doc block, for reference.


text:
Q: getAllByRole - TestingLibraryElementError: Unable to find an accessible element with the role "option" I am trying to learn how to unit test, and my first test is trying to test a selector dropdown menu. I am using react jest to test.
When I try to access the options in the selector I get this error: TestingLibraryElementError: Unable to find an accessible element with the role "option"
Error in terminal
My selector looks like this
export function Selector({ data, name, defaultVal, labelStyle, ...rest }) {

    return (
        <>
            <label htmlFor={name} style={labelStyle}>{name}</label>
            <Select id={name} defaultValue={defaultVal} {...rest} >
                {data && data.map(n => <Option role="option" key={n} value={n}>{n}</Option>)}
            </Select>
        </>
    )
}

My test file looks like this:
import Selectors, { Selector } from "./Selectors";
import renderer from "react-test-renderer";
import store from "../../redux/store";
import {
  render,
  cleanup,
  fireEvent,
  getAllByRole,
  screen
} from "@testing-library/react";
import { Provider } from "react-redux";
import "@testing-library/jest-dom/extend-expect";

afterEach(cleanup);

const options = [
  {
      key: 'All Namespaces',
      value: 'All Namespaces',
  },
  {
      key: 'Production',
      value: 'Production',
  },
  {
      key: 'Default',
      value: 'Default',
  },
];

const MySelector = () => (
  <Selector
      data-testid="selector"
      data={options}
      defaultVal={options[0].value}
  />
);

it("can change the value of the Selector dropdown", () => {
  const { getByTestId } = render(<MySelector />);
  const selector = getByTestId('selector');
  const display = selector.children[0];

  expect(screen.getAllByRole('option').length).toBe(options.length);

  expect(display.textContent).toBe(options[0].text);

  console.log(display.textContent);

  fireEvent.click(selector);

  expect(screen.getAllByRole('option').length).toBe(3)

  const selectorOptions = getAllByRole(selector, 'option');

  fireEvent.click(selectorOptions[2]);

  expect(display.textContent).toBe(options[2].text);

  console.log(display.textContent);
});

Hopefully someone can help me with this, thank you!

A: It was not possible to add the role tag to the third party component since the source code has removed it for optimalization.


text: Q: How to tune the performance of ROCm(llvm) compiler? I modified llvm (roc-1.6.x) a bit to generate a code that can run on AMDGPU pro dirver. It can run but the performance is over 10% slower than AMDGPU's online compiler, for the same opencl code.  I wonder if there is some flags I can set to tune up llvm. If you can give me some examples it will be great.


text:
Q: Angular 11: inject service into a passed function Let's say i have model class:
export class Model {
  id: number;
  editAction?: () => any;
}

then some component creates array of those object with defined function
  someArray: Model[];

  constructor(private readonly injectedService: InjectedService) {}

  private createObjects(): void {
    this.someApiService.getData().subscribe((data) => {
    this.someArray = data.map(x =>
      ({id: x.id, editAction: someEditAction})
    );
  }

  private someEditAction(): void {
    this.injectedService
      .open(/* ... */)
  }

then another one component, which has got someArray by an @Input() tries to invoke editAction for every element in HTML (it is all working properly):
Template:
<div *ngFor="let item of someArray">
  <button (click)="item.editAction()">
</div>

Component:
@Input() someArray: Model[];

The problem is that after we click this button, the function "someEditAction" is actually invoked, but it does not have dependencies from it's first component and it throws error that injectedService is null. Is there any way to inject this service into that function? InjectedService is of course decorated with providedIn: 'root' as usual. I tried to build factoryProvider, but I think i did it wrong

A: Instead of this:
({id: x.id, editAction: someEditAction})
Write this:
({id: x.id, editAction: () => this.someEditAction()})
This will maintain the proper this.
EDIT: Having said that, a design change in the spirit of @DeborahK's comment above should be considered.


text:
Q: why done runs earlier before supertest request on sequelize? const request = require('supertest');
const app = require('../app');

    request(app)
        .get("/videos")
        .expect(200)
        .end(async (err,res) => {
            if (err) {
                console.error(err);
                done();
            } else {
                console.log(res.body);
                done(); // <- this is the question line
            }

If I take off the done from the code, the test will print the result, but if I have done there, sequelize still print but there is no res.body print on the console.
Anyone knows why?

A: I think it's because of the asynchronous nature of javascript.
By default, Jest tests complete once they reach the end of their execution. That means this test will not work as intended:
const request = require('supertest');
const app = require('../app');

    request(app)
        .get("/videos")
        .expect(200)
        .end(async (err,res) => {
            if (err) {
                console.error(err);
                // done();
            } else {
                console.log(res.body);
                // done();
            }

The problem is that the test will complete as soon as function completes asynchronosly.
Moving to, after putting done()
const request = require('supertest');
const app = require('../app');

    request(app)
        .get("/videos")
        .expect(200)
        .end(async (err,res) => {
            if (err) {
                console.error(err);
                done();
            } else {
                console.log(res.body);
                done();
            }

And then, in that case, it waits for the done function before finishing the test.
For more details. Please check here.
I hope it helps. Thanks

A: Try to remove async from .end(async (err,res) => { line so the callback is not considered asynchronous anymore.


text:
Q: How to get 0-padded binary representation of an integer in R language How to Generate a function in R that translates integers into a binary vector for length K, for example, if I have integer n=3 and length is K= 7
the output is 0000011?
I generate this function but I don't know how to get 0-padded binary representation :
convert_to_b <- function(n)
{
  if(n > 1) {
  convert_to_b(as.integer(n/2))
  }
  cat(n %% 2)
 }

A: The R.utils package has the function intToBin() that can be combined with sprintf() to left pad the result.
convert_to_b <- function(n, K)
{
  n <- R.utils::intToBin(n)
  if (K < nchar(n))
    K <- nchar(n)
  sprintf("%0*d", K, as.integer(n))
}

convert_to_b(3, 7)
[1] "0000011"

A: An option is to use intToBits:
convert_to_b <- function(n, K) {
    x <- head(substr(intToBits(n), 2L, 2L), K)
    paste(rev(x), collapse="")
}
convert_to_b(3, 7)
#[1] "0000011"


text:
Q: How to suppress EXC_BAD_ACCESS KERN_INVALID_ADDRESS 0x00000000915e3957 (Objective-C iOS) I got into a situation where the crash is in production app but not in debug application, so not able to reproduce the crash in debug application.I am getting the crash reports from Crashlytics
Here is the stack trace of the bug and it is something related to EXC_BAD_ACCESS KERN_INVALID_ADDRESS which is painful to debug as generally people say
Crashed: command_dispatch
EXC_BAD_ACCESS KERN_INVALID_ADDRESS 0x00000000915e3957
 Raw Text

#0  libobjc.A.dylib objc_msgSend + 5

#1  CoreFoundation  -[__NSArrayM removeAllObjects] + 182

#2  Almond  -[self removeObjectFromArray:]

Definition of removeObjectFromArray:
-(void)removeObjectFromArray:(NSMutableArray *)array{
   if(array!=nil && array.count>0){
      [array removeAllObjects];
    }
 }

The method removeObjectFromArray is called in the below method
-(void)cleanUp{
   [self removeObjectFromArray:self.array];
}

the parameter self.array is strong and atomic which are by default and property of this class(Let the name of this class be Main class).
The values to this property array is assigned in a method of another class as below
 -(void) fillData {
     NSMutableArray* array = [NSMutableArray new];
     //fillArray fills the array created and assigns the array to the array in MainClass
     [self fillArray:array];
     MainClass.array = array;
 }

The crash is inside the method removeObjectFromArray because of accessing memory that is already released which I have learnt from other posts, to avoid that I am having a nil check before sending message to the array.
Does not the object be nil if the memory is released or is the memory released after code execution passing the nil check or should I lock the array object before nil check and unlock the object after nil check, or the array that is created and assigned to the array of this class might have released, did I miss any case or any suggestions how to suppress this bug stopping the app from crashing is appreciable.


text:
Q: Spring boot integration with JBPM 7.23.0 I am new to the jBPM. I want to use the jBPM 7.23.0 with the Spring boot. As per my understanding there are two ways to integrate it.

*

*JBPM as a service

*jBPM project embedded in Spring boot application

I am trying to understand how to embed jBPM 7.23.0 with Spring boot.

*

*Do I need to create and build the jBPM project separately using either Business Central or Eclipse plugin and use the kjar in spring boot application ?
or

*Can I use the jBPM project files (like .BPNM , .drl etc files) directly in spring boot application and build the spring boot application directly?

I am reading the jBPM documentation from https://www.jbpm.org/
I also got few sample project links as well from document. I tried to install and run the sample project but its not helping to clear the integration concept.

A: I am working on a tutoral on this at Integrated jBPM and on github at business-application. It works with the jBPM starter applications from jBPM - Build your business application expanded to demonstrate more complete examples.

*

*original-business-application-kjar: A kjar project. The kjar project
holds the process flows, business rules, optimization and other
information needed to implement and run in the jBPM runtime engine.
The default starter kjar only has a default configuration files.

*original-business-application-model: A simple java project to be used
as an external data model for business processes. The default
contains an empty POJO at com.company.model.Model.

*original-business-application-service: The default springboot jBPM service.
The default server state is defined in business-application-service.xml in the project's root directory. This configuration file defines a deployed and running container with the same GAV value as the business-application-kjar. he will build as is out  of the box and installs with GAV of com.company:business-application-kjar:1.0-SNAPSHOT. The pom.xml that comes out of the box will cause issues with eclipse m2e. You can add entry to fix the warnings from m2e.
If you run the server it will initially fail with a java runtime exception java.lang.RuntimeException: Cannot find KieModule: com.company:business-application-kjar:1.0-SNAPSHOT. To fix this you must install the kjar into the local maven repository with mvn install from the kjar project.
Once the springboot jBPM service is started it is running on localhost port 8090. The jBPM REST endpoint can be found at http://localhost:8090/rest/server and is access restricted. The Authorization is configured in the DefaultWebSecurityConfig.java class of the project.

A: As I understand, you need confirmation for the first 3 questions and answer to the fourth one.
It seems the options are right for the first 3, and beside first 2 I would say you have more flexibility and options than just those 2.

Can I use the jBPM project files (like .BPNM , .drl etc files)
  directly in spring boot application and build the spring boot
  application directly?

You can do this in this ways: Your spring boot application have the kie-server.jar library. You then start a Deployment service, if you need the bpmn/drl files to be in a deployment or you can directly start a Runtime manager and a KieBase to which you then addResuorce bpmn and drl and then build. This will make those definitions ready to start and instance and execute.
I hope this is clear enough, or you can ask for further clarification


text:
Q: Derivation for average value input current in buck-boost converter I am struggling with the derivation of average value of input current as below.
The image is from the lecture here (page 26).
Here is what I got so far.
How did the lecture derive the final step here?
$$ \langle i_g(t)\rangle_{T_s}=\frac{1}{T_s} \int_{0}^{T_s} i_g(t) dt =\frac{1}{T_s} \int_{0}^{dT_s} \langle i(t)\rangle_{T_s}  dt = d(t)\langle i(t)\rangle_{T_s} $$

A: $$ \langle i_g(t)\rangle_{T_s}=\frac{1}{T_s} \int_{0}^{T_s} i_g(t) dt =\frac{1}{T_s} \int_{0}^{dT_s} \langle i(t)\rangle_{T_s}  dt = d(t)\langle i(t)\rangle_{T_s} $$
Lets consider i(t).  Taking the integral of i(t) with respect to t will result in ti(t).  I am assuming also Ts is a subscript in this derivation.  The steps missing would be the following:
$$ \frac{dT_s}{T_s}i(t)_{Ts} - \frac{0}{T_s}i(t)_{Ts} = d(t)i(t)_{Ts} $$
d(t) needs to be taken with respect to t which is why it appears in the final derivation.  The computation of the integral is really the only step missing in this case.


text:
Q: how to extract numeric values from input string in java How can I extract only the numeric values from the input string?
For example, the input string may be like this:
String str="abc d 1234567890pqr 54897";

I want the numeric values only i.e, "1234567890" and "54897". All the alphabetic and special characters will be discarded.

A: Split your string into char array using yourString.toCharArray(); Then iterate through the characters and use Character.isDigit(ch); to identify if this is the numeric value. Or iterate through whole string and use str.charAt(i). For e.g:
public static void main(String[] args) {
    String str = "abc d 1234567890pqr 54897";
    StringBuilder myNumbers = new StringBuilder();
    for (int i = 0; i < str.length(); i++) {
        if (Character.isDigit(str.charAt(i))) {
            myNumbers.append(str.charAt(i));
            System.out.println(str.charAt(i) + " is a digit.");
        } else {
            System.out.println(str.charAt(i) + " not a digit.");
        }
    }
    System.out.println("Your numbers: " + myNumbers.toString());
}

A: You could do something like:
Matcher m = Pattern.compile("\\d+").matcher(str);
while (m.find()) {
   System.out.println(m.group(0));
}

A: You could use the .nextInt() method from the Scanner class:

Scans the next token of the input as an int.

Alternatively, you could also do something like so:
String str=" abc d 1234567890pqr 54897";

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

A: You can use str = str.replaceAll("replaced_string","replacing_string");
String str=" abc d 1234567890pqr 54897";
String str_rep1=" abc d ";
String str_rep2="pqr ";
String result1=str.replaceAll("", str_rep1);
String result2=str.replaceAll(",",str_rep2);

also what npinti suggests is fine to work with.

A: Example using java Scanner class
import java.util.Scanner;

Scanner s = new Scanner( "abc d 1234567890pqr 54897" );
s.useDelimiter( "\\D+" );
while ( s.hasNextInt() ){
    s.nextInt(); // get int
}

A: If you do not want to use regex,
String str = " abc d 1234567890pqr 54897";

char[] chars = new char[str.length()];

int i = 0;
for (int j = 0; j < str.length(); j++) {
    char c = str.charAt(j);
    if (Character.isDigit(c)) {
        chars[i++] = c;
        if (j != chars.length - 1)
            continue;
    }
    if (chars[0] == '\0')
        continue;
    String num = new String(chars).trim();
    System.out.println(num);
    chars = new char[str.length()];
    i = 0;

}

Output :
1234567890
54897

A: You want to discard everything except digits and spaces:
String nums = input.replaceAll("[^0-9 ]", "").replaceAll(" +", " ").trim();

The extra calls clean up doubled and leading/trailing spaces.
If you need an array, add a split:
String[] nums = input.replaceAll("[^0-9 ]", "").trim().split(" +");

A:         String line = "This order was32354 placed 343434for 43411 QT ! OK?";
        String regex = "[^\\d]+";

        String[] str = line.split(regex);
        String required = "";
        for(String st: str){
            System.out.println(st);
        }

By above code you will get all the numeric values. then you can merge them or what ever you wanted to do with those numeric values.

A: String str=" abc d 1234567890pqr 54897";
Pattern pattern = Pattern.compile("\\w+([0-9]+)\\w+([0-9]+)");
Matcher matcher = pattern.matcher(str);
for(int i = 0 ; i < matcher.groupCount(); i++) {
  matcher.find();
  System.out.println(matcher.group());
}

A: You could split the string on spaces to get the individual entries, loop across them, and try to parse them with the relevant method on Integer, using a try/catch approach to handle the cases where parsing it is as a number fails. That is probably the most straight-forward approach.
Alternatively, you can construct a regex to match only the numbers and use that to find them all. This is probably far more performant for a big string. The regex will look something like `\b\d+\b'.
UPDATE: Or, if this isn't homework or similar (I sort of assumed you were looking for clues to implementing it yourself, but that might not have been valid), you could use the solution that @npinti gives. That's probably the approach you should take in production code.

A: public static List<String> extractNumbers(String string) {
    List<String> numbers = new LinkedList<String>();
    char[] array = string.toCharArray();
    Stack<Character> stack = new Stack<Character>();

    for (int i = 0; i < array.length; i++) {
        if (Character.isDigit(array[i])) {
            stack.push(array[i]);
        } else if (!stack.isEmpty()) {
            String number = getStackContent(stack);
            stack.clear();
            numbers.add(number);
        }
    }
    if(!stack.isEmpty()){
        String number = getStackContent(stack);
        numbers.add(number);
    }
    return numbers;
}

private static String getStackContent(Stack<Character> stack) {
    StringBuilder sb = new StringBuilder();
    Enumeration<Character> elements = stack.elements();
    while (elements.hasMoreElements()) {
        sb.append(elements.nextElement());
    }
    return sb.toString();
}

public static void main(String[] args) {
    String str = " abc d 1234567890pqr 54897";
    List<String> extractNumbers = extractNumbers(str);
    for (String number : extractNumbers) {
        System.out.println(number);
    }
}

A: Just extract the digits
String str=" abc d 1234567890pqr 54897";

for(int i=0; i<str.length(); i++)
    if( str.charAt(i) > 47 && str.charAt(i) < 58)
        System.out.print(str.charAt(i));

Another version
String str=" abc d 1234567890pqr 54897";
boolean flag = false;
for(int i=0; i<str.length(); i++)
    if( str.charAt(i) > 47 && str.charAt(i) < 58) {
        System.out.print(str.charAt(i));
        flag = true;
    } else {
        System.out.print( flag ? '\n' : "");
        flag = false;
    }

A: public class ExtractNum

{

  public static void main(String args[])

  {

   String input = "abc d 1234567890pqr 54897";

   String digits = input.replaceAll("[^0-9.]","");

   System.out.println("\nGiven Number is :"+digits);

  }

 }

A:  public static String convertBudgetStringToPriceInteger(String budget) {
    if (!AndroidUtils.isEmpty(budget) && !"0".equalsIgnoreCase(budget)) {
        double numbers = getNumericFromString(budget);
        if( budget.contains("Crore") ){
            numbers= numbers* 10000000;
        }else if(budget.contains("Lac")){
            numbers= numbers* 100000;
        }
        return removeTrailingZeroesFromDouble(numbers);
    }else{
        return "0";
    }
}

Get numeric value from alphanumeric string
 public static double getNumericFromString(String string){
    try {
        if(!AndroidUtils.isEmpty(string)){
            String commaRemovedString = string.replaceAll(",","");
            return Double.parseDouble(commaRemovedString.replaceAll("[A-z]+$", ""));
            /*return Double.parseDouble(string.replaceAll("[^[0-9]+[.[0-9]]*]", "").trim());*/

        }
    }catch (NumberFormatException e){
        e.printStackTrace();
    }
    return 0;
}

For eg . If i pass 1.5 lac or 15,0000 or 15 Crores then we can get numeric value from these fucntion . We can customize string according to our needs.
For eg. Result would be 150000 in case of 1.5 Lac

A: String str = "abc d 1234567890pqr 54897";
str = str.replaceAll("[^\\d ]", "");

The result will be "1234567890 54897".

A: String str = "abc34bfg 56tyu";

str = str.replaceAll("[^0-9]","");

output: 3456


text:
Q: How to get third category of woocommerce via category id I tried this code to show multi child category via woocommerce category id but getting error. Could you tell me what is wrong?
    $args = array(
        'hierarchical' => 1,
        'show_option_none' => '',
        'hide_empty' => 0,
        'parent' => $number = 66,
        'taxonomy' => 'product_cat'
    );
    $subcats = get_categories($args);
    echo '
';
        foreach ($subcats as $sc) {
            $link = get_term_link($sc->slug, $sc->taxonomy);
            echo '
' . $sc->name . '' . '
';
                $args2 = get_terms('product_cat',array(
                    'child_of' => $sc->term_id,
                    'hierarchical' => 1,
                    'hide_empty' => 1,
                ));
            }
    echo '
';
    echo '
';
            foreach ($args2 as $subsubCats) {
                $SubLinks = get_term_link($subsubCats->slug, $subsubCats->taxonomy);
                echo '
' . $subsubCats->name . '' .'
';
                }
    echo '
';
    wp_reset_query();

A: ok so now I got the problem from your code. As you want 2 levels of subcategories, you are writing 2 foreach loop which is correct but you need to add second foreach loop as nested loop of first foreach. I have done some change in your code to get 2 levels subcatecories and proper layout.
$args = array(
    'hierarchical' => 1,
    'show_option_none' => '',
    'hide_empty' => 0,
    'parent' => $number = 66,
    'taxonomy' => 'product_cat'
);
$subcats = get_categories($args);
echo '
';
echo '
';
foreach ($subcats as $sc) {
    $link = get_term_link($sc->slug, $sc->taxonomy);
    echo '
' . $sc->name . '';
        echo '
';
            $args2 = get_terms('product_cat', array(
                'child_of' => $sc->term_id,
                'hierarchical' => 1,
                'hide_empty' => 1
            ));
            echo '
';
                foreach ($args2 as $subsubCats) {
                    $SubLinks = get_term_link($subsubCats->slug, $subsubCats->taxonomy);
                    echo '
' . $subsubCats->name . '' . '
';
                }
            echo '
';
        echo '
';
    echo '
';
}
echo '
';
echo '
';

wp_reset_query();


text:
Q: centering components with css/html/angular Hi my project is located at
https://stackblitz.com/github/skwallace36/temprepo
I am trying to center the trees/and or the the two tree names at the top...
I am struggling to achieve this due to the crazy structure of the angular components and other wacky css/html which I'm not really too good at...
I don't think it would be helpful to post css/html snippets because I'm honestly not sure where I should try to achieve this, or if something I already have is preventing it...
I have tried all sorts of center, margin, etc solutions in so many different places.. I cannot find a solution
SOS and thank you very much for checking out my stack blitz

A: Add this to your style.scss file
.treebuttoncontainer {
  text-align: center;
}

.trees {
  justify-content: center;
}

DEMO


text:
Q: How to correctly close OutputStream? Below you find the constructor of a server in order to setup it. In a few words, it restore its state from the last time that it was up reading a List of objects (called log) and two int (called currentTerm and votedFor). Any time that any of these "volatile" fields will be updated, the relative file will have to be updated too (and so make upadate the consistent state), so I need the two ObjectOutPutStream called metadataWriter and logWriter. Since the server could go down in any moment, I cannot write any close() method. Do you think that the only possible solution in order to avoid an EOFException the next time that I setup the server (during the reading operation) is to flush() the output stream everytime (like I've done on the last lines of the code)?
   public ServerRMI(...)
    {
        ...
        log = new ArrayList<>();
        try {
            //if Log file exists then should exists Metadata too
            if(Files.exists(Paths.get("Server" + id + "Log"), LinkOption.NOFOLLOW_LINKS))
            {
                reader = new ObjectInputStream(new FileInputStream("Server"+id+"Log"));
                try
                {
                    while(true)
                        log.add((LogEntry) reader.readObject());
                }
                catch (EOFException e){}
                catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
                reader = new ObjectInputStream(new FileInputStream("Server"+id+"Metadata"));
                currentTerm = reader.readInt();
                votedFor = reader.readInt();
            }
            else//if it is the first time that the server is set up initialize all persistent fields
            {
                currentTerm = 1;
                votedFor = -1;
                log = new ArrayList<LogEntry>();
            }
            logWriter = new ObjectOutputStream(new FileOutputStream("Server"+id+"Log"));
            metadataWriter = new ObjectOutputStream(new FileOutputStream("Server" + id + "Metadata"));
            //since creating a new ObjectOutputStream overwrite the old file with the an empty one, as first thing we rewrite the old content
            for(LogEntry entry : log)
                logWriter.writeObject(entry);
            metadataWriter.writeInt(currentTerm);
            metadataWriter.writeInt(votedFor);
            metadataWriter.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        ...
    }

IMPORTANT NOTE:
I don't think that the try-with-resources in every method which use them (and so each method that update server's state) as someone have suggested is a feasible solution, since it would be ok for the metadata file (the two int written on it are always replaced at every update/write to file) but for the log file it would mean to write the whole list every time that it is changed (the operation made on it are not only appen, but replacement too!), which I think that it's not so good for performance!

A: I suggest you use try-with-resource and write the whole collection at once and you don't have to read until you get an exception. You can write meta data at the start.
List<LogEntry> entries = ..
try (ObjectOutputStream out = new ObjectOutputStream(....)) {
    out.writeObject(currentTerm);
    out.writeObject(votedeFor);
    out.writeObject(entries);
}

to read you can do
String currentTerm = "none";
String votedFor = "no-one";
List<LogEntry> entries = Collections.emptyList();
try (ObjectInputStream in = new ObjectInputStream(....)) {
    currentTerm = (String) in.readObject();
    votedFor = (String) in.readObject();
    entries = (List<LogEntry>) in.readObject();
}

Note: this needs Java 7, but given it's about to be EOL, I suggest upgrading to Java 8 if you can.

which I think that it's not so good for performance!

This is a very different question but you would still use try-with-resource.  A solution is to only append new entries.  To do this you need,

*

*a protocol on top of ObjectOutputStream which supports appending to a file. ObjectOutputStream won't do this for you, instead you need to write blocks of data and you need a means to sticking these together.

*a way to determine what has changed/added since the last write to disk and only write the changes to disk.

Befor eyou assume performance is bad, you should test it as you might find it is not worth the added complexity to save a few milli-second.
BTW if you really care about performance, don't use ObjectOutputStream, it is generic and flexible, but very slow.

so the OutpuStreamObject (which are class field, not constructor local variable) are not correctly closed.

In this case the file will be corrupted.  You need a means of validating the file and truncating invalid data.

Take a look at a library I wrote. Chronicle Queue It may solve many of your problems as it supports

*

*continuous writing from multiple threads, processes or machines.

*if a process or thread dies while writing it, the corrupted entry is truncated or ignored.

*if a process dies between writes, there is no loss of data.

*it support more efficient means of serialization.

*it can be read by multiple threads/processes while it is being written with micro-second latency.

*it can be replicated to multiple machines for distribution.

*entries can be randomly accesses by an index or by binary search.

A: The try-with-resources Statement

The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement.

Example
static String readFirstLineFromFile(String path) throws IOException {
    try (BufferedReader br =
                   new BufferedReader(new FileReader(path))) {
        return br.readLine();
    }
}


text:
Q: Can JavaScript call a PHP function directly, or do I need separate php file to call the function? I am doing some basic Ajax stuff (not jquery.. just learning the basics), and I have a general structure set up where html calls a javascript function which sends data to and runs a specific php page.
But what if I just need to run a php function that's already defined in functions.php. Is that possible at all?  I'm getting tired of making new php files for every task ;)

A: In the PHP script surround each function with a if statement designed to check a GET variable. Then in the JS send a GET variable specific to the one required to call that function.

A: You could define a class in php to handle stuff like this, such as:
functions.php:

class MyFunctions {
   function foo() {
      // code here
      // if you need to pass in some parameters, you can do it via jQuery and fetch the data like so (for the jQuery, see below)
      if($_GET['name'] == "john") { } // do stuff
   }

   function bar() {
      // code here
   }

   static function handleFn($fName) {
      if(method_exists(__CLASS__, $fname)) {
         echo $this->{$fname}(); die; // since AJAX, just echo the output and stop executing
      }
   }
}

if(!empty($_GET['f'])) {
   MyFunctions::handleFn($_GET['f']);
}

Then do your ajax call like so (assuming jQuery):
$.get("/functions.php?f=func_name_to_call", {name: "John", hobby: "Programming"}, function(data) {
});

A: ajax is also an http request, which cannot call php functions directly


text:
Q: ng-repeat with *conditional* ng-class by $index I'm applying a button to a list-group-item using ng-repeat where the button has a class btn-primary when not selected and a minus glyphico and a class btn-success when selected and an ok glyphicon. I'm trying to apply this conditionally using ng-class which is fine, but how to do it by $index selection I don't know. I've looked at examples using the ternary and logic ( && ) operators but can't seem to get the syntax right. To clarify I'd like one button when clicked to change it's icon and it's colour. As you can see I am successfully using the $index to select a group-item and change its colour no problem.
Here's a plunk
http://plnkr.co/edit/dPoHtL7MgFNX4FhDXoBH?p=preview
  <button class="btn btn-sm pull-right move-button" ng-class="{'btn-success': Activatorator, 'btn-primary': !Activatorator}" ng-click="markActive($event, this.$index)">

  </button>

***** Solution
I fixed this using the selected ng-repeat item as suggested. Since the regular 'class' on an html element sort of acts like the 'else' clause in an if/else I used that to evaluate the default state of the button, btn-primary with glyphicon-minus and ng-class to change the state on click by id.
Working plunker
http://plnkr.co/edit/0j9BxFQdD2lIx7lgthDR?p=preview

A: Forget using index and pass the active id to function :
ng-click="setSelected(id)"

$scope.selected ={ id: null}
$scope.setSelected = function(id) {
   $scope.selected.id = id;
}

$scope.selected is an object so that it will get inherited by the child scopes created in ng-repeat whereas a primitive won't
Then you can compare the id of ng-repeat to selected.id
ng-class="{'list-group-item-info': selected.id == id}"

A: Basically you need to create a method in scope which will give you the value of activated row.
Markup
<button class="btn btn-sm pull-right move-button" ng-class="{'btn-success': isActivate($index), 'btn-primary': !isActivate($index)}" ng-click="markActive($event, this.$index)">

</button>

Code
$scope.setSelected = function(idx) {
    $scope.indx = idx;
}

$scope.isActivate =function(idx){
    return $scope.indx == idx
}

Working Plunkr

Though playing with $index of ng-repeat is not an good idea to do, @JB Nizet already given answer for the other way which would be best way to implement it.

A: You're using a single scope variable to store the state of 6 different elements. That can't possibly work.
Forget about using the index. That's a bad idea. For example, as soon as you use an orderBy or filter filter, the index of a given element of the array will change. Same if you implement the remove() function; a given element will have its index modified, but you still want its state to be unchanged.
Instead, iterate over objects, and store the state of the object as an attribute of the object. When you click on a button, you change the state of the current object. As simple as that.
Here's a working version of your plunkr: http://plnkr.co/edit/GxI4AyeGBPTDKDFS8Zjf?p=preview
Key stuff:
  $scope.objectsFromServer = [{
    id: 1
  },
  {
    id: 2
  },
  {
    id: 3
  },
  {
    id: 4
  },
  {
    id: 5
  },
  {
    id: 6
  }];

  $scope.setSelected = function(object) {
    $scope.selectedObject = object
  }

  $scope.markActive = function(object, $event) {
    object.active = !object.active;
    $event.stopPropagation();
    $event.preventDefault();
  };

and

{{ object.id }}

      <button disabled="" class="btn btn-sm btn-danger pull-right move-button" ng-click="remove()">

      </button>

      <button class="btn btn-sm pull-right move-button" ng-class="{'btn-success': object.active, 'btn-primary': !object.active}" ng-click="markActive(object, $event)">

      </button>


text:
Q: Proving $\sqrt{2}x-\sqrt{x^{2}+1} \geq \frac{\sqrt{2}}{2}\ln{(x)}$ How can I prove that
$$
x\sqrt{2}-\sqrt{x^{2}+1} \geq \frac{\sqrt{2}}{2}\ln{(x)}
$$
It's a derivation-based process if I remember correctly, however I was unable to prove it correctly.

A: Let's get rid of $\sqrt{2}$ by rewriting the inequality as
$$
f(x)=2x-\sqrt{2(x^2+1)}-\ln x\ge0
$$
We have $\lim_{x\to0}f(x)=\infty$. For computing the limit at $\infty$, we do the substitution $t=1/x$, so the limit becomes
$$
\lim_{t\to0^+}\frac{2}{t}-\frac{\sqrt{2(t^2+1)}}{t}+\ln t=
\lim_{t\to0^+}\frac{2-\sqrt{2(t^2+1)}+t\ln t}{t}=\infty
$$
Thus we know that $f$ has at least a point of minimum.
Compute the derivative
$$
f'(x)=2-\frac{2x}{\sqrt{2(x^2+1)}}-\frac{1}{x}
=2-\frac{x\sqrt{2}}{\sqrt{x^2+1}}-\frac{1}{x}
$$
Let's go on:
$$
f''(x)=-\sqrt{2}\,\frac{\sqrt{x^2+1}-\dfrac{x^2}{\sqrt{x^2+1}}}{x^2+1}
+\frac{1}{x^2}
=-\sqrt{2}\,\frac{1}{(x^2+1)\sqrt{x^2+1}}+\frac{1}{x^2}
$$
and we want to evaluate the sign of
$$
(x^2+1)\sqrt{x^2+1}-x^2\sqrt{2}
$$
that is, where $(x^2+1)\sqrt{x^2+1}>x^2\sqrt{2}$. We can square getting
$$
x^6+3x^4+3x^2+1>2x^4
$$
that is
$$
x^6+x^4+3x^2+1>0
$$
which is of course true.
Therefore $f''(x)>0$ for all $x>0$ and so $f'(x)$ is increasing. Since $f'(1)=0$, $f'$ vanishes only at $1$, which is thus the unique minimum point for $f$.
Since $f(1)=0$, we see that $f(x)\ge0$ for all $x>0$ (equality only at $1$).

A: Let $f(x)=x\sqrt{2}-\sqrt{x^{2}+1} -\dfrac{\sqrt{2}}{2}\ln{(x)}$. Then, $$f'(x)=\sqrt{2}-\frac{x}{\sqrt{x^2+1}}-\frac{1}{x\sqrt{2}}=\frac{2x\sqrt{x^2+1}-x^2\sqrt{2}-\sqrt{x^2+1}}{x\sqrt{2(x^2+1)}}.$$
For $x>0$, the denominator is positive, so we just need to check the sign of the numerator: $$2x\sqrt{x^2+1}-x^2\sqrt{2}-\sqrt{x^2+1}\geq2\sqrt{2}-\sqrt{2}-\sqrt{2}=0  \;\;\text{ for } \; x\geq1.$$
Thus, $f(x)$ is an increasing function on $[1,\infty)$.
Since $f(1)=0$, it follows that $f(x) \geq 0$ for all $x \in [1,\infty)$. Hence, $$x\sqrt{2}-\sqrt{x^{2}+1} -\dfrac{\sqrt{2}}{2}\ln{(x)} \geq0 \implies x\sqrt{2}-\sqrt{x^{2}+1} \geq \frac{\sqrt{2}}{2}\ln{(x)}.$$

A: $$f(x):=x\sqrt{2}-\sqrt{x^2+1}-\frac{\sqrt{2}}{2}\ln x$$
Which is continuously differentiable on $(0,\infty)$
$$f'(x)=-\frac{x}{\sqrt{x^2+1}}-\frac{1}{\sqrt{2} x}+\sqrt{2}=\frac{-2 x^2+2 \sqrt{2} \sqrt{x^2+1} x-\sqrt{2} \sqrt{x^2+1}}{2 x \sqrt{x^2+1}}$$
We want to solve
$$
-2 x^2+2 \sqrt{2} \sqrt{x^2+1} x-\sqrt{2} \sqrt{x^2+1}=0$$
$$
\frac{2x^2}{2x-1}=\sqrt{2}\sqrt{x^2+1}\Rightarrow -2 + 8 x - 10 x^2 + 8 x^3 - 4 x^4=0
$$
Or:
$$
(x-1) \left(2 x^3-2 x^2+3 x-1\right)=0
$$
The second term has two complex roots, as its discriminant is negative, and a root between $0$ and $\frac{1}{2}$(by Bolzano-Weierstrass), but from
$$
\frac{2x^2}{2x-1}=\sqrt{2}\sqrt{x^2+1}
$$
we can see that it must be a false root. We have to check the second derivative:
$$f''(x)=\frac{x^2}{\left(x^2+1\right)^{3/2}}-\frac{1}{\sqrt{x^2+1}}+\frac{1}{\sqrt{2} x^2}$$
$$\left.f''(x)\right|_{x=0}=\frac{1}{2\sqrt{2}}>0$$
Thus it is a minimum, and the only possible one.


text:
Q: Django ModelForm does not save to database I try to add a comment but it does not save it to the database. There is no error.
My Views is
def add_comment(request, id):
    article = get_object_or_404(Article, id=id)

    if request.method == "POST":
        form = CommentForm(request.POST,instance=article)

        if form.is_valid():
            comment = form.save(commit=False)
            comment.post = article
            comment.save()
            return redirect('articles:detail', pk=article.pk)
    else:
        form = CommentForm()

    template="article/comment.html"
    return render(request, template, {'form': form})

comment.html:
<form method="POST">{% csrf_token %}
{{form.as_p}}
<button type="submit">Send</button>

forms.py
class CommentForm(forms.ModelForm):

class Meta:
    model = Comment
    fields = ('name', 'comment')


text:
Q: Multiple *ngFor loops in ion-list I have two arrays of data. "subtitles" & "title". How to I properly incorporate the two arrays into an ion-list, so that I have a title and subtitle from the two arrays showing in one ion-item (title on top of the subtitle)?
in my .ts file:
items = [
 'Email',
 'Phone Number',
 'Address',
 'Cards'
];

data = [
  "first last",
  "test phone number",
  "test address"
]

in my .html file
<ion-content padding>
 <ion-list class="list">
  <div *ngFor="let unit of data">
    <button ion-item *ngFor="let item of items" (click)="enterPage(item)">
        {{item}}
        {{unit}}
   </button>
  </div>
 </ion-list>
</ion-content>

A:
  <button ion-item *ngFor="let item of items; let i = index" (click)="enterPage(item)">
        {{items[i]}}
        <h3>{{data[i]}}</h3>
  </button>


text:
Q: Issue with Null terminating string display I have written small piece of code for displaying data in 2x16 character LCD.
char str2[] = "Hello Welcome";
char *ptr2=str2;

initializeLCD();
sendLCDCommand(CLEAR_DISPLAY);
while(*ptr2) {
    displayInRow1(ptr2++);
    CL_delayMS(300);
}

In this code, the display displays "Hello Welcomeeeeeeeeeeeeeeeeeeeee"
I thought while(*ptr2) will terminate after printing last letter "e" in the string. If I comment the line containing while(*ptr2), the data is displayed correctly. I am not sure what is wrong with this code above.
I am using Atmel Studio with Atmega328 controller. displayInRow1() function is tested and no issue with that.

A: Your function displayInRow1() takes a pointer and passes it to sendTextToLCD() which displays a string. That's why it works correctly when you remove the while. So all you need is
initializeLCD();
sendLCDCommand(CLEAR_DISPLAY);
displayInRow1(str2);

I am not going to try to explain the result you are getting, except to say the while loop displays something like this
Hello Welcome
ello Welcome
llo Welcome
lo Welcome
o Welcome
 Welcome
Welcome
elcome
lcome
come
ome
me
e


text:
Q: Getting System.AccessViolationException when running project in visual studio 2015 Win 10 TP via Parallel on mac I am trying to run project in Visual Studio 2015 CTP 6 installed on Windows 10 Technical Preview over mac via Parallel Desktop 10.
Project creation and build goes fine, but when I try to run it in debugger mode i get following error:
An unhandled exception of type 'System.AccessViolationException' occurred in Unknown Module.

Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

FYI - It runs fine if I try "Start Without Debugging".
Thanks in advance.

A: Install Windows 10 preview build 10049.
As I updated my PC from Windows 10 10041 --> 10049 and this problem is resolved.


text:
Q: Dynamic iframe content with $_POST PHP has always been kind of a problem for me. Normally I find my way with searching and trial and error, but this time I can't figure it out.
I'm currently working on a project where people can order services online. The ordering module is on a different domain which we frame using iframe. All the rest of the content is hosted on or own domain. When people browse through our services they can click a link where they order said service online. They are being lead to a page with a dynamic iFrame. The iFrame looks like this:

   <iframe id="innerframe" src="<?php echo $_POST['res']; ?>"
            name="reserveer" frameborder="0">

The button that leads them there looks like this:

<form method="post" action="iframepage.php">
<input type="hidden" name="res" value="http://requestedservice.com" />
<input type="submit" value="Order now"/>
</form>

And this works pretty great! The only problem is when people go to the iframe page, the page (or frame) is empty. I would like for the users to see a standard iframe src if they didn't go to the page with a "Order now" button. So I was trying to get something like this (and tried a lot of different approaches in the meantime):

<?php
if ($_POST) {
 $resUrl =  "echo $_POST['res']";
} else {
 $resUrl = "http://standardframecontent.com";
}
?>

Where the frame now echos $resUrl.
Like I said, I tried a lot of different approaches. This is the first time I asked help online myself which means I'm pretty desperate.

A: Try this:
<iframe id="innerframe" src="<?= (isset($_POST['res']) ? $_POST['res'] : 'http://standardframecontent.com'); ?>" name="reserveer" frameborder="0">

A: Have you tried testing the post value like this?
if (isset($_POST['res'])) {
    $resUrl =  $_POST['res'];
} else {
    $resUrl = "http://standardframecontent.com";
}

    <iframe id="innerframe" src="<?php echo $resUrl; ?>"   name="reserveer" frameborder="0">

I test the var and then put it into a var.
I print that var now, both case =)


text:
Q: curl get request brings no js page version When I bring www.amazon.com with curl get request I get no js page version.
My request looks like this:
$ch = curl_init ($url );
$header[0] = "Accept: text/xml,application/xml,application/xhtml+xml,";
$header[0] .= "text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
$header[] = "Accept-Language: en-us,en;q=0.5";
$header[] = "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7";
$header[] = "Accept-Encoding: deflate";
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt ($ch, CURLOPT_COOKIEJAR, $ckfile);
curl_setopt ($ch, CURLOPT_COOKIEFILE, $ckfile);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION,1);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER,0);
$res = curl_exec($ch);