text:
Q: use *this as std::shared_ptr here is a "chess++" problem that I'm facing wright now with my nested class,
although it may look like some joke, it's not a joke but real problem which I want to either solve or change the way to achieve the same thing in my project.
#include <map>
#include <memory>
#include <iostream>
#include <sigc++/signal.h>

class foo
{
public:
    struct bar;

    typedef sigc::signal<void, std::shared_ptr<bar>> a_signal;

    struct bar
    {
        bar()
        {
            some_signal.connect(sigc::mem_fun(*this, &foo::bar::func));
        }

        void notify()
        {
            some_signal.emit(this); // how to ??
        }

        void func(std::shared_ptr<foo::bar> ptr)
        {
            std::cout << "you haxor!" << std::endl;
            // use the pointer ptr->
        }

        a_signal some_signal;
    };

    std::map<int, std::shared_ptr<bar>> a_map;
};

int main()
{
    std::shared_ptr<foo::bar> a_foo_bar;
    foo foo_instance;

    foo_instance.a_map.insert(std::pair<int, std::shared_ptr<foo::bar>>(4, a_foo_bar));
    foo_instance.a_map.at(0)->notify();
    return 0;
}

What I want to do here is to emit a signal.
the signal is declared as one that triggers a handler that takes a shared_ptr as an argument.
the function notify() should convert *this into shared_ptr, how do I do that to make the above code run?

A: Derive from enable_shared_from_this:
struct bar : std::enable_shared_from_this<bar>

to get a member shared_from_this():
some_signal.emit(shared_from_this());

As long as the current object is owned by at least one shared pointer, this will return a shared pointer, sharing ownership with that pointer. Note that, in your program, a_foo_bar is empty, so neither this nor the call to notify will work. Also beware that it won't work from the constructor or destructor, since the object is not owned by a shared pointer at that time.


text:
Q: Derivation of Runge-Kutta Methods of Order Two? My textbook (Burden Faires Numerical Analysis Chapter 5.4) starts with:

The first step in deriving a Runge-Kutta method is to determine values for $a_1, \alpha_1, \beta_1$ with the property that $a_1 f(t + \alpha_1, y + \beta_1)$ approximates:

\begin{align*}
  T^{(2)}(t,y) &= f(t,y) + \frac{h}{2} f'(t,y) \\
\end{align*}
Can someone explain this setup? What is this $T$ function? Where did that definition come from and what does it represent? And why should this be approximated by $a_1 f(t + \alpha_1, y + \beta_1)$?
Here is the rest of the derivation, FWIW:
By chain rule:
\begin{align*}
  f'(t,y) &= \frac{df}{dt}(t,y) = \frac{\partial f}{\partial t}(t,y) + \frac{\partial f}{\partial y}(t,y) \cdot f(t, y) \\
\end{align*}
we have:
\begin{align*}
  T^{(2)}(t,y) &= f(t,y) + \frac{h}{2} \frac{\partial f}{\partial t}(t,y) + \frac{h}{2} \frac{\partial f}{\partial y}(t,y) \cdot f(t,y) \\
\end{align*}
Taylor expansion of $f(t + \alpha_1, y + \beta_1)$ yields:
\begin{align*}
  a_1 f(t + \alpha_1, y + \beta_1) &= a_1 f(t,y) + a_1 \alpha_1 \frac{\partial f}{\partial t}(t,y) + a_1 \beta_1 \frac{\partial f}{\partial y}(t,y)\\
                                   &+ a_1 \cdot R_1(t + \alpha_1, y + \beta_1) \\
\end{align*}
where for $\xi \in (t, t+\alpha_1), \mu \in (y, y+\beta_1)$:
\begin{align*}
  R_1(t + \alpha_1, y + \beta_1) &= \frac{\alpha_1^2}{2} \frac{\partial^2 f}{\partial t^2} (\xi, \mu) + \alpha_1 \beta_1 \frac{\partial^2 f}{\partial t \partial y} (\xi, \mu)
                                   + \frac{\beta_1^2}{2} \frac{\partial^2 f}{\partial y^2}(\xi, \mu) \\
\end{align*}
When we set
\begin{align*}
  a_1 f(t + \alpha_1, y + \beta_1) &= T^{(2)}(t,y) = f(t,y) + \frac{h}{2} f'(t,y) \\
\end{align*}
yields:
\begin{align*}
  a_1 &= 1 \\
  \alpha_1 &= \frac{h}{2} \\
  \beta_1 &= \frac{h}{2} f(t,y) \\
\end{align*}
So:
\begin{align*}
  T^{(2)}(t,y) &= f\left( t + \frac{h}{2}, y + \frac{h}{2} f(t,y) \right) - R_1 \left( t + \frac{h}{2}, y + \frac{h}{2} f(t,y) \right) \\
\end{align*}
This yields the midpoint method:
\begin{align*}
  w_0 &= \alpha \\
  w_{i+1} &= w_i + h f\left( t_i + \frac{h}{2}, w_i + \frac{h}{2} f(t_i, w_i) \right) \\
\end{align*}

A: $T^{(2)}$ appears to be the two-term Taylor approximation for the divided difference
$$
\frac{y(t+h)-y(t)}{h}=y'(t)+\frac{h}{2}y''(t)+\frac{h^2}{6}y'''(t)+...
$$
You can combine the first two terms a la Taylor to $y'(t+\frac h2)$. which hints to where the midpoint method comes into play.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Multiple draggable with different color depending on which droppable it's in I have several divs. Some with class eucountry and some with class country. I want the divs with eucountry as class to turn green when it's in the droppable with #EU and red when it's in #not. I want the divs with class country to do the opposite.
Here is my js code
$(document).ready(function() {
    $(".eucountry").draggable();

    $("#EU").droppable({
        drop: function(event, ui) {

            $(ui.draggable).css("background-color", "green");
        }
    });

    $("#not").droppable({
        drop: function(event, ui) {

            $(ui.draggable).css("background-color", "red");
        }
    });
});

I've tried to use an if statement that :
if($("div").hasClass("eucountry){
    $(ui.draggable).css("background-color", "red");
}

but it's not working.Any ideas how I can solve this problem?

A: So close, you have just to use the if statement inside drop callback, example :
$("#EU").droppable({
   drop: function(event, ui) {
       if( $(ui.draggable).hasClass("eucountry") ){
           $(ui.draggable).css("background-color", "green");
       }

       if( $(ui.draggable).hasClass("country") ){
           $(ui.draggable).css("background-color", "red");
       }
   }
});

$("#not").droppable({
   drop: function(event, ui) {
       if( $(ui.draggable).hasClass("eucountry") ){
           $(ui.draggable).css("background-color", "red");
       }

       if( $(ui.draggable).hasClass("country") ){
           $(ui.draggable).css("background-color", "green");
       }
   }
});

Hope this helps.

A: If you make the drop actually append items into droppable, you can use CSS declarations:

$(document).ready(function() {
  $(".draggable").draggable();
  $(".droppable").droppable({
    drop: function(event, ui) {
      ui.draggable.css({
        top: 0,
        left: 0
      }).appendTo(this);
    }
  });
});
div {
  display: inline-block;
  vertical-align: top;
  margin: 5px;
}
.droppable {
  width: 100px;
  min-height: 100px;
  color: #fff;
  background-color: grey;
}
.draggable {
  width: 70px;
  height: 50px;
  background-color: dodgerblue;
}
#EU .eucountry {
  background-color: green;
}
#EU .country {
  background-color: red;
}
#not .eucountry {
  background-color: red;
}
#not .country {
  background-color: green;
}

Country

EU country

EU

NOT


text:
Q: Xcode 8 localization import crash Xcode (8.1) is crashing when I import the localizations for my project.
It also crashes when I export and then import the same xliff file whithout modification.
Here is the xliff file: http://ge.tt/7J5UY3i2
Here is the full crash report http://pastebin.com/JsJFeCqB.  Any tips or workarounds for this?
Application Specific Information:
ProductBuildVersion: 8B62
UNCAUGHT EXCEPTION (NSInvalidArgumentException): -[Xcode3VariantGroup addToTargetDefaultResourcesBuildPhase:]: unrecognized selector sent to instance 0x7fe69615cba0
UserInfo: (null)
Hints: None

Backtrace:
  0   __exceptionPreprocess (in CoreFoundation)
  1   DVTFailureHintExceptionPreprocessor (in DVTFoundation)
  2   objc_exception_throw (in libobjc.A.dylib)
  3   -[NSObject(NSObject) doesNotRecognizeSelector:] (in CoreFoundation)
  4   ___forwarding___ (in CoreFoundation)
  5   _CF_forwarding_prep_0 (in CoreFoundation)
  6   __81+[IDELocalizationWork fileReferenceStreamForName:directoryPath:superitem:target:]_block_invoke (in IDEFoundation)
  7   __33-[IDEStream(IDEStreamMonad) map:]_block_invoke (in IDEFoundation)
  8   __24-[_IDEStreamMap onNext:]_block_invoke_4 (in IDEFoundation)
  9   -[_DVTTimeSlicedMainThreadOrderedUniquingWorkQueue _processWorkItemsWithDeadline:] (in DVTFoundation)
 10   -[DVTTimeSlicedMainThreadWorkQueue _processWithDeadline:] (in DVTFoundation)
 11   -[_DVTTimeSlicedMainThreadActiveWorkQueues _processWorkQueuesOnDeadline] (in DVTFoundation)
 12   __NSFireDelayedPerform (in Foundation)
 13   __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ (in CoreFoundation)
 14   __CFRunLoopDoTimer (in CoreFoundation)
 15   __CFRunLoopDoTimers (in CoreFoundation)
 16   __CFRunLoopRun (in CoreFoundation)
 17   CFRunLoopRunSpecific (in CoreFoundation)
 18   RunCurrentEventLoopInMode (in HIToolbox)
 19   ReceiveNextEventCommon (in HIToolbox)
 20   _BlockUntilNextEventMatchingListInModeWithFilter (in HIToolbox)
 21   _DPSNextEvent (in AppKit)
 22   -[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] (in AppKit)
 23   -[DVTApplication nextEventMatchingMask:untilDate:inMode:dequeue:] (in DVTKit)
 24   -[NSApplication run] (in AppKit)
 25   NSApplicationMain (in AppKit)
 26   start (in libdyld.dylib)

A: This issue kills me. The tool could/should work and make your life so much easier, but it just doesn't. I had this problem over the summer and fixed it with the info.plist tip in the first bullet, but I've recently updated the project and I'm back in xliff exception hell again. On the bright side, my current crash seems to be happening after it finishes doing the work so I am able to keep working.
There are a bunch of things that can go wrong and cause the import to crash. Usually Xcode just blinks out of existence. If you want to see some info before the crash, use xcodebuild:
xcodebuild -verbose -importLocalizations -localizationPath "lang.xliff" -project ./myProject.xcodeproj

*

*When you localize, don't add a language directly to an info.plist. Instead add a InfoPlist.Strings file to your project and add the language to that. You may need to manually create the file in each lang.lproj folder. Make sure you don't have an info.plist file in any lang.lproj folder other than base.lproj.

*When localizing Settings.bundle, create your lang.lproj folders. When you create the Root.strings file, capitalization matters. It must be "Root.strings" otherwise it might work on iOS, but it won't work on the iOS Simulator.

*Look around in your project structure. After you work with the crashing tool you end up with a bunch of files in the wrong place. You can have a Localized.Strings file in the root group of your project. Remove those.

*Only use base.lproj instead of en.lproj so manually remove en.lproj files if you find them in the project.

*the XLIFF file does need to be well formatted, but I don't think that causes a crash.

*not for you, but supposedly there was a specific crash fixed in Xcode 7 so make sure you are on the latest to avoid that one, at least.
I have some python scripts for living with xliff. They need source path's updated in some of the scripts, but they may help out in the long run: https://github.com/danloughney/xliffHell

A: One of your strings contains double quotes. Try replacing them by " in your untranslated XLIFF file and see if you can re-import that file. This is just a wild guess, and I do not have XCode 8.1 at hand to try and reproduce this myself, but this is the only thing I noticed in your XLIFF file that looked dodgy.

A: Another hint: Make sure you do not translate CFBundleName and CFBundleDisplayName. XCode will crash during the last step of the import. This issue still exist in XCode 10.3.


text:
Q: unpack JSONB object with best performance There are a simple expression or function to "unpack" sub-objects, exploding it into the main object?

Explaining with example:
SELECT '{"x":null,"A":{"foo":true,"bar":123},"B":2332}'::jsonb;
-- = JSONB object with "A" as sub-object.

Is a typical case: I need "A" content into the main object. And need that datatypes (number/boolean/null) are preserved, no "convert string solution" is valid. Also good perfomance is expected.
Remove "A" is ok with - 'A', but, put back its contents , is not easy:
SELECT ('{"x":null,"A":{"foo":true,"bar":123},"B":2332}'::jsonb - 'A')
    || '{"foo":true,"bar":123}'::jsonb; -- aim result, unpacked!

SELECT ('{"x":null,"A":{"foo":true,"bar":123},"B":2332}'::jsonb - 'A')
    || ('{"A":{"foo":true,"bar":123}}'::jsonb)->'A' -- NOT WORKS...

How to put back "A" contents?

A: Operator || has higher priority than operator ->, so you need to move the parentheses around. I only changed the last from ::jsonb)->'A' to ::jsonb->'A') and it works:
SELECT
    ('{"x":null,"A":{"foo":true,"bar":123},"B":2332}'::jsonb - 'A')
    || ('{"A":{"foo":true,"bar":123}}'::jsonb->'A');


text:
Q: AVR flash memory reading and writing I don't understand one fundamental thing about flash memory access in AVR.
 As datasheet says flash page consists from 64 words for atmega16 and there are 128 pages. Since it has 16kbytes of flash memory it easy to get that word size is 2 bytes and page size is 128 bytes.
Well.. In Spi programming mode there are load and write instructions. First of all, what is the difference between them?
And the second question is about load memory page instructions. There are two instructions: one for low byte and one for high. We have to send four bytes: command identification byte(if I can call it so), MSB of the address, LSB of the address and data byte. Question exactly is what do that instructions do? What are high and low bytes here although we load page which consists from 128 bytes?

A:
Well.. In Spi programming mode there are load and write instructions. First of all, what is the difference between them?

You are probably not aware of the "Page Buffer". To write new data to a page, the Page Buffer must be filled first. It is holding one temporary page and must be filled word by word. -> Load instruction
The buffer is copied to Flash memory in one operation. -> Write instruction

And the second question is about load memory page instructions. There are two instructions: one for low byte and one for high. We have to send four bytes: command identification byte(if I can call it so), MSB of the address, LSB of the address and data byte. Question exactly is what do that instructions do? What are high and low bytes here although we load page which consists from 128 bytes?

It refers to the low and high byte of each word that is loaded into the page buffer.


text:
Q: Amending REST API function without deactivate/activate plugin every time changes is made I am working on WordPress development where I have to create a custom REST API in a custom plugin. But every time I am amending the the REST API functions, I have to deactivate and activate the plugin to make the changes works on browser. I find it time consuming and a bit annoying.
Is there any way to add/edit/delete a REST API without deactivating/activate the plugin?
My REST API is inside <plugin_name>_plugin.php and the route registration is outside of construct function.


text:
Q: Embed bitmap in ActionScript3 How can I embed a bitmap in Actionscript 3 and get the BitmapData?
public class MyGame extends Sprite {
    [EMBED(source="Assets/helicopter1.png")] private static var BMClass:Class;
    public function MyGame() {
        var BM:Bitmap = new BMClass();
        var BMData:BitmapData = new BitmapData(BM.width, BM.height);
        BMData.draw(BM)
    }
}

I've tried everything. If I ever try to instantiate the embedded class (new BMClass();) I get this error:
TypeError: Error #1007: Instantiation attempted on a non-constructor..
If I use
[EMBED(source="Assets/helicopter1.png")] private static var BMClass:BitmapData;
or something similar the BitmapData is null.
Edit:
So I figured out that the embedded data is null, but I can't figure out why. What did I do wrong in the embedding?

A: You don't need to instantiate as BitmapData and draw - you can simply:
[Embed(source="Assets/helicopter1.png")]
private var AssetClass:Class;

var bitmap:Bitmap = new AssetClass();

A: Looks like you are embedding correctly if you don't get an error transcoding. You should be able to get the bitmapData directly from the bitmap:
[Embed(source="picture.jpg")]
private var Picture:Class;

// create a bitmap of the embedded
var pic:Bitmap = new Picture();

// add to display list
addChild(pic);

// if you need to get the bitmapData for something else
var bitmapData:BitmapData = pic.bitmapData;

A: In some editors (at least my version of Intellij) the Embed tag is case sensitive. I got the exact same error you have when using [EMBED] but it worked great when I switched to [Embed]


text:
Q: What is the correct syntax for params? According to this rails guide it is acceptable to key params with the name you associate with the html values in your template,
"When the form is submitted, the name will be passed along with the form data, and will make its way to the params hash in the controller with the value entered by the user for that field. For example, if the form contains <%= text_field_tag(:query) %>, then you would be able to get the value of this field in the controller with params[:query]"
However, when I attempt to access a param I submitted it throws the following error:

I understand that there are other params besides :name but I am just trying to get this one handled for now before passing the others. I am just making this app to practice the fundamentals.
Also, how come my params are being passed in my URL? These are forms, shouldn't they be submitted as a POST request and thereby able to use strong params with? I think the reason i'm having so much trouble is because I am used to strong params, I am unfamiliar with this syntax. Any help is appreciated, thanks!
Here is my code:
Controller:
class OrdersController < ApplicationController
  def create
    Order.create(params[:name])
  end
end

View
<h1> Input information </h1>
<%= form_tag("/order",method: "get") %>
<%= label_tag(:name, "Enter name") %>
<%= text_field_tag(:name) %>
<%= label_tag(:email, "enter email") %>
<%= text_field_tag(:email) %>
<h2> Select color </h2>
<%= label_tag(:red,"red") %>
<%= check_box_tag(:red) %>
<%= label_tag(:green,"green") %>
<%= check_box_tag(:green) %>
<%= label_tag(:indigo,"Indigo") %>
<%= check_box_tag(:indigo) %>
<%= submit_tag("submit") %>

A: You need to provide a hash argument to create. How will Order know that you are setting name? You are basically doing this:
Order.create('phoot')
You need to specify what phoot is:
Order.create(name: params[:name])
# ends up being Order.create(name: 'phoot')


text:
Q: how to get user who creates article in blog using ruby on rails I am writing own blog in ruby on rails. I got stuck while getting user who creates articles on views. Basically I want to fetch username of user who creates article(post) in my blog application.
I have user, article tables where I have user_id in article table. I do not know how to fetch user who create article in application.Basically I want to display name (username) of user who create article on article/index.html page. I tried to get user name while creating article in article controller
def create
      @article = Article.new(params[:article])
      @article.user_id = current_user
      @article.save
      redirect_to article_path(@article)

but could not get.
Currently users_controller.rb is empty.
Do I need join between user and article table or is it possible with out join in rails. Please suggest me.
article/index.html.

  <title>
 learning experience blog
</title>

<% @articles.each do |article| %>

<%= article.title %>

 <%= article.created_at %>

 <%= truncate(article.body, :length => 500, :separator => ' ') %>

    <% if current_user.try(:is_admin) %>
     <%= link_to "edit",edit_article_path(article), :class => 'btn btn-warning btn' %>
     <%= link_to "delete",article_path(article),:method => :delete,:confirm => 'Are you sure?',:class => 'btn  btn-danger' %>
    <% end %>
     <%= link_to "view more...",article_path(article), :class => 'btn btn-primary' %>

    <% end %>
 <% if current_user.try(:is_admin) %>
  <%= link_to "Create new Article", new_article_path, :class => 'btn btn-large btn-primary' %>
  <% end %>

articles_controller.rb
class ArticlesController < ApplicationController
    def index
        @articles = Article.all
    end

    def show
      @article = Article.find(params[:id])
    end

    def new
      @article = Article.new
    end

    def create
      @article = Article.new(params[:article])
      @article.user_id = current_user.id
      @article.save
      redirect_to article_path(@article)
    end

    def destroy
      @article = Article.find(params[:id])
      @article.destroy
      redirect_to action:  'index'
    end

    def edit
      @article = Article.find(params[:id])
    end

    def update
      @article = Article.find(params[:id])
      @article.update_attributes(params[:article])
      flash.notice = "Article '#{@article.title}' Updated!"
      redirect_to article_path(@article)
     end
end

user.rb model
class User < ActiveRecord::Base
    has_many :articles
    has_many :comments
  # Include default devise modules. Others available are:
  # :token_authenticatable, :confirmable,
  # :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  # Setup accessible (or protected) attributes for your model
  attr_accessible :username, :email, :password, :password_confirmation, :remember_me
   attr_accessible :title, :body
end

article_rb
class Article < ActiveRecord::Base
   attr_accessible :title, :body
   has_many :comments
   belongs_to :user
end

schema.rb
# encoding: UTF-8
# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended to check this file into your version control system.

ActiveRecord::Schema.define(:version => 20130406120152) do

  create_table "articles", :force => true do |t|
    t.string   "title"
    t.text     "body"
    t.datetime "created_at",  :null => false
    t.datetime "updated_at",  :null => false
    t.integer  "user_id"
  end

  create_table "comments", :force => true do |t|
    t.text     "content"
    t.integer  "user_id"
    t.string   "article_id"
    t.datetime "created_at", :null => false
    t.datetime "updated_at", :null => false
  end

  create_table "users", :force => true do |t|
    t.string   "email",                  :default => "", :null => false
    t.string   "encrypted_password",     :default => "", :null => false
    t.string   "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",          :default => 0
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string   "current_sign_in_ip"
    t.string   "last_sign_in_ip"
    t.boolean  "is_admin"
    t.datetime "created_at",                             :null => false
    t.datetime "updated_at",                             :null => false
    t.string   "name"
    t.string   "username"
    t.boolean  "is_active"
  end

  add_index "users", ["email"], :name => "index_users_on_email", :unique => true
  add_index "users", ["reset_password_token"], :name => "index_users_on_reset_password_token", :unique => true

end

Please suggest me how to get user info who creates article.

A: I beleive you have the relationships defined in your model.
class User
   has_many :articles
end

class Article
  belongs_to :user
end

Now you could simply do
a = Article.find_by_id(1)
a.user # to get the user for Article


text:
Q: Can GDB decode core if it were piped? I have huge core files, and hence set the core_pattern is set to gzip as they are written.
Later if the backtrace is to be obtained, first gunzip has to be done (and it takes a very long time!) before the core file can be fed to gdb.
I wanted to know if there is a way to pipe the core (as it is being created) to gdb (or any other program which can fetch the backtrace). I checked gdb, and there seems to be no such option (neither does readelf); before I could whip up something of this sort, I wanted to know if there is anything with the format of ELF core (on x86_64, GNU/Linux) that could prevent this from working ?
-- EDIT --
grok'd through readelf sources, and other programs which can generate backtrace, and they seem to be seek()ing through the file forwards and backwards! I am not sure if this is absolutely necessary, or if its possible to read and gather all the needed info in a single pass (since I want to read from a pipe, seek is not an option!)

A: A kernel coredump handler can generate the backtrace from the zombie process, without writing the coredump to disk first.
I assumed that ABRT could do this.  However, it seems that there is a patch, but it has not been merged yet:

*

*https://github.com/abrt/abrt/issues/872

A: Generating a backtrace requires fetching memory contents by address. In a core file each virtual address whose contents are included in the core is at a particular offset in the core file. When code which generates a backtrace performs a seek, the target of that seek is the offset for the memory contents for an address which maps to that offset.
The obstacle to treating a core file as a stream is that there is no reason to expect the offsets corresponding to addresses whose contents are being fetched to increase with each fetch. A backwards seek simply means that the current fetch is for contents whose offset is smaller than the offset of the previous fetch.
Perhaps the simplest scenario for constructing a backtrace from a core file is a core file generated by code which consistently uses a frame pointer. In this scenario the memory fetches are from the stack, and the frame pointer values, one per stack frame, provide what amounts to a linked list of stack frames, in which the next word of each stack frame is a return address (which, in the presence of appropriate symbols, can be mapped to a function name and offset).
Increasing addresses in a typical core file have increasing offsets within the file, and a typical backtrace represented with a linked list of frame pointer values has a larger frame pointer address for each successive frame. A simple backtrace from a core file from code which uses a frame pointer could begin by locating the stack (from the value of the stack pointer register), and traversing the linked list of frame pointer values, displaying the return address associated with each frame. This approach would involve a fair amount of buffering, mainly of the program segment headers near the beginning of the core file, which are used to map virtual addresses to file offsets. The worst of the inefficiency in this approach would presumably be ignoring all of the uncompressed data between the segment headers (and the note used to obtain register values) and the stack of the relevant thread.
Generating a backtrace from code which does not use a frame pointer is more complicated, but that might also be possible if enough data is buffered. It's more likely to be feasible if the correct symbols are available, more so if debug symbols are available. As with the frame pointer scenario, fetching data from the relevant stack is likely to be essential.
Rather than beginning with the hope of treating a core file as a stream, perhaps the best approach here is to change the way space savings are achieved for huge core files. The fundamental problem with gzip output is that it does not provide random access. A better choice for a space efficient representation of a core file is a format like squashfs, in which random access is provided by compressing constant size chunks, and those chunks are indexed, so that obtaining data for a specified offset consists first of locating and uncompressing the appropriate chunk, and then seeking within that uncompressed data.
The immediate challenge with using squashfs in core_pattern is that there is no obvious way to invoke mksquashfs on standard input. Perhaps the simplest way to work around this is to allow a core file to exist in its uncompressed form long enough to invoke mksquashfs. A more space efficient approach might involve writing code which can generate squashfs format from standard input; this is likely to be straightforward if mksquashfs never has a reason to seek backwards in a file it includes in a squashfs image (I don't know this for sure, but my understanding of squashfs format suggests that it is at least a possibility).
Assuming you have a squashfs image containing a huge core file, one way to feed it to a tool which generates a backtrace is to simply mount the image and provide the relevant pathname within that mount point, but it is also feasible to modify applications to handle squashfs format natively. One advantage of this approach is that any other operation on a core file beyond a simple backtrace is also available (a likely next step in a core analysis is generating multiple backtraces, one per thread).


text:
Q: How can I make a parallelogram using a copy of a triangle? Okay, so I'm feeling a little silly as I think this was probably something covered in grades 6-8... However, for the life of me I can't think of the solution or find one online aside from the obvious guess work...
I'm writing some software that requires I create a parallelogram out of an existing triangle....
So essentially, I think I need to copy the original triangle and then somehow mirror it to form a parallelogram. I'm just not certain as to what steps need to be taken to transform the copied triangle into the right rotation and attached to the right side of the original triangle to make it a parallelogram...
Here's an image I drew up illustrating what I mean....
https://puu.sh/rIQZC/43c52e9afb.png

A: Reflect the triangle about the midpoint of one of its sides. An easy way to do this is to reflect the vertex that's opposite your chosen side and then connect the dots:

Let's say we want to build the parallelogram with $\overline{AC}$ as its diagonal. Find its midpoint $M$, draw the line $BM$ and measure off a distance equal to $|\overline{BM}|$ on the other side of $M$. That's the fourth vertex of your parallelogram:

Analytically, $M=(A+C)/2$ and $B'=M-(B-M)$, i.e., reverse the vector $\vec{MB}$. This construction can be performed on any side of the triangle, of course.
By the way, this is equivalent to rotating a copy of the triangle 180° and then translating it so that the edges that you want to be the diagonal of the parallelogram coincide.


text:
Q: Req.body is Empty in Node Js In my Node application I am trying to view request.body object to check for elements that are coming inside of it but console.log(req.body) revels that its empty. Here are my files.
app.js file below
var express = require("express");
var app = express();
var mongoose = require("mongoose");
var nationalPark = require("./models/NationalParks");

//config
mongoose.connect('mongodb://localhost/National_Parks', {useNewUrlParser: true, useUnifiedTopology: true}).catch(function(reason){
    console.log('Unable to connect to the mongodb instance. Error: ', reason);
});
app.set('view engine', 'ejs');
var bod = require("body-parser");
app.use(bod.urlencoded({extended:true}));
app.use(bod.json());

app.use(express.static(__dirname + '/resources'));

//Routes
app.get("/",function(req,res){
    nationalPark.find({},function(err,nationalParks){
        if(err){
            console.log(err);
        }else{

            res.render("home",{nationalParks:nationalParks});
        }
    })

});

app.get("/home",function(req,res){
    nationalPark.find({},function(err,nationalParks){
        if(err){
            console.log(err);
        }else{
            console.log(nationalParks);
            res.render("home",{nationalParks:nationalParks});
        }
    })
});

app.get("/login",function(req,res){
    res.render("login");
});
app.get("/signup",function(req,res){
    res.render("signup");
});
app.get("/logout",function(req,res){
    res.render("home");
});

app.get("/NationalPark",function(req,res){
    console.log(park.park)
 res.render("NationalPark",{park:park.park});
});

app.post("/NationalPark",function(req,res){

      console.log(req.body);
    res.render("NationalPark");
});
app.get("/post",function(req,res){
    res.render("post");
});
app.get("/post-display",function(req,res){
    res.render("post-display");
});
app.get("/profile",function(req,res){
    res.render("profile");
});

//listening port
app.listen(3000,function(){
    console.log("Server started");
});

Here is my home.ejs  file
<!doctype html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link href="https://fonts.googleapis.com/css?family=Pacifico&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <link rel="stylesheet" type="text/css" href="/css/national-parks.css">

                Login
                Sign Up
                Logout

National Parks Observer

Site Dedicated to Indian National Parks

         <%  var r=Math.round(nationalParks.length/3); %>
         <% var x = 1; %>
         <% var elementCount = 3; %>
         <% var constant = 3; %>
         <% var start=0; %>
         <% while(x<=r){ %>

           <% for(var k=start;k<elementCount;k++){ %>

               <form method="POST" action="/NationalPark">
                <img class="card-img-top" src=<%=nationalParks[k].imageurl %> alt="Card image cap">

<%=nationalParks[k].nationalPark %>

                  <button type="submit" class="btn btn-primary btn-sm"">View Page</button>

                </form>

           <% } %>
           <%  start=start+constant; %>
           <%   elementCount=Math.min(elementCount+constant,nationalParks.length); %>

          <% x++; }  %>

at following post method in app.js
app.post("/NationalPark",function(req,res){

      console.log(req.body);
    res.render("NationalPark");
});

console.log(req.body) simply prints {}
Why is it happening, am I missing something? Will deeply appreciate your help. Thanks in advance.

A: Your form, the excerpt below has no <input /> elements.
<form method="POST" action="/NationalPark">
                <img class="card-img-top" src=<%=nationalParks[k].imageurl %> alt="Card image cap">

<%=nationalParks[k].nationalPark %>

                  <button type="submit" class="btn btn-primary btn-sm"">View Page</button>

                </form>

So no data is posted back to the app.
Adding an input element example
<Input type="hidden" name="park_name" value=<%=nationalParks[k].nationalPark %> />

In your form would make the attribute req.body.park_name available in app.js


text:
Q: Get string from default values folder (No Locale)
How to programmatically get a string from the default values folder?

A: If that string won't be present in localised strings.xml entries do this in your default strings.xml:
<string name="my_string" translatable="false">Hello world!</string>

And when you use
getResources().getString(R.string.my_string);

It will return this value.
Make sure your localised strings.xml do not have string entry with that name


text:
Q: Converting a Pandas dataframe to dictionary I have a Pandas Dateframe:
+-----------+-------+---------+
| kpi_name  | coeff | measure |
+-----------+-------+---------+
| messi     | 2     | DoD     |
| ronaldo   | 1.5   | MTD     |
| del_piero | 2     | MTD     |
+-----------+-------+---------+

I need to convert this to a dictionary like :
{'MTD':[{'KPI':'ronaldo', 'measure':'1.5'}, {'KPI:':'messi', 'measure':'2'],
 'DoD':['KPI':'messi', 'measure':'1.4']}

I am trying:
a = df.groupby('measure').apply(lambda x: x.to_dict('list')).to_dict()

My output:
{'MTD': {'kpi_name': ['ronaldo', 'del_piero'], 'coeff': [1.5, 2.0], 'measure': ['MTD', 'MTD']}, 'DoD': {'kpi_name': ['messi'], 'coeff': [2.0], 'measure': ['DoD']}}

Thx a lot of help!

A: Please look into slicing dataframes and transpose T for future reference.
Given a dataframe
df = pd.DataFrame({'KPI':['messi', 'ronaldo', 'del_piero'],\
                   'coeff':[2, 1.5, 2], \
                   'measure':['DoD', 'MTD', 'MTD']})

You can use the following lambda function
df.groupby('measure').apply(lambda x: list(x[['KPI','coeff']].T.to_dict().values())).to_dict()

To achieve your expected output
{'DoD': [{'KPI': 'messi', 'coeff': 2.0}],
 'MTD': [{'KPI': 'ronaldo', 'coeff': 1.5}, {'KPI': 'del_piero', 'coeff': 2.0}]}

A: Using a dictionary comprehension with GroupBy:
df = pd.DataFrame({'kpi_name': ['messi', 'ronaldo', 'del_piero'],
                   'coeff': [2, 1.5, 2],
                   'measure': ['DoD', 'MTD', 'MTD']})

res = {k: grp.to_dict(orient='records') for k, grp in df.groupby('measure')}

print(res)

{'DoD': [{'kpi_name': 'messi', 'coeff': 2.0, 'measure': 'DoD'}],
 'MTD': [{'kpi_name': 'ronaldo', 'coeff': 1.5, 'measure': 'MTD'},
         {'kpi_name': 'del_piero', 'coeff': 2.0, 'measure': 'MTD'}]}


text:
Q: How can you set the SMTP envelope MAIL FROM in AIX 6.1 Sendmail? We have new SMTP relay host and it requires that the sender's email address should be the company's official email domain instead of server hostname
Already did masquerade using generetics table. However, the new relay host still rejected my test email. It seems that my configuration still using server hostname. I am thinking that the MAIL FROM in sendmail SMTP envelope is still the server hostname.
Config Done:

*

*#uncomment line in /etc/sendmail.cf
Kgenerics hash -o /etc/mail/genericstable

*Create genericstable file in /etc/mail directory
a. Set IDs and the addresses I need to map
b. Convert the genericstable file into a db file
Still I got this error message from the relay host:
Reason:[{504 5.5.2 sender@AIXServername Sender address rejected: need fully-qualified address


text:
Q: Why there is && after some function definitions in bash completion file? If you look at files /usr/share/bash-completion/completions/* many have function definition followed by && complete -F (at least in Xenial). Why is this?
Does the notation have some special meaning in bash completion file?
In bash, I don't see any functional difference between scripts
a(){ echo in;return 1;} && a

and
a(){ echo in;return 1;}; a

A: Bash Reference Manual tells

The exit status of a function definition is zero unless a syntax error occurs or a readonly function with the same name already exists. When executed, the exit status of a function is the exit status of the last command executed in the body.

Syntax error may terminate script execution before the complete -Fcommand, so the command following the function declaration may not be executed anyway, but if a readonly function with same name is declared before sourcing the file containing the function, it may not terminate execution. To prevent a wrong bash completion function from being called, such a logical AND test is used.

A: complete is a bash builtin, which tells bash how to autocomplete in various situations. In particular, complete -F funcname cmdname tells bash that if the user has entered the command cmdname then the completion of the arguments is to be handled by the function funcname. Use help complete and man bash for further information. Many system-installed autocompletion files install autocompletion functions using the pattern
_cmd_name () {
  ... compute completions here and assign them to COMPREPLY ...
  return 0
} && complete -F _cmd_name cmd_name

For example,
_apt_get () {
  ... compute completions here and assign them to COMPREPLY ...
  return 0
} && complete -F _apt_get apt-get

which tells bash that if the user has type apt-get as the command name then the autocompletion will be handled by the function _apt_get.
It's purely a matter of coding style, and this style is not ugly or hard to understand.


text:
Q: How do I activate the Daedric gauntlet in the Midden?
Possible Duplicate:
What is the Oblivion-symbol gauntlet in the Midden?

What is the purpose of Daedric gauntlet in the Midden, and why can't I activate it? Are there fail conditions that can prevent one from activating it? If not, what do I need to do?

A: Check out this sites guide on this puzzle. It is part of a quest where you interact with Velehk Sain. UESP's Page on The Midden explains how to activate it:
The Midden Dark contains a ritual chamber with a
large black metal gauntlet on a
pedestal. The symbol of Oblivion is emblazened on the palm of the gauntlet.
The Midden Incident Report can be found on the table here,
along with the Investigator's Key.
Following the clues in the report,
the player can find the needed rings in the Arcanaeum,
in a master-locked chest. The lock can be picked,
or simply opened with the key.
Returning the rings to the gauntlet will activate it,
and the gauntlet will clench into a fist.
Shortly afterwards the dremora Velehk Sain will be summoned.

Hope this helps


text:
Q: How to have a private repository with public issue tracker on GitHub? I am going to release some beta version of my application to the community. Project is stored on GitHub in the private repository.
I would like to allow this community to report bugs and place them directly on GitHub Issues tab - it's not provided by GitHub right now. Do you have any idea, how to cover this flow ?

A: Not possible as of 2019-09 as documented at: https://help.github.com/articles/issues-only-access-permissions/ (archive):

GitHub does not provide issues-only access permissions, but you can accomplish this using a second repository which contains only the issues.

They suggest that you create a separate public repository just for the issues instead.
Possible same request: Github-like hosting, with private source, public ticketing system

A: Bitbucket provides this. You can keep the code private but make tracker public (anyone can view, create, and comment on issues).

A: Use the API access and program some minimal frontend yourself - https://docs.github.com/en/rest/issues


text:
Q: PHP Serial port communication won't give read output I want to read out a QR reader with PHP. I used the library: https://github.com/Xowap/PHP-Serial to setup communication with a serial port. The device is connected but won't read output. Below my code.
<?php
include 'src/PhpSerial.php';

function microtime_float()
{
    list($usec, $sec) = explode(" ", microtime());

    return ((float) $usec + (float) $sec);
}
// Let's start the class
$serial = new PhpSerial;

// First we must specify the device. This works on both linux and windows (if
// your linux serial device is /dev/ttyS0 for COM1, etc)

// We can change the baud rate, parity, length, stop bits, flow control
$serial->deviceSet("COM1");
$serial->confBaudRate(115200);
$serial->confParity("none");
$serial->confCharacterLength(8);
$serial->confStopBits(1);
$serial->confFlowControl("none");

// Then we need to open it
$serial->deviceOpen();

$read = '';
$theResult = '';
$start = microtime_float();
 // To write into
 // Or to read from
while ( ($read == '') && (microtime_float() <= $start + 2) ) {
    $read = $serial->readPort();
    if ($read != '') {
        $theResult .= $read;
        $read = '';
    }
}
$serial->deviceClose();
// If you want to change the configuration, the device must be closed

// We can change the baud rate

// etc...
//
//
/* Notes from Jim :
> Also, one last thing that would be good to document, maybe in example.php:
>  The actual device to be opened caused me a lot of confusion, I was
> attempting to open a tty.* device on my system and was having no luck at
> all, until I found that I should actually be opening a cu.* device instead!
>  The following link was very helpful in figuring this out, my USB/Serial
> adapter (as most probably do) lacked DTR, so trying to use the tty.* device
> just caused the code to hang and never return, it took a lot of googling to
> realize what was going wrong and how to fix it.
>
> http://lists.apple.com/archives/darwin-dev/2009/Nov/msg00099.html

Riz comment : I've definately had a device that didn't work well when using cu., but worked fine with tty. Either way, a good thing to note and keep for reference when debugging.
 */

At first I thought the problem was in the serial port configuration. But i double checkt everything and it's setup correctly. If i open the serial port with an serial port reader program "Hercules" then it reads a value if i scan an qr code.


text:
Q: VMware ESX 3 Storage Array Maintenance We've got a small ESX3 cluster w/ Server vMotion (I don't believe we have Storage vMotion) attached to two iSCSI storage arrays. One array is (gross) Windows and requires Windows updates pretty much all the time. The backup array offers pretty similar performance but is on a platform that doesn't need as much maintenance. However, for reasons that are outside the scope of this question, assume that the Windows array must be the primary.
Currently, we simply shut down all the VMs, place the ESX hosts in Maintenance mode, reboot the storage array, then re-boot the VMs. It is time consuming and annoying but doesn't seem to cause any problems with VM images.
In the cases in which I need to perform maintenance (aka Windows Update reboot) on the initial storage array, how can I migrate my VMs over to the backup array? After the array returns, how can I migrate them back? Prefer using VirtualCenter but we're comfortable from the command line.
Or, if it's possible, is there a way to, ahem, cluster the two arrays (using our existing tech - w/o add'l hardware purchase)?

A: If you are running on ESX versions prior to v3.5 then Storage VMotion isn't supported but Storage VMotion is available in ESX 3.5 if you have VMotion enabled licenses. There there is no GUI interface provided by default though. If you want to use it you can use the ESX Remote CLI tools but it's a lot simpler to follow these instructions on how to install Andrew Kutz's excellent Storage VMotion VI Client Plugin and use that.

A: I see by shutting down the VM I can migrate to a different datastore. Guess I need Storage vMotion in order to migrate a running VM. Shucks.

A: I don't believe you can cluster your arrays and if that is indeed the case then you really only have one option which is to move to 3.5 and use SVM.


text:
Q: MissingMethodException in iOS app while using Xamarin's FileHelper Implementation I recently followed Xamarin's SQLite tutorial to install SQLite-net PCL. Everything works perfectly on the simulator in Debug mode but I'm getting crashes on startup in Release mode.
The exception is as follows:
exception:

System.MissingMethodException

message:

Default constructor not found for type MyApp.iOS.FileHelper

stack trace:

at (wrapper managed-to-native) UIKit.UIApplication:UIApplicationMain
  (int,string[],intptr,intptr)   at UIKit.UIApplication.Main
  (System.String[] args, System.IntPtr principal, System.IntPtr
  delegate) [0x00005] in
  /Users/builder/data/lanes/3969/7beaef43/source/xamarin-macios/src/UIKit/UIApplication.cs:79
  at UIKit.UIApplication.Main (System.String[] args, System.String
  principalClassName, System.String delegateClassName) [0x00038] in
  /Users/builder/data/lanes/3969/7beaef43/source/xamarin-macios/src/UIKit/UIApplication.cs:63
  at MyApp.iOS.Application.Main (System.String[] args) [0x00008] in
  /Users/{FilePath}/iOS/Main.cs:13

What I've found
So this MyApp.iOS.FileHelper is Xamarin's code that fetches the documents directory. The implementation goes like this:
In the Forms application we just have a contract:
public interface IFileHelper
{
    string GetLocalFilePath(string filename);
}

In the MyApp.iOS project we define a dependency:
[assembly: Dependency(typeof(FileHelper))]
namespace MyApp.iOS
{
    public class FileHelper : IFileHelper
    {
        public FileHelper() { }

        public string GetLocalFilePath(string filename)
        {
             string docFolder = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            string libFolder = Path.Combine(docFolder, "..", "Library", "Databases");

            if (!Directory.Exists(libFolder))
            {
                Directory.CreateDirectory(libFolder);
            }

            return Path.Combine(libFolder, filename);
        }
    }
}

Here's how I am using it:
DependencyService.Get<IFileHelper>().GetLocalFilePath("MyAppDatabase.db3")

The application works as expected in Debug mode. So either the Dependency Service is behaving differently in Release or the Documents Directory is different in Release.
My Question
How can avoid this exception in release mode?
Dependency Info:
Xamarin Forms 2.3.3.193
Sqlite-net-pcl 1.2.1

update:
What I've tried:

*

*Added a default constructor, yields no change

*Tried different linker possibilities, yields no change

A: From Introduction to DependencyService

Note that every implementation must have a default (parameterless)
  constructor in order for DependencyService to be able to instantiate
  it. Parameterless constructors cannot be defined by the interface.

You need to add an empty constructor to your FileHelper class.
public FileHelper() {
}

A:
Please note: I tried voting to close this question as a duplicate. It clearly
  failed to be closed as such.

Based on comments point to this post from SushiHangover, this is what resolved my issue:
I needed to add decorate my FileHelper class in my iOS project with:
[Preserve(AllMembers = true)]
again, please go check out his original post here:
https://stackoverflow.com/a/41932246/1664443


text:
Q: Why does Perl 6's Map give me a value in one case and a list in another? I'm playing with Map and I get a result I don't understand.
First, I construct the Map. No big whoop:
> my $m = Map.new: '1' => :1st, '2' => :2nd;
Map.new(("1" => :st(1),"2" => :nd(2)))

I access a single element by the literal key and get back a Pair:
> $m<1>.^name
Pair
> $m<<1>>.^name
Pair

That's all fine.
If I try it with the key in a variable, I get back a List instead:
> my $n = 1
1
> $m<<$n>>.^name
List

That list has the right value, but why do I get a List in that case and not the $m<<1>> case?
And, once I have the list, I seem unable to chain another subscript to it:
> $m<<$n>>.[0]
===SORRY!=== Error while compiling:
Unable to parse quote-words subscript; couldn't find right double-angle quote
at line 2

A: When you access an associative value like this, the compiler can tell that it need only ever return one value.
$m<  1  >
$m<< 1 >>

In Perl 6, a singular value will in many cases behave just like a list of one value.
42.elems == 1 # True
42.[0] =:= 42 # True

In the following case, the compiler can't immediately tell that it will only produce one value:
my $n = 1;
$m<< $n >>;

As it could produce 2 values:
my $o = '1 2';
$m<< $o >>;

If you want the string to be a single key, you have to use quotation marks.
$m<< "$o" >>

Or use the more appropriate {}
$m{ $n }

The $m<1> is just a combination of two features.

*

*Quotewords: ( qw<> and qqww<<>> )
<   a  b  c   > eqv ("a", "b", "c")
<  "a  b" c   > eqv (「"a」, 「b"」, "c") # three strings

<<  a  b  c  >> eqv ("a", "b", "c")
<< "a  b" c  >> eqv ("a  b", "c")    # two strings

*Associative indexing:
%h<   a  b  c  > eqv %h{ <   a  b  c  > }
%h<< "a  b" c >> eqv %h{ << "a  b" c >> }

Also I now get back different values.
$m<   1  >.WHAT =:= Pair
$m<<  1 >>.WHAT =:= Pair
$m<< $n >>.WHAT =:= Pair # different

$m<< $o >>.WHAT =:= List

The reason $m<<$n>>.[0] doesn't work is the compiler thinks you are using a hyper postfix >>.[0].
There are a couple ways of working around that.

*

*Actually using a hyper postfix
$m<<$n>>>>.[0]
$m<<$n>>».[0]

*Use an unspace. (can never be inside of an operator so will split them up)
$m<<$n>>\.[0]
$m<<$n>>\     .[0]

I think this is a bug, as it doesn't make much sense to be matching a hyper postfix inside of a quotewords statement.
(It doesn't affect $m<<1>>.elems)


text:
Q: Jface TreeViewer add right click menu, depending on clicked node There is a good thread on how to correctly hook up a right-click menu to a Jface TreeViewer depending on the selected item.
I would like to show the right click menu depending on: if the right-click was on a node or into "empty space". The problem is that TreeViewer does not automatically clear the selection if you click into empty space. Is there any clean way how to achieve this?
My current approach would be to simply hook up a MouseListener to the tree with the following mouseDown method:
@Override
public void mouseDown(MouseEvent e) {
    TreeItem item = treeViewer.getTree().getItem(new Point(e.x, e.y));
    if (item == null) {
        treeViewer.getTree().deselectAll();
    }
}

This seems to work quite well. What do you think of this?

A: Ok, I found a dirty workaround. So if you really want to do it, here is a possible solution:
final Tree tree = viewer.getTree();

final Menu menu = new Menu(tree);
tree.setMenu(menu);
menu.addMenuListener(new MenuAdapter()
{
    @Override
    public void menuShown(MenuEvent e)
    {
        Point point = tree.toControl(Display.getDefault().getCursorLocation());
        boolean found = false;
        for (TreeItem item : tree.getItems())
        {
            for (int i = 0; i < tree.getColumnCount(); i++)
                if (item.getBounds(i).contains(point))
                    found = true;
        }

        System.out.println(found);
    }
});

A: How to add popup menu to your SWT/JFace TreeViewer
Hi, in your applications main class (that extends ApplicationWindow) in protected Control createContents(Composite parent) method you should add code like this:
//Author: Darius Kucinskas (c) 2008-2009
//Email: d[dot]kucinskas[eta]gmail[dot]com
//Blog: http://blog-of-darius.blogspot.com/
//License: GPL

// Create the popup menu
  MenuManager menuMgr = new MenuManager();
  Menu menu = menuMgr.createContextMenu(mTreeViewer.getControl());
  menuMgr.addMenuListener(new IMenuListener() {
    @Override
    public void menuAboutToShow(IMenuManager manager) {
      if(mTreeViewer.getSelection().isEmpty()) {
        return;
      }

      if(mTreeViewer.getSelection() instanceof IStructuredSelection) {
        IStructuredSelection selection = (IStructuredSelection)mTreeViewer.getSelection();
        DatabaseModelObject object = (DatabaseModelObject)selection.getFirstElement();

        if (object.getType() == DATABASE_OBJECT_TYPE.TABLE){
          manager.add(new ShowTableDataAction(SWTApp.this));
        }
      }
    }
  });

  menuMgr.setRemoveAllWhenShown(true);
  mTreeViewer.getControl().setMenu(menu);
DatabaseModelObject - is class from my problem domain (specific to my program). mTreeViewer - is object of TreeViewer class (JFace). Thanks, have a nice day!


text:
Q: Create an authentication system with a predefined unique password I will want to set up an input on an html page which will ask for
a predefined password in the program, so that when the predefined password is entered,
access to a third party page is executed.
Ideally, the code would have to be JavaScript to be able to integrate it,
but I don't know much about it. I did an equivalent in python (code at the bottom),
if anyone could translate the code to js and implement it in an html page.
   identification = True
   while identification :
    user_password = input("Le mdp : ") #Empty input in the middle of the page
    if user_password == mdp:
            print("allowed access") #Redirection to the third party page via a button
        else: print("x")
            continue          #End of loop, user must enter password again

A: This solution prompts the user for a password, checks it against mdp, and if so redirects to http://redirection.page/. Please note that this isn't secure as anyone can just inspect the page (Ctrl+Shift+I) and see the plain text password.
<script>
var mdp = "PASSWORD"; //Put password here
var identification = true;
while (identification) {
  var user_password = prompt("Le mdp:");
  if (user_password == mdp) {
    alert("Access allowed");
    break;
  } else {
    alert("Access denied");
  }
}
//Your code here
location.href = "http://redirection.page/";
</script>


text:
Q: Laravel Excel Installation I've just used composer to get Maatwebsite Laravel-Excel. I am about to use it but I am brand new to installing/using packages. So far I've only used what is shipped with Laravel.
I'm reading the documentation and am following the steps (I've done the first three steps) but I am confused by this line;
The class is binded to the ioC as excel

$excel = App::make('excel');

I don't really know what most of that means. I have read up a little on ioC and then Dependency Injection (also new to me). But I still don't know - is this part of the docs telling me to do something?? I ran php artisan on the command line (for another purpose) and I got this back;
[2015-04-23 13:42:09] local.ERROR: exception 'BadMethodCallException' with message 'Call to undefined method [package]' in /vagrant/source/laravel-excel/vendor/laravel/framework/src/Illuminate/Support/ServiceProvider.php:226
Stack trace:
#0 /vagrant/source/laravel-excel/vendor/maatwebsite/excel/src/Maatwebsite/Excel/ExcelServiceProvider.php(45): Illuminate\Support\ServiceProvider->__call('package', Array)
#1 /vagrant/source/laravel-excel/vendor/maatwebsite/excel/src/Maatwebsite/Excel/ExcelServiceProvider.php(45): Maatwebsite\Excel\ExcelServiceProvider->package('maatwebsite/exc...')
#2 [internal function]: Maatwebsite\Excel\ExcelServiceProvider->boot()
#3 /vagrant/source/laravel-excel/vendor/laravel/framework/src/Illuminate/Container/Container.php(523): call_user_func_array(Array, Array)
#4 /vagrant/source/laravel-excel/vendor/laravel/framework/src/Illuminate/Foundation/Application.php(703): Illuminate\Container\Container->call(Array)
#5 /vagrant/source/laravel-excel/vendor/laravel/framework/src/Illuminate/Foundation/Application.php(685): Illuminate\Foundation\Application->bootProvider(Object(Maatwebsite\Excel\ExcelServiceProvider))
#6 [internal function]: Illuminate\Foundation\Application->Illuminate\Foundation\{closure}(Object(Maatwebsite\Excel\ExcelServiceProvider), 19)
#7 /vagrant/source/laravel-excel/vendor/laravel/framework/src/Illuminate/Foundation/Application.php(686): array_walk(Array, Object(Closure))
#8 /vagrant/source/laravel-excel/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/BootProviders.php(15): Illuminate\Foundation\Application->boot()
#9 /vagrant/source/laravel-excel/vendor/laravel/framework/src/Illuminate/Foundation/Application.php(181): Illuminate\Foundation\Bootstrap\BootProviders->bootstrap(Object(Illuminate\Foundation\Application))
#10 /vagrant/source/laravel-excel/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(195): Illuminate\Foundation\Application->bootstrapWith(Array)
#11 /vagrant/source/laravel-excel/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(92): Illuminate\Foundation\Console\Kernel->bootstrap()
#12 /vagrant/source/laravel-excel/artisan(36): Illuminate\Foundation\Console\Kernel->handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#13 {main}

php artisan ran sucessfully when I took out the maatwebsite references in config/app.php - so there must be more to do here but I don't know what.

A: Looks like the documentation is listing the wrong version. The 1.x branch is meant for Laravel 4.x. The GitHub page  provides a better guide for Laravel 5 users. Try changing the version to 2.* in your composer.json and re-run composer update. Add the correct references back to your app.php you should be able to run php artisan without errors.
The App::make('excel') command should also work after that.


text:
Q: Match housenumbers on buildings (special case of point-in-polygon-test) Task with example
I'm working with geodata (country-size) from openstreetmap. Buildings are often polygons without housenumbers and a single point with the housenumber is placed within the polygon of the building. Buildings may have multiple housenumbers.
I want to match the housenumbers to the polygons of the buildings.

Simple solution
Foreach housenumber perform a point-in-polygon-test with each building-polygon.
Problem
Way too slow for about 50,000,000 buildings and 10,000,000 address-points.
Idea
Build and index for the building-polygons to accelerate the search for the surrounding polygon for each housenumber-point.
Question
What index or strategy would you recommend for this polygon-structure? The polygons never overlap and the area is sparsly covered.

This is a duplicate from stackoverflow.com. It was recommended to post the question here.

A: I have the same problem in my mapping software. I am not sure if this is helpful, so forgive me if it doesn't address your actual difficulty, but what I do when searching for addresses is a form of lazy evaluation. I find all the building polygons and address points near a desired street after searching for the street, so there will only be a few hundred, then match up points with polygons.


text:
Q: Memory leak on Liferay 6.2 migration I've migrated a Liferay 6.2-CE-GA2 server from Liferay 6.1.1-ce-ga2.
I made a few changes in custom hooks and themes to addapt to the new version.
On locale I have never had a problem with memory nor with the 6.1 version, but once in production, server runs out of memory in a few hours.
I tried to adjust heap parameters and increasing server memory (from 2GB to 3GB) but it seems that the heap keeps growking slowly but non-stopping, until I get an OutOfMemory: Java heap space or, if I grant bigger limits to the heap, system runs out of memory.
I've been some days studying catalina.out, trying to minimize warnings and errors and this is the only interesting things I've seen  during a shutdown-reboot process (I replaced all domain names on logs):
[on shutdown]
WARN: The method class org.apache.commons.logging.impl.SLF4JLogFactory#release() was invoked.
WARN: Please see http://www.slf4j.org/codes.html#release for an explanation.

[...]

28-xul-2014 16:53:51 org.apache.catalina.loader.WebappClassLoader clearReferencesThreads
SEVERE: The web application [] appears to have started a thread named [org.python.google.common.base.internal.Finalizer] but has failed to stop it. This is very likely to create a memory leak.
28-xul-2014 16:53:51 org.apache.catalina.loader.WebappClassLoader clearReferencesThreads
SEVERE: The web application [] appears to have started a thread named [Thread-26] but has failed to stop it. This is very likely to create a memory leak.
28-xul-2014 16:53:51 org.apache.catalina.loader.WebappClassLoader clearReferencesThreads
SEVERE: The web application [] appears to have started a thread named [Thread-27] but has failed to stop it. This is very likely to create a memory leak.

[...]

16:55:40,517 ERROR [liferay/hot_deploy-1][JDBCExceptionReporter:82] Batch entry 0 insert into CalendarBooking (uuid_, groupId, companyId, userId, userName, createDate, modifiedDate, resourceBlockId, calendarId, calendarResourceId, parentCalendarBookingId, title, description, location, startTime, endTime, allDay, recurrence, firstReminder, firstReminderType, secondReminder, secondReminderType, status, statusByUserId, statusByUserName, statusDate, calendarBookingId) values ('985aac08-6457-484c-becb-2c4964805158', '10545', '10154', '10196', 'Carlos Ces', '2012-06-06 06:26:41.431000 +01:00:00', '2012-06-06 06:26:41.431000 +01:00:00', '0', '550617', '550571', '565201', 'Master Class de improvisación e tango contemporáneo con Jorge Retamoza', '
_    Master Class con Jorge Retamoza.
_
_    Organiza: Escola de Música de rrrrrr. Colabora: Concello de rrrrrr.
', 'Auditorio de rrrrrr', '1339246800000', '1339257600000', '0', '', '900000', 'email', '300000', 'email', '0', '10196', 'Carlos Ces', '2012-06-06 06:26:41.431000 +01:00:00', '565201') was aborted.  Call getNextException to see the cause. [Sanitized]
16:55:40,518 ERROR [liferay/hot_deploy-1][JDBCExceptionReporter:82] ERROR: duplicate key value violates unique constraint "ix_f4c61797"
16:55:40,536 ERROR [liferay/hot_deploy-1][SerialDestination:68] Unable to process message {destinationName=liferay/hot_deploy, response=null, responseDestinationName=null, responseId=null, payload=null, values={command=deploy, companyId=0, servletContextName=calendar-portlet}}
com.liferay.portal.kernel.messaging.MessageListenerException: com.liferay.portal.kernel.dao.orm.ORMException: org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
    at com.liferay.portal.kernel.messaging.BaseMessageListener.receive(BaseMessageListener.java:32)
    at com.liferay.portal.kernel.messaging.InvokerMessageListener.receive(InvokerMessageListener.java:72)
    at com.liferay.portal.kernel.messaging.SerialDestination$1.run(SerialDestination.java:65)
    at com.liferay.portal.kernel.concurrent.ThreadPoolExecutor$WorkerTask._runTask(ThreadPoolExecutor.java:682)
    at com.liferay.portal.kernel.concurrent.ThreadPoolExecutor$WorkerTask.run(ThreadPoolExecutor.java:593)
    at java.lang.Thread.run(Thread.java:636)
Caused by: com.liferay.portal.kernel.dao.orm.ORMException: org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
    [...]
    ... 5 more
Caused by: org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
    at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:96)
    at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
    [...]
    ... 62 more
Caused by: java.sql.BatchUpdateException: Batch entry 0 insert into CalendarBooking (uuid_, groupId, companyId, userId, userName, createDate, modifiedDate, resourceBlockId, calendarId, calendarResourceId, parentCalendarBookingId, title, description, location, startTime, endTime, allDay, recurrence, firstReminder, firstReminderType, secondReminder, secondReminderType, status, statusByUserId, statusByUserName, statusDate, calendarBookingId) values ('985aac08-6457-484c-becb-2c4964805158', '10545', '10154', '10196', 'Carlos Ces', '2012-06-06 06:26:41.431000 +01:00:00', '2012-06-06 06:26:41.431000 +01:00:00', '0', '550617', '550571', '565201', 'Master Class de improvisación e tango contemporáneo con Jorge Retamoza', '
_  Master Class con Jorge Retamoza.
_
_    Organiza: Escola de Música de rrrrrr. Colabora: Concello de rrrrrr.
', 'Auditorio de rrrrrr', '1339246800000', '1339257600000', '0', '', '900000', 'email', '300000', 'email', '0', '10196', 'Carlos Ces', '2012-06-06 06:26:41.431000 +01:00:00', '565201') was aborted.  Call getNextException to see the cause. [Sanitized]
    at org.postgresql.jdbc2.AbstractJdbc2Statement$BatchResultHandler.handleError(AbstractJdbc2Statement.java:2621)
    at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1837)
    [...]
    ... 68 more

Then server runs properly for 5 hours with some spared warnings each few minutes:
23:39:09,275 WARN  [ajp-apr-8009-exec-20][SecurityPortletContainerWrapper:623] Reject process action for http://www.rrrrrr.com/rrrrrr25n/notadeprensa on 56_INSTANCE_rk7ADlb9Ui2w
23:43:51,234 WARN  [ajp-apr-8009-exec-19][SecurityPortletContainerWrapper:623] Reject process action for http://www.rrrrrr.org/feiron/normas on 56_INSTANCE_jh6ewEPuvvjb
23:46:59,568 WARN  [ajp-apr-8009-exec-5][SecurityPortletContainerWrapper:623] Reject process action for http://www.rrrrrr.es/recursos-servizossociais on 56_INSTANCE_4eX2GzETiAQb
23:55:51,177 WARN  [ajp-apr-8009-exec-5][SecurityPortletContainerWrapper:623] Reject process action for http://www.rrrrrr.es/cans on 56_INSTANCE_4eX2GzETiAQb
00:00:13,713 WARN  [ajp-apr-8009-exec-24][SecurityPortletContainerWrapper:623] Reject process action for http://www.rrrrrr.es/rexistro on 56_INSTANCE_4eX2GzETiAQb
00:00:25,822 WARN  [ajp-apr-8009-exec-24][SecurityPortletContainerWrapper:623] Reject process action for http://www.rrrrrr.es/plenos on 110_INSTANCE_acNEFnslrX8c

And then memory problems begin. I post the first errors on log:
Exception in thread "http-apr-8080-exec-4" java.lang.OutOfMemoryError: Java heap space
01:00:01,223 ERROR [MemoryQuartzSchedulerEngineInstance_Worker-3][SimpleThreadPool:120] Error while executing the Runnable:
java.lang.OutOfMemoryError: Java heap space
Exception in thread "fileinstall-/home/rrrrrr/liferay-portal-6.2-ce-ga2/data/osgi/modules" Exception in thread "ajp-apr-8009-AsyncTimeout" Exception in thread "ajp-apr-8009-exec-21"   at java.util.LinkedHashMap.createEntry(LinkedHashMap.java:441)
    at java.util.LinkedHashMap.addEntry(LinkedHashMap.java:423)
    at java.util.HashMap.put(HashMap.java:402)
Exception in thread "ajp-apr-8009-exec-24"  at sun.util.resources.OpenListResourceBundle.loadLookup(OpenListResourceBundle.java:134)
Exception in thread "MemoryQuartzSchedulerEngineInstance_QuartzSchedulerThread" Exception in thread "ContainerBackgroundProcessor[StandardEngine[Catalina]]"    at sun.util.resources.OpenListResourceBundle.loadLookupTablesIfNecessary(OpenListResourceBundle.java:113)
Exception in thread "ajp-apr-8009-exec-35" Exception in thread "ajp-apr-8009-exec-36" Exception in thread "ajp-apr-8009-exec-29" Exception in thread "ajp-apr-8009-exec-37"     at sun.util.resources.OpenListResourceBundle.handleGetKeys(OpenListResourceBundle.java:91)
    at sun.util.LocaleServiceProviderPool.getLocalizedObjectImpl(LocaleServiceProviderPool.java:353)
Exception in thread "ajp-apr-8009-exec-33" Exception in thread "ajp-apr-8009-exec-34" Exception in thread "ajp-apr-8009-exec-30"    at sun.util.LocaleServiceProviderPool.getLocalizedObject(LocaleServiceProviderPool.java:284)
Exception in thread "ajp-apr-8009-exec-28" Exception in thread "ajp-apr-8009-exec-31" Exception in thread "http-apr-8080-AsyncTimeout" Exception in thread "http-apr-8080-exec-5" Exception in thread "http-apr-8080-exec-2" Exception in thread "liferay/scheduler_dispatch-3" Exception in thread "ajp-apr-8009-exec-41"  at sun.util.TimeZoneNameUtility.retrieveDisplayNames(TimeZoneNameUtility.java:111)
    at sun.util.TimeZoneNameUtility.retrieveDisplayNames(TimeZoneNameUtility.java:99)
    at java.util.TimeZone.getDisplayNames(TimeZone.java:418)
    at java.util.TimeZone.getDisplayName(TimeZone.java:369)
    at java.text.SimpleDateFormat.subFormat(SimpleDateFormat.java:1110)
    at java.text.SimpleDateFormat.format(SimpleDateFormat.java:899)
    at java.text.SimpleDateFormat.format(SimpleDateFormat.java:869)
    at org.apache.tomcat.util.http.ServerCookie.appendCookieValue(ServerCookie.java:254)
    at org.apache.catalina.connector.Response.generateCookieString(Response.java:1032)
    at org.apache.catalina.connector.Response.addCookie(Response.java:974)
    at org.apache.catalina.connector.ResponseFacade.addCookie(ResponseFacade.java:381)
    at javax.servlet.http.HttpServletResponseWrapper.addCookie(HttpServletResponseWrapper.java:58)
    at com.liferay.portal.kernel.servlet.HttpOnlyCookieServletResponse.addCookie(HttpOnlyCookieServletResponse.java:62)
    at javax.servlet.http.HttpServletResponseWrapper.addCookie(HttpServletResponseWrapper.java:58)
    at javax.servlet.http.HttpServletResponseWrapper.addCookie(HttpServletResponseWrapper.java:58)
    at javax.servlet.http.HttpServletResponseWrapper.addCookie(HttpServletResponseWrapper.java:58)
    at com.liferay.portal.kernel.servlet.MetaInfoCacheServletResponse.addCookie(MetaInfoCacheServletResponse.java:128)
    at javax.servlet.http.HttpServletResponseWrapper.addCookie(HttpServletResponseWrapper.java:58)
    at com.liferay.portal.kernel.servlet.MetaInfoCacheServletResponse.addCookie(MetaInfoCacheServletResponse.java:128)
01:02:56,362 ERROR [PersistedQuartzSchedulerEngineInstance_QuartzSchedulerThread][ErrorLogger:120] An error occurred while scanning for the next triggers to fire.
org.quartz.JobPersistenceException: Failed to obtain DB connection from data source 'ds': java.lang.OutOfMemoryError: Java heap space [See nested exception: java.lang.OutOfMemoryError: Java heap space]
    at org.quartz.impl.jdbcjobstore.JobStoreSupport.getConnection(JobStoreSupport.java:771)
    at org.quartz.impl.jdbcjobstore.JobStoreTX.getNonManagedTXConnection(JobStoreTX.java:71)
    at org.quartz.impl.jdbcjobstore.JobStoreSupport.executeInNonManagedTXLock(JobStoreSupport.java:3808)
    at org.quartz.impl.jdbcjobstore.JobStoreSupport.acquireNextTriggers(JobStoreSupport.java:2751)
    at org.quartz.core.QuartzSchedulerThread.run(QuartzSchedulerThread.java:264)
Caused by: java.lang.OutOfMemoryError: Java heap space
    at javax.servlet.http.HttpServletResponseWrapper.addCookie(HttpServletResponseWrapper.java:58)
    at com.liferay.portal.kernel.servlet.MetaInfoCacheServletResponse.addCookie(MetaInfoCacheServletResponse.java:128)
    at com.liferay.portal.kernel.util.CookieKeys.addCookie(CookieKeys.java:99)
    at com.liferay.portal.kernel.util.CookieKeys.addCookie(CookieKeys.java:63)
    at com.liferay.portal.language.LanguageImpl.updateCookie(LanguageImpl.java:751)
java.lang.OutOfMemoryError: Java heap space
java.lang.OutOfMemoryError: Java heap space
java.lang.OutOfMemoryError: Java heap space
java.lang.OutOfMemoryError: Java heap space
java.lang.OutOfMemoryError: Java heap space
01:03:00,917 ERROR [QuartzScheduler_PersistedQuartzSchedulerEngineInstance-NON_CLUSTERED_MisfireHandler][PortalJobStore:120] MisfireHandler: Error handling misfires: Unexpected runtime exception: Index: 0, Size: 0
org.quartz.JobPersistenceException: Unexpected runtime exception: Index: 0, Size: 0 [See nested exception: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0]
    at org.quartz.impl.jdbcjobstore.JobStoreSupport.doRecoverMisfires(JobStoreSupport.java:3200)
    at org.quartz.impl.jdbcjobstore.JobStoreSupport$MisfireHandler.manage(JobStoreSupport.java:3947)
    at org.quartz.impl.jdbcjobstore.JobStoreSupport$MisfireHandler.run(JobStoreSupport.java:3968)
Caused by: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
    at java.util.ArrayList.rangeCheck(ArrayList.java:571)
    at java.util.ArrayList.get(ArrayList.java:349)
    at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1689)
    at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:257)
    at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:512)
    at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:388)
    at org.postgresql.jdbc2.AbstractJdbc2Statement.executeQuery(AbstractJdbc2Statement.java:273)
    at org.quartz.impl.jdbcjobstore.StdJDBCDelegate.countMisfiredTriggersInState(StdJDBCDelegate.java:416)
    at org.quartz.impl.jdbcjobstore.JobStoreSupport.doRecoverMisfires(JobStoreSupport.java:3176)
    ... 2 more
java.lang.OutOfMemoryError: Java heap space
java.lang.OutOfMemoryError: Java heap space
Exception in thread "fileinstall-/home/rrrrrr/liferay-portal-6.2-ce-ga2/data/osgi/portal" java.lang.OutOfMemoryError: Java heap space
java.lang.OutOfMemoryError: Java heap space
java.lang.OutOfMemoryError: Java heap space
java.lang.OutOfMemoryError: Java heap space
java.lang.OutOfMemoryError: Java heap space
java.lang.OutOfMemoryError: Java heap space
java.lang.OutOfMemoryError: Java heap space
java.lang.OutOfMemoryError: Java heap space
java.lang.OutOfMemoryError: Java heap space
java.lang.OutOfMemoryError: Java heap space
java.lang.OutOfMemoryError: Java heap space
java.lang.OutOfMemoryError: Java heap space

I have some custom themes and hooks that I now post. I wonder there has to be a memory leak anywhere on them, but i cannot find it.
First, I have a custom Application Display Templatefor Blogs:

 #foreach ($entry in $entries)

  #set ($viewUrl = $currentURL.replaceFirst("\?.*$","") + "/-/blogs/" + $entry.getUrlTitle())
  #set($img_ini=$entry.content.indexOf("= 0)
   #set($img_end=$entry.content.indexOf(">",$img_ini) + 1)
   #set($first_img_tag= $entry.content.substring($img_ini, $img_end))

   #set($first_img_url=$first_img_tag.replaceFirst("= 0)

   #end

    $entry.title

     $dateFormats.getSimpleDateFormat("dd MMMMM yyyy HH:mm", $locale).format($entry.displayDate)
      #set($plain_content = $entry.content.replaceAll("</?[^>]+/?>", ""))
      #set($res_length = 240)
      #if ($res_length > $plain_content.length())
       #set($res_length = $plain_content.length())
      #end

       $plain_content.substring(0,$res_length) ...

 #end

Custom hook Blogshome overrides some jsps from blogs_aggregator.
view_entries.jspf
<c:choose>
    <c:when test="<%= results.isEmpty() %>">
        <liferay-ui:message key="there-are-no-blogs" />

    </c:when>
    <c:otherwise>

        <%

        if (displayStyle.startsWith("extract-side-events")) {

            List<BlogsEntry> eventsColumn = new ArrayList<BlogsEntry>();
            List<BlogsEntry> mainColumn = new ArrayList<BlogsEntry>();

            for (int i=0; i< results.size(); i++) {
                BlogsEntry entry = (BlogsEntry) results.get(i);

                if (entry.getDisplayDate().after(new Date())) {
                    searchContainer.setTotal(searchContainer.getTotal() - 1);
                    continue;
                }

                boolean isEvent = ((Boolean) entry.getExpandoBridge().getAttribute("evento"));

                if (isEvent) eventsColumn.add(entry);
                mainColumn.add(entry); /* change: add ALL to mainColumn; events are duplicated on side */
            }

                        /* reorder eventsColumn */

                        TreeMap<Date, BlogsEntry> next= new TreeMap<Date, BlogsEntry>();
            List<BlogsEntry> toRemove = new ArrayList<BlogsEntry>();

                for (BlogsEntry entry: eventsColumn) {
                                Date ini = (Date) entry.getExpandoBridge().getAttribute("evento-inicio");
                                Date end = (Date) entry.getExpandoBridge().getAttribute("evento-remate");
                                Date now = new Date();

                                if (ini.before(now) && (end.after(now))) {
                    next.put(end, entry);
                    /* mainColumn.remove(entry); */
                } else if (end.before(now)) {
                    toRemove.add(entry);
                } else {
                    next.put(ini, entry);
                    /* mainColumn.remove(entry); */
                }
                        }
            eventsColumn.removeAll(toRemove);

            /* third rearrangement: current & next are visible; past are pushed to mainColumn */
            /* current ordered by end; next ordered by ini */

                        ArrayList<BlogsEntry> lNext = new ArrayList<BlogsEntry>(next.values());

                        %>

            <%
                if (!lNext.isEmpty()) {

                                for (BlogsEntry entry: lNext) {
                                        %>

                                                <%@ include file="/html/portlet/blogs_aggregator/view_entry_extract.jspf" %>

                                        <%
                                }
                }
            %>

<%--

                    <button type="button" class="btn btn-default btn-large"
                    onclick="document.getElementById('events-showdown').style.right =50">

                    </button>

--%>

 <%

                        %>
 <%
                        for (BlogsEntry entry: mainColumn) {
                                    %>
                                        <%@ include file="/html/portlet/blogs_aggregator/view_entry_extract.jspf" %>
                                    <%
                        }
                        %>
 <%

                /* original blogs styles */
                } else {

            for (int i = 0; i < results.size(); i++) {
                BlogsEntry entry = (BlogsEntry)results.get(i);

                if (entry.getDisplayDate().after(new Date())) {
                    searchContainer.setTotal(searchContainer.getTotal() - 1);
                    continue;
                }
            %>
                <%@ include file="/html/portlet/blogs_aggregator/view_entry_content.jspf" %>
            <%
            }
        }
        %>

    </c:otherwise>
</c:choose>

<c:if test="<%= enableRssSubscription %>">

    <%
    StringBundler rssURLParams = new StringBundler();

    if (selectionMethod.equals("users")) {
        if (organizationId > 0) {
            rssURLParams.append("&organizationId=");
            rssURLParams.append(organizationId);
        }
        else {
            rssURLParams.append("&companyId=");
            rssURLParams.append(company.getCompanyId());
        }
    }
    else {
        rssURLParams.append("&groupId=");
        rssURLParams.append(themeDisplay.getScopeGroupId());
    }
    %>

        <liferay-ui:icon
            image="rss"
            label="<%= true %>"
            method="get"
            target="_blank"
            url='<%= themeDisplay.getPathMain() + "/blogs_aggregator/rss?p_l_id=" + plid + rssURLParams %>'
        />

</c:if>

<c:if test="<%= !results.isEmpty() %>">

        <liferay-ui:search-paginator searchContainer="<%= searchContainer %>" />

</c:if>

view_entry_extract.jspf
<c:if test="<%= BlogsEntryPermission.contains(permissionChecker, entry, ActionKeys.VIEW) %>">

        <%
        PortletURL showBlogEntryURL = renderResponse.createRenderURL();

        showBlogEntryURL.setParameter("struts_action", "/blogs_aggregator/view_entry");
        showBlogEntryURL.setParameter("entryId", String.valueOf(entry.getEntryId()));

        StringBundler sb = new StringBundler(8);

        StringBundler ab = new StringBundler(8);
        ab.append(themeDisplay.getURLPortal());
        ab.append(GroupLocalServiceUtil.getGroup(entry.getGroupId()).getFriendlyURL());
        ab.append("/-/blogs/");
        ab.append(entry.getUrlTitle());

        String viewEntryURL = ab.toString();

        sb.append("&showAllEntries=1");

        String viewAllEntriesURL = sb.toString();

        User user2 = UserLocalServiceUtil.getUserById(entry.getUserId());
        %>

            <c:if test='<%= (Boolean) entry.getExpandoBridge().getAttribute("evento")%>'>

        <%

                        Calendar iniDate = com.liferay.portal.kernel.util.CalendarFactoryUtil.getCalendar(timeZone);
                        Calendar endDate = com.liferay.portal.kernel.util.CalendarFactoryUtil.getCalendar(timeZone);
                        iniDate.setTime(((Date) entry.getExpandoBridge().getAttribute("evento-inicio")));
                        endDate.setTime(((Date) entry.getExpandoBridge().getAttribute("evento-remate")));
                                                                            boolean sameDay = false;

                        if ((iniDate.get(Calendar.DAY_OF_YEAR) == endDate.get(Calendar.DAY_OF_YEAR))
                         && (iniDate.get(Calendar.YEAR) == endDate.get(Calendar.YEAR)))
                sameDay = true;

            String diaDaSemana = (new SimpleDateFormat("EEEE", locale)).format(iniDate.getTime());
            String numeroDeDia = (new SimpleDateFormat("d", locale)).format(iniDate.getTime());
            String mes = (new SimpleDateFormat("MMMM", locale)).format(iniDate.getTime());
//          String hora = (new SimpleDateFormat("HH:mm", locale)).format(iniDate.getTime()) + "h";
            String hora = (iniDate.get(Calendar.HOUR_OF_DAY) +  new SimpleDateFormat(":mm", locale).format(iniDate.getTime()) + "h");

            String numeroDeDiaFin = StringPool.BLANK;
            String mesFin = StringPool.BLANK;
            if (!sameDay) {
                numeroDeDiaFin = (new SimpleDateFormat("d", locale)).format(endDate.getTime());
                mesFin = (new SimpleDateFormat("MMMM", locale)).format(endDate.getTime());
            }

        %>

        <%
            if (sameDay) {
        %>

                <%= numeroDeDia %>

<%= mes  %>

<%= diaDaSemana  %>

<%= hora  %>

        <%
            } else {
        %>

                <%= numeroDeDia %>

<%= mes  %>

<%= diaDaSemana  %>

<liferay-ui:message key="rrrrrr.events.until" /> <%= numeroDeDiaFin %>
                            <liferay-ui:message key="rrrrrr.events.of" /> <%= mesFin  %>

        <%

            }
        %>

            </c:if>

            <%

            String resumeText = StringPool.BLANK;
            String resumeImage = StringPool.BLANK;
            int extLength = 240;

            if (entry.isSmallImage()) {
                if (Validator.isNotNull(entry.getSmallImageURL()))
                    resumeImage = entry.getSmallImageURL();
                else
                    resumeImage = themeDisplay.getPathImage() + "/journal/article?img_id=" + entry.getSmallImageId() + "&t=" + WebServerServletTokenUtil.getToken(entry.getSmallImageId()) ;
                resumeImage.trim();
            }

            /* if no small image, extract first */
            if ((resumeImage == null) || (resumeImage.isEmpty())) {

                java.util.regex.Pattern p = java.util.regex.Pattern.compile("src=['\"]([^'\"]+)['\"]");
                java.util.regex.Matcher m = p.matcher(entry.getContent());
                if (m.find())
                    resumeImage = m.group().substring(5, m.group().length() -1);
            }

            resumeText = HtmlUtil.stripHtml(entry.getDescription());
            resumeText.trim();

            /* if no resume description, extract text */
            if ((resumeText == null) || (resumeText.isEmpty())) {
                resumeText = HtmlUtil.escape(StringUtil.shorten(HtmlUtil.extractText(entry.getContent()), extLength));
            }

            %>

                <a href="<%= viewEntryURL %>"  style="background-image: url('<%= HtmlUtil.escape(resumeImage) %>')">
                    <img class="asset-small-image" src="<%= HtmlUtil.escape(resumeImage) %>"/>

                <a href="<%= viewEntryURL %>"><%= HtmlUtil.escape(entry.getTitle()) %>

                <a href="<%= viewEntryURL %>">
                    <%= GroupLocalServiceUtil.getGroup(entry.getGroupId()).getDescriptiveName() %>
                    <%= dateFormatDateTime.format(entry.getDisplayDate()) %>
                    <%= " " + resumeText %>

I am unable to guess any memory leak there, but there has to be! I've spent few weeks trying to find a bug (deactivating hooks to see if errors persisted) but couldn't come to a clue.
Does anybody see something potentially dangerous in my code? Wich other way can I trace Java memory usage to fetch for leaks?

A: That is really a messy code...
First do not use scriplets use servlets.
Do not throw that amount of code at as identify your problem and then narrow down your question so we can answer it.
 You can make use of MAT in eclipse take stack dump and analyze what objects take up most amount of memory and therefore what is a cause of the memory leak.
 Why are you mixing JSTL with scriplets? JSTL is design to work with servlets.
You mix up business logic with presentation layer it is why scriplets are strongly not recommended. Your code is not readable messy come back when you change it to scriplets and then I would be able to give you some answers.

A: The symptoms you describe fit with the memory leak. In case you suspect one, give Plumbr a try to find the cause and solve it. In case you just need more information about the java.lang.OutOfMemoryError: Java heap space you are facing, see the informational post about the error, possible causes and solution means.


text:
Q: Installing an EV certificate straight into the cPanel I just bought an EV SSL certificate from geotrust and I was wondering if its possible to install it straight from the cPanel (ssl category). The single problem I'm having with that is that its asking me a private key that isn't mentioned in the e-mail where I received the certificate.
I'll appreciate any advices , thank you!


text:
Q: Change root view controller of AppDelegate cause an exception of UIViewControllerHierarchyInconsistency Outside the AppDelegate, I want to change the rootViewController of it. In other words, I want to put a new navigation controller on top of what I had before in my window and then push the new controller in this navigation controller:
func JumpToPage(_ controller: UIViewController) {
        guard let rootController = AppDelegate.shared?.presentationViewController else {
            return
        }
        let navigationController = UINavigationController(rootViewController: rootController)
        navigationController.pushViewController(controller, animated: true)
        AppDelegate.shared?.window?.rootViewController = navigationController
    }
}

But this function cause the app to crash with the following error message:
Terminating app due to uncaught exception 'UIViewControllerHierarchyInconsistency',
    reason: 'adding a root view controller <MyExampleController> as a child of view controller:<UINavigationController>'

How should I solve it?

A: Change from
let navigationController = UINavigationController(rootViewController: rootController)

To
let navigationController = UINavigationController(rootViewController: controller)

Update
func JumpToPage(_ controller: UIViewController) {
    guard let rootController = AppDelegate.shared?.presentationViewController else {
        return
    }
    let navigationController = UINavigationController(rootViewController: controller)
    AppDelegate.shared?.window?.rootViewController = navigationController
}

A: Instead of trying to replace navigation controller, I'm replacing root VC in the initial navigation controller as follows.
In AppDelegate:
func application(_ application: UIApplication, didFinishLaunchingWithOptions ...) {
    let storyboard = UIStoryboard(name: "FirstVC", bundle: Bundle.main)
    let firstViewController = instantiateInitialViewController()! as! FirstViewController
    navigationController = UINavigationController(rootViewController: firstViewController)
    window = UIWindow(frame: UIScreen.main.bounds)
    window!.rootViewController = navigationController
    window!.makeKeyAndVisible()
    return true
}

Then, I change root VC w/in FirstViewController as follows:
func someFuncInFirstVC() {
    let allControllers = NSMutableArray(array: self.navigationController!.viewControllers)
    allControllers.removeObject(at: allControllers.count - 1)  // remove root VC, count should be one...
    let secondViewController = SecondViewController()
    allControllers.add(secondViewController as AnyObject)  // this becomes new root VC since nav stack is empty now
    navigationController!.setViewControllers(allControllers as [AnyObject] as! [UIViewController], animated: true)
}


text:
Q: Including weather report in website using XSLT I want to include the weather report at ftp://ftp.knmi.nl/pub_weerberichten/basisverwachting.xml to my website.
The specific element I want to include is located at:
report/data/location/block

where block contains:
<field_id>Verwachting</field_id>

How do I do this using simple XSL Transformations?
Update:
I have the following XSL Transformation however it has no results:
<xsl:variable name="weerknmi" select="document('ftp://ftp.knmi.nl/pub_weerberichten/basisverwachting.xml')/report/data/location"/>
<xsl:value-of select="$weerknmi/block[field_id = 'Verwachting']/field_content"/>

A: A simple XPath expression will do this:
report/data/location/block[field_id = 'Verwachting']/field_content
If you want to use this in XSLT, you can just do:
<xsl:value-of select="document('ftp://ftp.knmi.nl/pub_weerberichten/basisverwachting.xml')/report/data/location/block[field_id = 'Verwachting']/field_content" />
I might have the syntax slightly wrong, I don't often use document() and I can't easily check it at the moment, but you get the idea.

A: Use:
report/data/location/block[field_id='Verwachting']/field_content

Here is a complete and really short XSLT transformation:
<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:variable name="vDoc" select=
 "document('ftp://ftp.knmi.nl/pub_weerberichten/basisverwachting.xml')"/>

 <xsl:template match="/">
  <xsl:apply-templates select="$vDoc" mode="doc"/>
 </xsl:template>

 <xsl:template match="/" mode="doc">
     <xsl:value-of select=
      "report/data/location/block[field_id='Verwachting']/field_content"/>
 </xsl:template>
</xsl:stylesheet>

when applied to any document (not used), the transformation dynamically obtains the XML document located ar ftp://ftp.knmi.nl/pub_weerberichten/basisverwachting.xml, processes it and the wanted result is produced:
Vrij veel bewolking en vooral in het noorden af en toe regen of motregen. In het zuiden blijft het overwegend droog. De middagtemperatuur loopt uiteen van een graad of 14 in het Waddengebied tot 19 graden in het zuidoosten. De zuidwestelijke wind is matig tot vrij krachtig. Aan de kust is de wind krachtig of hard,  6 tot 7.
Komende nacht is er vrij veel bewolking met in het noorden en midden mogelijk nog lichte regen. De minimumtemperatuur ligt rond een graad of 11. De zuidwestelijke wind neemt af naar zwak tot matig, rond kracht 3. Aan de kust is de wind af en toe vrij krachtig, 5.
Morgen overdag breekt op steeds meer plaatsen de zon door en is het vrijwel overal droog. De middagtemperatuur loopt uiteen van een graad of 16 in het noordwestelijk kustgebied tot 23 graden in het zuidoosten. De zuidwestelijke wind trekt weer aan en wordt matig tot vrij krachtig, kracht 4 of 5, aan de kust en op het IJsselmeer krachtig tot hard, 6 of 7 Bft. 's Avonds neemt de wind af. (Bron: KNMI)


text:
Q: Python scope when assignment never performed So I get that
x = 5
def f():
    print(x)

f()
print(x)

gives back 5 and 5.
I also get that
x = 5
def f():
    x = 7
    print(x)

f()
print(x)

gives back 7 and 5.
What is wrong with the following?
x = 5
def f():
    if False:
        x = 7
        print(x)
    else:
        print(x)

f()
print(x)

I would guess that since the x=7 never happens I should get 5 and 5 again. Instead I get
UnboundLocalError: local variable 'x' referenced before assignment
Does python regard x as a local variable because in this indented block there is an assignment expression regardless if it is executed or not? What is the rule exactly?

A: When the function is defined python interprets x as a local variable since it's assigned inside the body of the function. During runtime, when you go into the else clause, the interpreter looks for a local variable x, which is unassigned.
If you want both x to refer to the same variable, you can add global x inside the body of the function, before its assignment to essentially tell python when I call x I'll be referring to the global-scope x.

A: If a name binding operation occurs anywhere within a code block, all uses of the name within the block are treated as references to the current block. This can lead to errors when a name is used within a block before it is bound. This rule is subtle. Python lacks declarations and allows name binding operations to occur anywhere within a code block. The local variables of a code block can be determined by scanning the entire text of the block for name binding operations.

A: You need to use global in your function f() like so:
x = 5
def f():
    global x
    if False:
        x = 7
        print(x)
    else:
        print(x)

f()
print(x)


text:
Q: How can I use my Google API email @developer.gserviceaccount.com This is simple question for those who know.
I have Google API registered access and as part of it
I was given few email addresses (@developer.gserviceaccount.com),
One per each type of access.
It seems that the main purpose of those email addresses, is to be a distinguishing ids.
My question is if its possible to use those email addresses as real mailboxes?

A: No, they are not destined to be used as email addresses, think of them more as user_id's for different purposes.
Here you can see an example os the @developer.gserviceaccount.com
I guess I'm a bit late for this answer but I am currently facing some issues with this subject so I think it might be useful to someone.


text:
Q: Prove that the only continuously differentiable functions of one variable satisfying the mean value property are lines. Define a function $f$ to have the mean value property if $f(\frac{s+t}{2}) = \frac{f(s)}{2} + \frac{f(t)}{2}$ for all $s$ and $t$ in $\mathbb{R}$. I'm trying to show that if $f$ is continuously differentiable and has the mean value property then it is of the form $f(x) = ax + b$. Using the limit of the difference quotient I was able to show that $2f'(x) - f'(2x) = f'(0)$ but this doesn't show that the derivative is constant as if $f'(x) = x$ then this equation would also be satisfied. Any ideas?

A: Differentiating the equation with respect to $t$ gives you $\frac{1}{2}f'\left(\frac{s+t}{2}\right) = \frac{1}{2} f'(t)$, or $f'\left(\frac{s+t}{2}\right) = f'(t)$. On the other hand, differentiating with respect to $s$  gives $f'\left(\frac{s+t}{2}\right) = f'(s)$. Hence $f'(s)=f'(t)$. Since $s,t$ are arbitrary, we conclude $f'$ is constant.