vendredi 11 septembre 2015

JMeter: Is Windows not capable of handling a hundreds of thousands of users in single system

My linux (i5 Processor, RAM: 16GB) machine is able to handle 100k users easily however same does not happen with Windows 8 (i7 Processor 2600 @ CPU 3.40GHz, RAM: 32GB) and thread creation stops after specific amount of thread is created somewhere around 20k in JMeter.

Is there any reason as why Windows in not able to handle huge number of users?



via Chebli Mohamed

SQL Server insert missing record with select distinct or left join

I have a table where is some case we are missing the location record for location = 'WHS1'. You will notice the bottom 2 "TCODE's" do not have a location = WHS1 record

I was thinking of doing a select distinct on TCODE InvYear and to get unique records then checking to see if the Location 'WHS1' NOT Exist.

I'm very green at this that you for any help

TCODE   InvYear Location    StartingInv Adjustments Damages EndingInv
NY530-1 2015    BRX         625         NULL        NULL    709
NY530-1 2015    LAN         365         NULL        NULL    365
NY530-1 2015    WHS1        432         NULL        NULL    442
NY530-2 2015    BRX         309         NULL        NULL    413
NY530-2 2015    LAN         94          NULL        NULL    96
NY530-2 2015    WHS1        1310        NULL        NULL    1344
NY547-1 2015    BRX         0           NULL        NULL    0
NY547-2 2015    BRX         0           NULL        NULL    0



via Chebli Mohamed

Echo issue during audio streaming using native RTP lib in Android

I'm working on an Android app, which streams live audio from mic to the vlc using native android RTP lib (using AudioStream and AudioGroup) with in the same room on the speaker(it is conference app, so MIC and Speaker both will be in same room) the problem is, it is creating a lot of ECHO, i know the android have native Android API AcousticEchoCanceler and also NoiseSuppressor API but these APIs work with AudioRecord or MediaRecorder... I need some hep, how can i remove Echo using these native APIs with RTP lib OR Anyone can suggest me any 3rd party lib which streams live audio with built-in Echo canceler..

Here is the link you can see, they are streaming live audio in the same room, without any echo, we are working on the same concept of live streaming...

Thanks in advance...!



via Chebli Mohamed

Find file names containing value stored in a string variable or object and move that file

Hi Please help a Powershell newbie with a seemingly simple task which is doing my head in.

I have a folder containing a large list of hofixes. Each hotfix filename contains the KB number such as KB2993958 similar to Windows8.1-KB2957189-x64.msu

I'm trying to troubleshoot an issue caused by the installation of a particular hotfix. I have narrowed the selection down to about 50 possible hotfixes, far less than how many are contained in the master folder. I want to install 10 hotfixes at a time to try and isolate the issue.

I have the list of 50 hotfixes I need to install either in a get-hotfix object or probably converted to a string in a variable.

So I want to compare the Kb numbers listed in my object / variable against the file names in the master folder and if the file name contains any of the KB number stored in my variable then move this file into a folder, ready for installation. Seems simple. Can't work it out.

Please help. Feeling a bit dumb right now :( Many Thanks!!



via Chebli Mohamed

Emacs + windowed mode + non-ascii characters + utf8 file encoding

I've developed a little mode for emacs which applies enriched format (colors, different fonts, etc) to some pieces of text using regular expressions (as markdown does).

In some of these regular expressions, there's french and spanish characters (like ``), and unicode characters (like ☛). Usually I use emacs in no windows mode (-nw), but to edit files which uses my mode, I open emacs in windowed mode, and I've realized that in windowed mode I can't write non-ascii characters, like ` or ☛. So, I can't use these special patterns (files are utf8).

If I execute describe-input-method in emacs, it says that no input method is specified, both in windowed and nw mode. However, it's not crazy to say the input method is different in windows and nw mode, since in boths modes the characters I'm able to write are different; or have I misunderstood what the meaning of input mode in emacs is?



via Chebli Mohamed

Entities tracking in Entity Framework

I started reading more about EF. I believed that entities are tracked as long as the context is in scope. But when I try the code below I get different results. I'm sure I misunderstood what I read. Can you please explain.

Destination canyon;
DbEntityEntry<Destination> entry;
using (var context = new BreakAwayContext())
      {
          canyon = (from d in context.Destinations.Include(d => d.Lodgings)
                    where d.Name == "Grand Canyon"
                    select d).Single();
          entry = context.Entry<Destination>(canyon);
      }
Console.WriteLine(entry.State); //Unchanged
canyon.TravelWarnings = "Carry enough water!";
Console.WriteLine(entry.State); //Modified



via Chebli Mohamed

Java3D move individual Point3f in shape3D consisting of big Point3f array

I have the following code that paints 4 points in a canvas3D window

public final class energon extends JPanel {    

    int s = 0, count = 0;

    public energon() {
        setLayout(new BorderLayout());
        GraphicsConfiguration gc=SimpleUniverse.getPreferredConfiguration();
        Canvas3D canvas3D = new Canvas3D(gc);//See the added gc? this is a preferred config
        add("Center", canvas3D);

        BranchGroup scene = createSceneGraph();
        scene.compile();

        // SimpleUniverse is a Convenience Utility class
        SimpleUniverse simpleU = new SimpleUniverse(canvas3D);


        // This moves the ViewPlatform back a bit so the
        // objects in the scene can be viewed.
        simpleU.getViewingPlatform().setNominalViewingTransform();

        simpleU.addBranchGraph(scene);
    }
    public BranchGroup createSceneGraph() {
        BranchGroup lineGroup = new BranchGroup();
        Appearance app = new Appearance();
        ColoringAttributes ca = new ColoringAttributes(new Color3f(204.0f, 204.0f,          204.0f), ColoringAttributes.SHADE_FLAT);
        app.setColoringAttributes(ca);

        Point3f[] plaPts = new Point3f[4];

        for (int i = 0; i < 2; i++) {
            for (int j = 0; j <2; j++) {
                plaPts[count] = new Point3f(i/10.0f,j/10.0f,0);
                //Look up line, i and j are divided by 10.0f to be able to
                //see the points inside the view screen
                count++;
            }
        }
        PointArray pla = new PointArray(4, GeometryArray.COORDINATES);
        pla.setCoordinates(0, plaPts);
        Shape3D plShape = new Shape3D(pla, app);
        TransformGroup objRotate = new TransformGroup();
        objRotate.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
        objRotate.addChild(plShape);
        lineGroup.addChild(objRotate);
        return lineGroup;
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.add(new JScrollPane(new energon()));
        frame.setSize(300, 300);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

Now i want to add a timertask that regularly updates the position of one of the points in the plaPts Point3f array. However, when i call plaPts[1].setX(2), nothing happens on the screen, they remain in the same position.

Do you have to have each point in a separate TransformGroup (consisting of a shape3D with a Point3f array of size 1) for this to be possible? I'm later going to use 100000 points, is it bad for performance if they all are in separate TransformGroups? Is there an easier way of doing this? Something like shape3D.repaint(), that automatically updates the position of the points based on the new values in plaPTS.



via Chebli Mohamed

Using scala.Future with Java 8 lambdas

The scala Future class has several methods that are based on functional programming. When called from Java, it looks like using lambdas from Java 8 would be a natural fit.

However, when I try to actually use that, I run into several problems. The following code does not compile

someScalaFuture.map(val -> Math.sqrt(val)).
       map(val -> val + 3); 

because map takes an ExecutionContext as an implicit argument. In Scala, you can (usually) ignore that, but it needs to be passed in explicitly in Java.

someScalaFuture.map(val -> Math.sqrt(val),
                    ec).
       map(val -> val + 3,
           ec);

This fails with this error:

error: method map in interface Future<T> cannot be applied to given types;
[ERROR] val),ExecutionContextExecutor
  reason: cannot infer type-variable(s) S
    (argument mismatch; Function1 is not a functional interface
      multiple non-overriding abstract methods found in interface Function1)
  where S,T are type-variables:
    S extends Object declared in method <S>map(Function1<T,S>,ExecutionContext)
    T extends Object declared in interface Future 

If I actually create an anonymous class extending Function1 and implement apply as such:

    someScalaFuture.map(new Function1<Double, Double>() {
            public double apply(double val) { return Math.sqrt(val); }
        },
        ec).
        map(val -> val + 3,
            ec);

I get an error that

error: <anonymous com.example.MyTestClass$1> is not abstract and does not override abstract method apply$mcVJ$sp(long) in Function1

I have not tried implementing that method (and am not sure if you can even implement a method with dollar signs in the middle of the name), but this looks like I am starting to wonder into the details of Scala implementations.

Am I going down a feasible path? Is there a reasonable way to use lambdas in this way? If there is a library that makes this work, that is an acceptable solution. Ideally, something like

import static org.thirdparty.MakeLambdasWork.wrap;
...
   wrap(someScalaFuture).map(val -> Math.sqrt(val)).
         map(val -> val + 3);



via Chebli Mohamed

Compose variadic template argument by transforming them

I have a simple situation which probably require a complex way to be solved but I'm unsure of it.

Basically I have this object which encapsulated a member function:

template<class T, typename R, typename... ARGS>
class MemberFunction
{
private:
  using function_type = R (T::*)(ARGS...);

  function_type function;

public:
  MemberFunction(function_type function) : function(function) { }

  void call(T* object, ARGS&&... args)
  {
    (object->*function)(args...);
  }   
};

This can be used easily

MemberFunction<Foo, int, int, int> function(&Foo::add)
Foo foo;
int res = function.call(&foo, 10,20)

The problem is that I would like to call it by passing through a custom environment which uses a stack of values to operate this method, this translates to the following code:

int arg2 = stack.pop().as<int>();
int arg1 = stack.pop().as<int>();
Foo* object = stack.pop().as<Foo*>();
int ret = function.call(object, arg1, arg2);
stack.push(Value(int));

This is easy to do directly in code but I'd like to find a way to encapsulate this behavior directly into MemberFunction class by exposing a single void call(Stack& stack) method which does the work for me to obtain something like:

MemberFunction<Foo, int, int, int> function(&Foo::add);
Stack stack;
stack.push(Value(new Foo());
stack.push(10);
stack.push(20);
function.call(stack);
assert(stack.pop().as<int>() == Foo{}.add(10,20));

But since I'm new to variadic templates I don't know how could I do in efficiently and elegantly.



via Chebli Mohamed

Navigating through Typescript references in Webstorm

We are using Typescript with Intellij Webstorm IDE.

The situation is we use ES6 import syntax and tsc compiler 1.5.3 (set as custom compiler in Webstorm also with flag --module commonjs)

The problem is it is imposible to click through (navigate to) method from module (file)

// app.ts

import * as myModule from 'myModule';

myModule.myFunction();



// myModule.ts

export function myFunction() {
    // implementation
}

When I click on .myFunction() in app.ts I expect to navigate to myModule.ts file but this doesn't happen?



via Chebli Mohamed

Why do I need a default contructor o Point class in this case?

I have this simple example of using a functor in C++:

#include <memory>
#include <ostream>
#include <iostream>

template <typename T>
struct Point {
    T x, y;

    Point(T x, T y) : x(x), y(y){};
    Point(){};

    Point<T> operator+(const Point<T>& other) {
        this->x += other.x;
        this->y += other.y;
        return *this;
    }
};

template <typename T>
struct AddSome {
    AddSome(){};
    AddSome(T* what) { add_what = (T)*what; };
    AddSome(T what) : add_what(what){};
    T operator()(T to_what) {
        if (ptr) {
            return to_what + add_what;
        }
        return to_what + add_what;
    };

   private:
    std::shared_ptr<T> ptr;
    T add_what;
};

int main(int argc, char* argv[]) {
    Point<int>* pt = new Point<int>(5, 6);

    AddSome<Point<int>> adder5(pt);
    Point<int> test = adder5(*pt);

    std::cout << test.x << " " << test.y << std::endl;

    return 0;
}

In the version above it works very well but it doesn't work at all if I delete the default constructor of the Point class.

What does the compiler need this constructor for?



via Chebli Mohamed

Indoor positioning System

I would like to develop an android app acting like an indoor positioning system.But I am stuck ,I don't know where to begin.I would like to know what is the best technology to use. I also want to know if there's a way to build this app based on BLE technology with beacons detection. Any information provided will be very helpful and thank you in advance.



via Chebli Mohamed

Oracle numeric string column and indexing

I have a numeric string column in oracle with or without leading zeros samples:

00000000056
5755
0123938784579343
00000000333  
984454  

The issue is that partial Search operations using like are very slow

select account_number from accounts where account_number like %57%

one solution is to restrict the search to exact match only and add an additional integer column that will represent the numeric value for exact matches.
At this point I am not sure we can add an additional column,
Do you guys have any other ideas?

Is it possible to tell Oracle to index the numeric string column as an integer value so we can do exact numeric match on it?

for example query on value :00000000333
will be:

select account_number from accounts where account_number = '333'

While ignoring the leading zeros.
I can use regex_like and ignore them, but i am afraid its going to be slow.



via Chebli Mohamed

Configure connection string to SQL Server Express to work with every computer/server name

How do I have to configure my SQL Server Express connection string that the server attribute accepts the computername where the SQL Server is running aka the current machine:

<connectionStrings>
    <add name="MyDbConn1" 
         connectionString="Server=.\SQLEXPRESS;Database=MyDb;Trusted_Connection=Yes;"/>       
</connectionStrings>

I have seen somewhere a configuration like the above where the server attribute has the .\SQLEXPRESS value.

What does that dot notation mean?



via Chebli Mohamed

Trim decimal to 2 digits

I have this query

SELECT CONVERT(VARCHAR(20),(((currentytd - PreviousYTD) / PreviousYTD) * 100)) + '%' as ytdGrowth from ytd 

It is returning: 11.224300%

I would like to return: 11.22%

I am very new SQL so trying to find the correct way to accomplish this.



via Chebli Mohamed

CSS selector - Select a element who's parent(s) has a sibling with a specific element

I have a series of textareas that all follow the same format nested html format but I need to target one specifically. The problem I'm having is that the unique value I can use to identify the specific textarea is a parent's sibling's child.

Given this html

<fieldset>
<legend class="name">
<a href="#" style="" id="element_5014156_showhide" title="Toggle “Standout List”">▼</a>
</legend>
<ul id="element_5014156" class="elements">
<li class="element clearboth">
<h3 class="name">Para:</h3>
<div class="content">
<textarea name="container_prof|15192341" id="container_prof15192341">  TARGET TEXTAREA</textarea>
</div>
::after
</li>
<li class="element clearboth">
<h3 class="name">Para:</h3>
<div class="content">
<input type="text" class="textInput" name="container_prof|15192342" id="container_prof_15192342" value="" size="64">
</div>
::after
</li>
</ul>
</fieldset>

There are many of the <li> elements. I can't use the name or id as they dynamically created.

I want to target the textarea that says TARGET TEXTAREA. The only unqiquess I can find is the title attribute of the <a> element within the element.

I can get that specifically legend.name a[title*='Standout'] In Chrome Console: $$("legend.name a[title*='Standout']");

and I can traverse all the way to up to the <legend> element from the textarea legend.name ~ ul.elements li.element div.content textarea

In Chrome Console: $$("legend.name ~ ul.elements li.element div.content textarea")

That gives me ALL the textareas that have a div with class="content" that has a li with a class=element which has a ul with a class=elements which has a sibling legend with a class=name.

The only thing I can figure out is to add the qualifier that the legend with the class=name has to have the anchor that has 'Standout' in it's title.

I've tried $$("legend.name a[title*='Standout'] ~ ul.elements li.element div.content textarea") but that fails obviously since the anchor is not an adjacent sibling of the ul

Any help would be most appreciated!



via Chebli Mohamed

Select all descendant HTML elements with a certain class that don't have an element with an other specific class in between

Assume you have the following HTML:

<div id="root-component" class="script-component">a0
            <div></div>
            <div class="component">a2</div>
            <div class="script-component">b
                <div class="component">b1
                    <div class="script-component">c
                    </div>
                    <div class="component">b2
                    </div>
                </div>
            </div>
            <div class="component">a3</div>
            <div class="component">a4</div>
            <div>            
                <div class="component">a5</div>
            </div>
            <div class="component"> a6            
                <div class="component">a7</div>
            </div>
            <div class="component">a8
                <div class="script-component"></div>
            </div>
</div>

From the root-component I would like to select all child elements with a component class until and not including the elements with the script-component class. This means at the end only the elements with an a text should be selected.

Edit: Or in Trung's words: The goal is to skip searching for components down the tree once script-component class is encountered.

Edit2: Or in even other words: I would like to select all .component children until a .script-component is encountered.

It can be done using jQuery and CSS.

You can use this jsFiddle http://ift.tt/1gf6Nlb to try it out.



via Chebli Mohamed

a single process system monitoring tools

i am working on a project on linux and i need to analyse the performence of an application server .

i need a tools that gives graphs , statistics and system metrics of a single process identified by it PID

i need information like : number of threads created , number of threads actives , memory usage by each thread , the distribution of threads on processor cores etc

i tried TOP and sysstat , but i didn't how to get an CSV file or a graph out of them

Thx



via Chebli Mohamed

Number list outputed as characters - Elixir

I was working on elixir and suddenly this happened

iex(1)> [9,9,9]
'\t\t\t'
iex(2)> [8,8,8]
'\b\b\b'
iex(3)> [104, 101, 108, 108, 111]
'hello'

List of numbers output as characters. I freaked out, but then checked out the documentation to see that this was normal behavior Can anyone tell me the reason,purpose and any other gotcha's about this if any, Thanks.



via Chebli Mohamed

Django Rest framework pagination by choices

I have pagination problem. My api has a model product which contains a field which has 5 choices.

I have already entered 30 entries in product each choices has 6 entries, page size which I've set is 5, my requirement is if at first I call 127.0.0.1:8000/api/product/ I want 1 entry from each choice, no matter whether first page has only entries on choice 1.

I'm not sure this has to be done through pagination or filtering but I'm unable to figure it out.

class Product(models.Model):
    item_category_choices = (('MU','Make Up'), ('SC','Skin Care'),   ('Fra','Fragrance'), ('PC','Personal Care'),('HC','Hair Care'))
    item_category = models.CharField(max_length=20,choices = item_category_choices)

now on hitting url /api/product I need a response something like

{"count":30,"next":"127.0.0:8000/api/product/?page=2","previous":null,"results":[{"id":1,"item_category":'Personal Care',},{"id":2,"item_category":'Hair Care'},{"id":3,"item_category":MakeUp},{"id":4,"item_category":"SkinCare},{"id":5,"item_category":"'Fragrance"}}]}



via Chebli Mohamed

Where do I save a variable that should not be overwritten when I refresh the page in rails

I am pretty new to rails and ruby and still wrapping my head around the hole concept of rails.

What I want to do: I'm creating a shift-planner with a view of one week and want to create a button that will show the next/last week.

What I did:

I have 3 tables that are relevant. shift, person and test (contains types of shifts) Where both Test and Peson have one to many relations to Shift.

In my controller I did the following:

  def index
@todos = Todo.all
@shifts = Shift.all
@people = Person.all

@start_of_week = Date.new(2015,8,7)
@end_of_week = Date.new(2015,8,11)

view:

<% person.shifts.where(:date_of_shift =>  @start_of_week..@end_of_week).order(:date_of_shift).each do |shift| %>
    <td>
        <%="#{shift.test.name} #{shift.date_of_shift}"%>
    </td>
<%end%>

My Idea was I would make a link where I would increment both Dates and refresh my Page

<a href="/todos/new">
    Next Week
    <% @start_of_week += 7 %>
    <% @end_of_week += 7 %>
</a>

Unfortuately that doesn't work. Cause everytime I call the index function in my controller it sets the date on the default value.

And I'm pretty clueless how to fix this problem in a rails way. My only would be to somehow pass the dates as parameter to the index function or something like that.

the generell structure is: I scaffolded a Todo view/controller/db just for the sake of having a view / controller and my 3 databases.

Thx for the help. PS: I'm using the current version of ruby and rails on lubuntu15(schouldn't be really releveant^^)



via Chebli Mohamed

Private methods in Ruby

An example of Rails controller which defines a private method:

class ApplicationController < ActionController::Base
  private
  def authorization_method
    # do something
  end
end

Then, it's being used in subclass of "ApplicationController":

class CustomerController < ApplicatioController
  before_action :authorization_method

  # controller actions
end

My question is: how is it possible, that private method be called from subclass? What is meaning of private in Ruby?

Thanks



via Chebli Mohamed

Encountered the symbol when expecting one of the following: if in Pl/SQL function

I am writing the below function in which i am getting an error i think for if/else condition as Error(1360,5): PLS-00103: Encountered the symbol "BUILD_ALERT_EMAIL_BODY" when expecting one of the following: if. I think i am using proper syntax but dont know why the error is coming.

FUNCTION BUILD_ALERT_EMAIL_BODY
(
  IN_ALERT_LOGS_TIMESTAMP IN TIMESTAMP
, IN_ALERT_LOGS_LOG_DESC IN VARCHAR2
, IN_KPI_LOG_ID IN NUMBER
) RETURN VARCHAR2 AS
BODY VARCHAR2(4000) := '';
V_KPI_TYPE_ID NUMBER;
V_KPI_THRESHOLD_MIN_VALE NUMBER;
V_KPI_THRESHOLD_MAX_VALE NUMBER;
V_EXPECTED_VALE NUMBER;
V_ACTUAL_VALE NUMBER;  

BEGIN
-- ,'yyyy-MM-dd H24 mm ss'
Select KPI_DEF_ID INTO V_KPI_DEF_ID FROM KPI_LOGS WHERE KPI_LOG_ID = IN_KPI_LOG_ID;
Select EXPECTED_VALE INTO V_EXPECTED_VALE FROM KPI_LOGS WHERE KPI_LOG_ID = IN_KPI_LOG_ID;
Select ACTUAL_VALE INTO V_ACTUAL_VALE FROM KPI_LOGS WHERE KPI_LOG_ID = IN_KPI_LOG_ID;


  Select KT.KPI_TYPE_ID INTO V_KPI_TYPE_ID FROM RATOR_MONITORING_CONFIGURATION.KPI_DEFINITION KD JOIN RATOR_MONITORING_CONFIGURATION.KPI_TYPE KT ON KD.KPI_TYPE = KT.KPI_TYPE_ID WHERE KD.KPI_DEF_ID = V_KPI_DEF_ID;
Select KPI_THRESHOLD_MIN_VAL INTO V_KPI_THRESHOLD_MIN_VALE FROM RATOR_MONITORING_CONFIGURATION.KPI_DEFINITION WHERE KPI_DEF_ID = V_KPI_DEF_ID;
Select KPI_THRESHOLD_MAX_VAL INTO V_KPI_THRESHOLD_MAX_VALE FROM RATOR_MONITORING_CONFIGURATION.KPI_DEFINITION WHERE KPI_DEF_ID = V_KPI_DEF_ID;

    IF ((V_KPI_TYPE_ID = 18) || (V_KPI_TYPE_ID = 19))  THEN
    BODY := BODY || 'KPI_THRESHOLD_MIN_VAL:' || V_KPI_THRESHOLD_MIN_VALE || Chr(13) || Chr(10);
    BODY := BODY || 'KPI_THRESHOLD_MAX_VAL:' || V_KPI_THRESHOLD_MAX_VALE || Chr(13) || Chr(10);
    ELSE IF ((V_KPI_TYPE_ID = 11) || (V_KPI_TYPE_ID = 12) || (V_KPI_TYPE_ID = 13) || (V_KPI_TYPE_ID = 14) || (V_KPI_TYPE_ID = 20)) THEN
    BODY := BODY || 'EXPECTED_VALE:' || V_EXPECTED_VALE || Chr(13) || Chr(10);
    BODY := BODY || 'ACTUAL_VALE:' || V_ACTUAL_VALE || Chr(13) || Chr(10);    
    END IF;

    RETURN BODY;
END BUILD_ALERT_EMAIL_BODY;



via Chebli Mohamed

Objective-c Coreplot graph scrolling

I generated a scatterplot graph.My requirement is to swipe the graph part by part ie,if 10 columns of plot r shown on the screen,on the swipe the next 10 columns need to be shown.

-(BOOL)plotSpace:(CPTXYPlotSpace *)space shouldHandlePointingDeviceDraggedEvent:(id)event atPoint:(CGPoint)point{
 NSLog(@"point.x=%lf,point.y=%lf",point.x,point.y);
 return YES;
}

This gives the point dragged..how can i achieve my requirement with this method or is their any other way to figure it out?

Anybody please help...



via Chebli Mohamed

Styling a nested XML element with XSLT?

I’m a print designer working on a travel guide that we recently started managing with XML-tagged content and XSLT styling. It mostly works, aside from this one small issue that has driven us to wit’s end! We have some sub-attraction listings that should appear as “child” listings that we can style differently in InDesign layout, and they’re noted in the XML by noting a value for their “parent” attraction in the MainAttraction tag.

My understanding is that we need the .XSL to notice whether there’s a value in the MainAttraction tags, and if there is, then to pull out the elements associated with that attraction to go under a different container tag so we can style them differently. I just haven’t had any luck writing syntax for this that works after doing some basic training and Googling around forums.

Here's what I'm experimenting with, which pulls in everything correctly except for sub-attractions (they're listed within the Attraction tags for their associated parent listing):

XSLT

<?xml version="1.0" ?>
<xsl:stylesheet xmlns:xsl="http://ift.tt/tCZ8VR" version="1.0">

    <xsl:template match="/">

    <Cities>
        <xsl:for-each select="Root/City">
            <City>
                <City_Name>
                    <xsl:value-of select="City_Name"/>
                </City_Name>
                <xsl:text>&#xa;</xsl:text>
                <City_Stats>
                    <xsl:text>POP. </xsl:text>
                    <xsl:value-of select="Population"/>
                    <xsl:text>  ALT. </xsl:text>
                    <xsl:value-of select="Altitude"/>
                    <xsl:text>  MAP </xsl:text>
                    <xsl:value-of select="Map_Grid_Location"/>
                </City_Stats>
                <xsl:text>&#xa;</xsl:text>

                <Visitor_Info>

                    <Visitor_Center>
                        <xsl:value-of select="Visitor_Center"/><xsl:text>: </xsl:text>
                    </Visitor_Center>

                    <Visitor_Information>

                        <xsl:value-of select="Visitor_Information"/><xsl:text> </xsl:text>
                        <xsl:value-of select="Address"/>
                        <xsl:text> </xsl:text>

                        <xsl:value-of select="normalize-space(Phone1)"/>
                            <xsl:if test="string-length(Phone2) &gt; 0">
                            <xsl:text> or </xsl:text>
                            <xsl:value-of select="Phone2"/>
                            </xsl:if>
                            <xsl:if test="string-length(Phone1) &gt; 0">
                            <xsl:text>. </xsl:text>
                            </xsl:if>


                        <xsl:value-of select="normalize-space(Website1)"/>
                            <xsl:if test="string-length(Website2) &gt; 0">
                            <xsl:text> or </xsl:text>
                            <xsl:value-of select="Website2"/>
                            </xsl:if>
                            <xsl:if test="string-length(Website1) &gt; 0">
                            <xsl:text>. </xsl:text>
                            </xsl:if>


                        </Visitor_Information>

                    </Visitor_Info>
                <xsl:text>&#xa;</xsl:text>

                <Description>
                    <xsl:value-of select="Description"/>
                </Description>
                    <xsl:text>&#xa;</xsl:text>

                <Attractions>
                    <xsl:apply-templates select="Attraction"/>
                </Attractions>



            </City>

        </xsl:for-each>

    </Cities>

    </xsl:template>


    <xsl:template match="Attraction">

        <Attraction>

                    <Attraction_Title>
                        <xsl:value-of select="normalize-space(Attraction_Title)"/>
                    </Attraction_Title>
                    <xsl:text>&#8212;</xsl:text>

                    <xsl:value-of select="Desc"/><xsl:text> </xsl:text>

                    <xsl:value-of select="normalize-space(Admissions)"/>
                        <xsl:if test="string-length(Admissions) &gt; 0">
                            <xsl:text>. </xsl:text>
                        </xsl:if>

                    <xsl:value-of select="normalize-space(Address)"/>
                    <xsl:if test="string-length(Address) &gt; 0">
                        <xsl:text>. </xsl:text>
                    </xsl:if>

                <xsl:value-of select="normalize-space(Directions)"/>
                <xsl:if test="string-length(Directions) &gt; 0">
                    <xsl:text>. </xsl:text>
                </xsl:if>

                <xsl:value-of select="normalize-space(Phone)"/>
                <xsl:if test="string-length(AltPhone) &gt; 0">
                    <xsl:text> or </xsl:text>
                    <xsl:value-of select="normalize-space(AltPhone)"/>
                </xsl:if>

                <xsl:if test="string-length(Phone) &gt; 0">
                    <xsl:text>. </xsl:text>
                </xsl:if>

                <xsl:value-of select="normalize-space(WebAddress)"/>
                <xsl:if test="string-length(WebAddress2) &gt; 0">
                    <xsl:text> or </xsl:text>
                    <xsl:value-of select="normalize-space(WebAddress2)"/>
                </xsl:if>

                <xsl:if test="string-length(WebAddress) &gt; 0">
                    <xsl:text>. </xsl:text>
                </xsl:if>

                <xsl:value-of select="normalize-space(Email)"/>
                    <xsl:if test="string-length(Email) &gt; 0">
                        <xsl:text>. </xsl:text>
                    </xsl:if>

                    <xsl:if test="string-length(SeeAlso) &gt; 0">
                        <xsl:text> </xsl:text>
                        <xsl:text>See </xsl:text>
                        <xsl:value-of select="normalize-space(SeeAlso)"/>
                        <xsl:text>. </xsl:text>
                    </xsl:if>

                <xsl:text>&#xa;</xsl:text>

        </Attraction>

    </xsl:template>

    <xsl:template match="SubAttraction">

        <SubAttraction>

            <xsl:if test="string-length(MainAttraction) &gt; 0">

                <xsl:text>&#9;</xsl:text>

                    <SubAttraction_Title>
                        <xsl:value-of select="normalize-space(Attraction_Title)"/>
                    </SubAttraction_Title>
                    <xsl:text>&#8212;</xsl:text>

                    <xsl:value-of select="Desc"/><xsl:text> </xsl:text>

                    <xsl:value-of select="normalize-space(Admissions)"/>
                        <xsl:if test="string-length(Admissions) &gt; 0">
                            <xsl:text>. </xsl:text>
                        </xsl:if>

                    <xsl:value-of select="normalize-space(Address)"/>
                    <xsl:if test="string-length(Address) &gt; 0">
                        <xsl:text>. </xsl:text>
                    </xsl:if>

                <xsl:value-of select="normalize-space(Directions)"/>
                <xsl:if test="string-length(Directions) &gt; 0">
                    <xsl:text>. </xsl:text>
                </xsl:if>

                <xsl:value-of select="normalize-space(Phone)"/>
                <xsl:if test="string-length(AltPhone) &gt; 0">
                    <xsl:text> or </xsl:text>
                    <xsl:value-of select="normalize-space(AltPhone)"/>
                </xsl:if>

                <xsl:if test="string-length(Phone) &gt; 0">
                    <xsl:text>. </xsl:text>
                </xsl:if>

                <xsl:value-of select="normalize-space(WebAddress)"/>
                <xsl:if test="string-length(WebAddress2) &gt; 0">
                    <xsl:text> or </xsl:text>
                    <xsl:value-of select="normalize-space(WebAddress2)"/>
                </xsl:if>

                <xsl:if test="string-length(WebAddress) &gt; 0">
                    <xsl:text>. </xsl:text>
                </xsl:if>

                <xsl:value-of select="normalize-space(Email)"/>
                    <xsl:if test="string-length(Email) &gt; 0">
                        <xsl:text>. </xsl:text>
                    </xsl:if>

                <xsl:text>&#xa;</xsl:text>

            </xsl:if>

        </SubAttraction>

    </xsl:template>

</xsl:stylesheet>

XML INPUT SAMPLE (note that the sub-attraction example, the Fredda Turner Durham Children's Museum, has a value in its Main Attraction tags and is nested within the attraction tags for its parent listing)

<?xml version="1.0" encoding="UTF-8"?>

<Root>
    <City>
        <City_Name>MIDLAND</City_Name>
        <Region>BIG BEND COUNTRY</Region>
        <Population>127,598</Population>
        <Altitude>2,891</Altitude>
        <Map_Grid_Location>L-9/KK-4</Map_Grid_Location>
        <Visitor_Center>Midland Visitors Center</Visitor_Center>                    <Visitor_Information>Midland Convention &amp; Visitors Bureau: Open 8 a.m.-5 p.m. Mon.-Sat. 109 N Main St. 800/624-6435.</Visitor_Information><Address>1406 W. I-20 (Exit 136).</Address><Hours>Open 9 a.m.-5 p.m. Mon.-Sat.</Hours><Phone1>432/683-2882</Phone1><Phone2>800/624-6435</Phone2><Website1>&lt;a href="http://ift.tt/ZyZBJr" &gt;http://ift.tt/1Kft3Yo;
        <CityId>MIDLAND</CityId>
        <Description>Description text goes here.</Description>

        <Attraction>
            <Attraction_Title>Haley Library &amp; History Center</Attraction_Title>
            <Desc>Description text goes here. </Desc>
            <Admissions>Donations accepted.</Admissions>
            <Hours>Open 9 a.m.-5 p.m. Mon.-Fri.</Hours>
            <Address>1805 W. Indiana Ave.</Address>
            <Directions></Directions>
            <Phone>432/682-5785</Phone>
            <AltPhone></AltPhone>
            <WebAddress></WebAddress>
            <WebAddress2></WebAddress2>
            <Email></Email>
            <SeeAlso></SeeAlso>
            <MainAttraction></MainAttraction>
        </Attraction>

        <Attraction>
            <Attraction_Title>I-20 Wildlife Preserve &amp; Jenna Welch Nature Study Center</Attraction_Title>
            <Desc>Description text goes here.</Desc>
            <Admissions></Admissions>
            <Hours>Open dusk–dawn daily.</Hours>
            <Address>2201 S. Midland Dr.</Address>
            <Phone>432/853-9453</Phone>
            <AltPhone></AltPhone>
            <WebAddress>http://ift.tt/1gf6NS9;
            <WebAddress2></WebAddress2>
            <Email></Email>
            <SeeAlso></SeeAlso>
            <MainAttraction></MainAttraction>
        </Attraction>

        <Attraction>
            <Attraction_Title>Museum of the Southwest</Attraction_Title>
            <Desc>Description text goes here.</Desc>
            <Admissions>Admission charged.</Admissions>
            <Hours>Open 10 a.m.-5 p.m. Tue.-Sat. and 2-5 p.m. Sun.</Hours>
            <Address>1705 W. Missouri.</Address>
            <Directions></Directions>
            <Phone>432/683-2882</Phone>
            <AltPhone></AltPhone>
            <WebAddress>http://ift.tt/1Kft2ni;
            <WebAddress2></WebAddress2>
            <Email></Email>
            <SeeAlso></SeeAlso>
            <MainAttraction></MainAttraction>

                <Attraction>
                    <Attraction_Title>Fredda Turner Durham Children's Museum</Attraction_Title>
                    <Desc>Description text goes here.</Desc>
                    <Admissions>Admission charge.</Admissions>
                    <Hours>Open 10 a.m.-5 p.m. Tue.-Sat. and 2-5 p.m. Sun. Free admission on Sundays.</Hours>
                    <Address></Address><Directions></Directions><Phone>432/683-2882</Phone><AltPhone></AltPhone><WebAddress></WebAddress><WebAddress2></WebAddress2><Email></Email><SeeAlso></SeeAlso><MainAttraction>Museum of the Southwest</MainAttraction>

            </Attraction>

        </Attraction>

    </City>

</Root>

CURRENT OUTPUT (the sub-attraction doesn't display)

    <?xml version="1.0" encoding="UTF-8"?>
<Cities>
   <City>
      <City_Name>MIDLAND</City_Name>
      <City_Stats>POP. 127,598  ALT. 2,891  MAP L-9/KK-4</City_Stats>
      <Visitor_Info>
         <Visitor_Center>Midland Visitors Center:</Visitor_Center>
         <Visitor_Information>Midland Convention &amp; Visitors Bureau: Open 8 a.m.-5 p.m. Mon.-Sat. 109 N Main St. 800/624-6435. 1406 W. I-20 (Exit 136). 432/683-2882 or 800/624-6435. &lt;a href="http://ift.tt/ZyZBJr" &gt;http://ift.tt/1gf6MO6;
      </Visitor_Info>
      <Description>Description text goes here.</Description>
      <Attractions>
         <Attraction>
            <Attraction_Title>Haley Library &amp; History Center</Attraction_Title>
            —Description text goes here.  Donations accepted.. 1805 W. Indiana Ave.. 432/682-5785.
         </Attraction>
         <Attraction>
            <Attraction_Title>I-20 Wildlife Preserve &amp; Jenna Welch Nature Study Center</Attraction_Title>
            —Description text goes here. 2201 S. Midland Dr.. 432/853-9453. http://ift.tt/1Kft3Yq.
         </Attraction>
         <Attraction>
            <Attraction_Title>Museum of the Southwest</Attraction_Title>
            —Description text goes here. Admission charged.. 1705 W. Missouri.. 432/683-2882. www.museumsw.org.
         </Attraction>
      </Attractions>
   </City>
</Cities>

DESIRED OUTPUT (the sub-attraction displays and had its own container tags)

<?xml version="1.0" encoding="UTF-8"?>
<Cities>
   <City>
      <City_Name>MIDLAND</City_Name>
      <City_Stats>POP. 127,598  ALT. 2,891  MAP L-9/KK-4</City_Stats>
      <Visitor_Info>
         <Visitor_Center>Midland Visitors Center:</Visitor_Center>
         <Visitor_Information>Midland Convention &amp; Visitors Bureau: Open 8 a.m.-5 p.m. Mon.-Sat. 109 N Main St. 800/624-6435. 1406 W. I-20 (Exit 136). 432/683-2882 or 800/624-6435. &lt;a href="http://ift.tt/ZyZBJr" &gt;http://ift.tt/1gf6MO6;
      </Visitor_Info>
      <Description>Description text goes here.</Description>
      <Attractions>
         <Attraction>
            <Attraction_Title>Haley Library &amp; History Center</Attraction_Title>
            —Description text goes here.  Donations accepted.. 1805 W. Indiana Ave.. 432/682-5785.
         </Attraction>
         <Attraction>
            <Attraction_Title>I-20 Wildlife Preserve &amp; Jenna Welch Nature Study Center</Attraction_Title>—Description text goes here. 2201 S. Midland Dr.. 432/853-9453. http://ift.tt/1Kft3Yq.
         </Attraction>
         <Attraction>
            <Attraction_Title>Museum of the Southwest</Attraction_Title>—Description text goes here. Admission charged.. 1705 W. Missouri.. 432/683-2882. www.museumsw.org.
         </Attraction>
         <SubAttraction>
            <SubAttraction_Title>Fredda Turner Durham Children's Museum</SubAttraction_Title>—Description text goes here. Admission charge.. 432/683-2882.
         </SubAttraction>
     </Attractions>
  </City>
</Cities>

So what do I do here to make it so sub-attractions (attractions with a value int he MainAttraction field) can get pulled into new container tags? I understand that we want to create a new template for SubAttractions, but I don't know how to get only the desired elements into it. I'd greatly appreciate help in finding something to plug in here if it's not too difficult for someone more experienced.

[Original post has been edited to provide more useful info.]



via Chebli Mohamed

How do I configure django-money to output GBP in British format?

I'm using django-money to handle money amounts in GBP (Pounds Sterling), but they are being output as GB£20.00, rather than £20.00. This is despite settings.LANGUAGE_CODE being "en-GB" and settings.USE_L10N being True.

What am I doing wrong?



via Chebli Mohamed

Using Linked List into OSP 2 TaskCB

I am learning OSP 2 and how to use to implement method in the TaskCB, as well as an implementation of a Linked List. So I got my TaskCB class work fine, but when I create a Linked List it gives me errors such as

Possible cause: Failed to add/remove a thread to/from task

Image of output

Anybody can help me to point out what I am missing or any suggest would be great! Thank you!

Here is my TaskCB and Linked Like code so far.

import osp.FileSys.*;
import osp.Hardware.*;
import osp.IFLModules.*;
import osp.Memory.*;
import osp.Ports.*;
import osp.Threads.*;

/**
 * The student module dealing with the creation and killing of tasks. A task
 * acts primarily as a container for threads and as a holder of resources.
 * Execution is associated entirely with threads. The primary methods that the
 * student will implement are do_create(TaskCB) and do_kill(TaskCB). The student
 * can choose how to keep track of which threads are part of a task. In this
 * implementation, an array is used.
 * 
 * @OSPProject Tasks
 */
public class TaskCB extends IflTaskCB {
    /**
     * The task constructor. Must have
     * 
     * super();
     * 
     * as its first statement.
     * 
     * @OSPProject Tasks
     */

    private LinkedList<ThreadCB> threadList;
    private LinkedList<PortCB> portList;
    private LinkedList<OpenFile> openFilesTable;

    private static int virtureMemorySize = (int) Math.pow(2,
        MMU.getVirtualAddressBits());

    public TaskCB() {

        super();
    }

    /**
     * This method is called once at the beginning of the simulation. Can be
     * used to initialize static variables.
     * 
     * @OSPProject Tasks
     */
    public static void init() {
        // your code goes here

    }

    /**
     * Sets the properties of a new task, passed as an argument.
     * 
     * Creates a new thread list, sets TaskLive status and creation time,
     * creates and opens the task's swap file of the size equal to the size (in
     * bytes) of the addressable virtual memory.
     * 
     * @return task or null
     * 
     * @OSPProject Tasks
     */
    static public TaskCB do_create() {

        TaskCB theTask = new TaskCB();
        PageTable pagTable = new PageTable(theTask);
        theTask.setPageTable(pagTable);

        theTask.threadList = new LinkedList<ThreadCB>();
        theTask.portList = new LinkedList<PortCB>();
        theTask.openFilesTable = new LinkedList<OpenFile>();

        theTask.setCreationTime(HClock.get());
        theTask.setStatus(TaskLive);
        theTask.setPriority(0);

        FileSys.create(SwapDeviceMountPoint + theTask.getID(),
            virtureMemorySize);
        OpenFile swapFile = OpenFile.open(SwapDeviceMountPoint + theTask.getID(),
            theTask);

        if ( swapFile == null ) {
            ThreadCB.dispatch();
//            theTask.do_kill();
            return null;
        }

        theTask.setSwapFile(swapFile);
        ThreadCB.create(theTask);

        return theTask;

    }

    /**
     * Kills the specified task and all of it threads.
     * 
     * Sets the status TaskTerm, frees all memory frames (reserved frames may
     * not be unreserved, but must be marked free), deletes the task's swap
     * file.
     * 
     * @OSPProject Tasks
     */
    public void do_kill() {

        for ( int i = threadList.size() - 1; i >= 0; i-- ) {
            ((ThreadCB) this.threadList.get(i)).kill();
        }

        for ( int i = this.portList.size() - 1; i >= 0; i-- ) {
            ((PortCB) this.portList.get(i)).destroy();
        }

        this.setStatus(TaskTerm);
        this.getPageTable().deallocateMemory();

        for ( int i = openFilesTable.size() - 1; i >= 0; i-- ) {
            OpenFile swapFile = (OpenFile) openFilesTable.get(i);
            if ( swapFile != this.getSwapFile() ) {
                swapFile.close();
            }
        }

        this.getSwapFile().close();
        FileSys.delete(SwapDeviceMountPoint + this.getID());

    }

    /**
     * Returns a count of the number of threads in this task.
     * 
     * @OSPProject Tasks
     */
    public int do_getThreadCount() {
        return threadList.size();
    }

    /**
     * Adds the specified thread to this task.
     * 
     * @return FAILURE, if the number of threads exceeds MaxThreadsPerTask;
     *         SUCCESS otherwise.
     * 
     * @OSPProject Tasks
     */
    public int do_addThread(ThreadCB thread) {
        if ( threadList.size() >= ThreadCB.MaxThreadsPerTask ) {
            return TaskCB.FAILURE;
        }
        threadList.addFirst(thread);
        return TaskCB.SUCCESS;
    }

    /**
     * Removes the specified thread from this task.
     * 
     * @OSPProject Tasks
     */
    public int do_removeThread(ThreadCB thread) {
        if ( this.threadList.contains(thread) ) {
            this.threadList.remove(thread);
            return TaskCB.SUCCESS;
        }
        else
            return TaskCB.FAILURE;
    }

    /**
     * Return number of ports currently owned by this task.
     * 
     * @OSPProject Tasks
     */
    public int do_getPortCount() {
        return portList.size();
    }

    /**
     * Add the port to the list of ports owned by this task.
     * 
     * @OSPProject Tasks
     */
    public int do_addPort(PortCB newPort) {
        if ( portList.size() >= PortCB.MaxPortsPerTask ) {
            return TaskCB.FAILURE;
        }
        portList.addFirst(newPort);
        return TaskCB.SUCCESS;
    }

    /**
     * Remove the port from the list of ports owned by this task.
     * 
     * @OSPProject Tasks
     */
    public int do_removePort(PortCB oldPort) {
        if ( this.portList.contains(oldPort) ) {
            portList.remove(oldPort);
            return TaskCB.SUCCESS;
        }

        return TaskCB.FAILURE;
    }

    /**
     * Insert file into the open files table of the task.
     * 
     * @OSPProject Tasks
     */
    public void do_addFile(OpenFile file) {
        this.openFilesTable.addLast(file);

    }

    /**
     * Remove file from the task's open files table.
     * 
     * @OSPProject Tasks
     */
    public int do_removeFile(OpenFile file) {
        if ( file.getTask() != this )
            return TaskCB.FAILURE;
        openFilesTable.remove(file);
        return TaskCB.SUCCESS;
    }




import java.util.*;

public class LinkedList<V> implements Iterable<V>
{
   private Node<V> head;
   private int count = 0;

 /**
   *  Constructs an empty list
   */
   public LinkedList()
   {
      head = null;
   }
 /**
   *  Returns true if the list is empty
   *
   */
   public boolean isEmpty()
   {
      return head == null;
   }

   public int size() {
       return count;
   }
 /**
   *  Inserts a new node at the beginning of this list.
   *
   */
   public void addFirst(V item)
   {
      head = new Node<V>(item, head);
   }
 /**
   *  Returns the first element in the list.
   *
   */
   public V getFirst()
   {
      if(head == null) throw new NoSuchElementException();

      return head.data;
   }
 /**
   *  Removes the first element in the list.
   *
   */
   public V removeFirst()
   {
      V tmp = getFirst();
      head = head.next;
      return tmp;
   }
 /**
   *  Inserts a new node to the end of this list.
   *
   */
   public void addLast(V item)
   {
      if( head == null)
         addFirst(item);
      else
      {
         Node<V> tmp = head;
         while(tmp.next != null) tmp = tmp.next;

         tmp.next = new Node<V>(item, null);
      }
   }
 /**
   *  Returns the last element in the list.
   *
   */
   public V getLast()
   {
      if(head == null) throw new NoSuchElementException();

      Node<V> tmp = head;
      while(tmp.next != null) tmp = tmp.next;

      return tmp.data;
   }
 /**
   *  Removes all nodes from the list.
   *
   */
   public void clear()
   {
      head = null;
   }
 /**
   *  Returns true if this list contains the specified element.
   *
   */
   public boolean contains(V x)
   {
      for(V tmp : this)
         if(tmp.equals(x)) return true;

      return false;
   }
 /**
   *  Returns the data at the specified position in the list.
   *
   */
   public V get(int pos)
   {
      if (head == null) throw new IndexOutOfBoundsException();

      Node<V> tmp = head;
      for (int k = 0; k < pos; k++) tmp = tmp.next;

      if( tmp == null) throw new IndexOutOfBoundsException();

      return tmp.data;
   }
 /**
   *  Returns a string representation
   *
   */
   public String toString()
   {
      StringBuffer result = new StringBuffer();
      for(Object x : this)
        result.append(x + " ");

      return result.toString();
   }
 /**
   *  Inserts a new node after a node containing the key.
   *
   */
   public void insertAfter(V key, V toInsert)
   {
      Node<V> tmp = head;

      while(tmp != null && !tmp.data.equals(key)) tmp = tmp.next;

      if(tmp != null)
         tmp.next = new Node<V>(toInsert, tmp.next);
   }
 /**
   *  Inserts a new node before a node containing the key.
   *
   */
   public void insertBefore(V key, V toInsert)
   {
      if(head == null) return;

      if(head.data.equals(key))
      {
         addFirst(toInsert);
         return;
      }

      Node<V> prev = null;
      Node<V> cur = head;

      while(cur != null && !cur.data.equals(key))
      {
         prev = cur;
         cur = cur.next;
      }
      //insert between cur and prev
      if(cur != null)
         prev.next = new Node<V>(toInsert, cur);
   }
 /**
   *  Removes the first occurrence of the specified element in this list.
   *
   */
   public void remove(V key)
   {
      if(head == null)
         throw new RuntimeException("cannot delete");

      if( head.data.equals(key) )
      {
         head = head.next;
         return;
      }

      Node<V> cur  = head;
      Node<V> prev = null;

      while(cur != null && !cur.data.equals(key) )
      {
         prev = cur;
         cur = cur.next;
      }

      if(cur == null)
         throw new RuntimeException("cannot delete");

      //delete cur node
      prev.next = cur.next;
   }

 /*******************************************************
 *
 *  The Node class
 *
 ********************************************************/
   private static class Node<AnyType>
   {
      private AnyType data;
      private Node<AnyType> next;

      public Node(AnyType data, Node<AnyType> next)
      {
         this.data = data;
         this.next = next;
      }
   }

 /*******************************************************
 *
 *  The Iterator class
 *
 ********************************************************/

   public Iterator<V> iterator()
   {
      return new LinkedListIterator();
   }

   private class LinkedListIterator  implements Iterator<V>
   {
      private Node<V> nextNode;

      public LinkedListIterator()
      {
         nextNode = head;
      }

      public boolean hasNext()
      {
         return nextNode != null;
      }

      public V next()
      {
         if (!hasNext()) throw new NoSuchElementException();
         V res = nextNode.data;
         nextNode = nextNode.next;
         return res;
      }

      public void remove() { throw new UnsupportedOperationException(); }
   }
}



via Chebli Mohamed

Visual studios c#, trying to add objects every click of a button

I'm trying to add a circle every click on button1. For some reason after adding the first circle, I can't add a second. Please help, it's for a school project... Here's the code: http://ift.tt/1FBNY2q



via Chebli Mohamed

Transfer artifact via SFTP using Maven

I'm attempting to add a build task into a Maven pom file so that I can transfer a jar file as well as some xml files to an SFTP server (it's a VM with Tomcat installed) but I have been unable to so far.

I've had a look at a few links, but they either don't quite match the requirements, have missing steps, or don't work. I'm basically a beginner with Maven so I'm not sure if I'm doing it correctly.

The requirement is that I want to invoke a Maven build, with command line arguments for the hostname, username, and password (which I have working) which then will upload a jar file and the xml files to a VM with Tomcat running in it via SFTP (FTP doesn't work, and I don't think SCP will work as I don't have a passfile). I also don't want to mess with the main Maven settings.xml file to add the connection details in, which some of the links I found seem to be reliant upon.

I have the following profile so far, using FTP, but it doesn't work due to not using SFTP.

<profiles>
    <profile>
        <!-- maven antrun:run -Pdeploy -->
        <id>deploy</id>
        <build>
            <plugins>
                <plugin>
                    <inherited>false</inherited>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-antrun-plugin</artifactId>
                    <version>1.6</version>
                    <configuration>
                        <target>
                            <!-- <loadproperties srcFile="deploy.properties" /> -->

                            <ftp action="send" server="${server-url}"
                                remotedir="/usr/share/myappserver/webapps/myapp/WEB-INF/lib"
                                userid="${user-id}" password="${user-password}" depends="no"
                                verbose="yes" binary="yes">
                                <fileset dir="target">
                                    <include name="artifact.jar" />
                                </fileset>
                            </ftp>

                            <ftp action="send" server="${server-url}"
                                remotedir="/var/lib/myappserver/myapp/spring"
                                userid="${user-id}" password="${user-password}" depends="no"
                                verbose="yes" binary="yes">
                                <fileset dir="src/main/resource/spring">
                                    <include name="*.xml" />
                                </fileset>
                            </ftp>

                            <!-- calls deploy script -->
                            <!-- <sshexec host="host" trust="yes" username="usr" password="pw" 
                                command="sh /my/script.sh" /> -->

                            <!-- SSH -->
                            <taskdef name="sshexec" classname="org.apache.tools.ant.taskdefs.optional.ssh.SSHExec" 
                                classpathref="maven.plugin.classpath" />
                            <taskdef name="ftp"
                                classname="org.apache.tools.ant.taskdefs.optional.net.FTP"
                                classpathref="maven.plugin.classpath" />
                        </target>

                    </configuration>
                    <dependencies>
                        <dependency>
                            <groupId>commons-net</groupId>
                            <artifactId>commons-net</artifactId>
                            <version>1.4.1</version>
                        </dependency>
                        <dependency>
                            <groupId>ant</groupId>
                            <artifactId>ant-commons-net</artifactId>
                            <version>1.6.5</version>
                        </dependency>
                        <dependency>
                            <groupId>ant</groupId>
                            <artifactId>ant-jsch</artifactId>
                            <version>1.6.5</version>
                        </dependency>
                        <dependency>
                            <groupId>jsch</groupId>
                            <artifactId>jsch</artifactId>
                            <version>0.1.29</version>
                        </dependency>
                    </dependencies>
                </plugin>
            </plugins>
        </build>
    </profile>
</profiles>

I tried swapping ftp for sftp, and using org.apache.tools.ant.taskdefs.optional.ssh.SFTP instead, but it didn't seem to work.

So to summarize, the SFTP config needs to be self contained within the pom file as much as possible, with stuff like the host url, username and password being passed in when invoked.



via Chebli Mohamed

Call function inside bxslider callback

I am trying to call a custom function inside a bxslider callback but the function doesn't get recorgnized (aka: Uncaught Reference Error: nextSlideCustom() is not a function)

my current code looks like

    var slider=$('#slider1').bxSlider({
         pager: 'true',
         onSlideNext: nextSlideHandle()
    });

and in a different js file I am defining this function:

function nextSlideHandle(){
    console.log("huhu");
}

so what's the problem with my code, or is it mory likely a wrong configuration of the slider or something?

thanks in advance!



via Chebli Mohamed

How to disable browser auto filling username and password

How to disable browser auto filling form username and password fields. I have already tried autocomplete="off". It's not working for me. Please find the form below. And help me to solve this.



via Chebli Mohamed

MySQL - Check if two values are equal or both NULL?

If I want to compare two values, I can write:

SELECT * FROM table1
JOIN table2 ON table1.col = table2.col;

I've noticed that this does not work if both table1.col and table2.col are NULL. So my corrected query looks like this:

SELECT * FROM table1
JOIN table2 ON 
  (table1.col = table2.col)
  OR
  (table1.col IS NULL AND table2.col IS NULL);

Is this the correct way to compare two values? Is there a way to say two values are equal if they are both NULL?



via Chebli Mohamed

Setting up a Ground node using SpriteKit?

I've been designing a game where I want the game to stop as soon as the ball makes contact with the ground. My function below is intended to set up the ground.

class GameScene: SKScene, SKPhysicsContactDelegate {

     var ground = SKNode() 

     let groundCategory: UInt32 = 0x1 << 0
     let ballCategory: UInt32 = 0x1 << 1

     func setUpGround() -> Void {
            self.ground.position = CGPointMake(0, self.frame.size.height)
            self.ground.physicsBody = SKPhysicsBody(rectangleOfSize: CGSizeMake(self.frame.size.width, self.frame.size.height)) //Experiment with this
            self.ground.physicsBody?.dynamic = false

            self.ground.physicsBody?.categoryBitMask = groundCategory    //Assigns the bit mask category for ground
            self.ball.physicsBody?.contactTestBitMask = ballCategory  //Assigns the contacts that we care about for the ground

            self.addChild(self.ground)
        } 
    }

The problem I am noticing is that when I run the iOS Simulator, the Ground node is not being detected. What am I doing wrong in this case?



via Chebli Mohamed

Return the row of first non-blank cell in Excel

Let's say I have the array A1:A5 in excel:

    A  
1    
2  
3  'test'  
4  
5  'test2'

How can I return "3"? I'm looking for something in Excel formulas. The blanks are genuine blanks.



via Chebli Mohamed

SQL connection error from PHP after many operations

I'm currently looping to create a MBTiles map, and add information to my database each time. Here's how I configured my connection and execute actions during the loop:

if ($pdo_mbtiles == null) {
    echo "Opening new database connection".PHP_EOL;
    $pdo_mbtiles = new PDO('sqlite:'.$filename,
            '',
            '',
            array(
                PDO::ATTR_PERSISTENT => true
                )
            );
}
$pdo_mbtiles->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$pdo_mbtiles->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$q = $pdo_mbtiles->prepare("INSERT INTO tiles (zoom_level, tile_column, tile_row,tile_data) VALUES (:zoom_level, :tile_column, :tile_rowTMS, :tile_data)");
$q->bindParam(':zoom_level', $zoom_level);
$q->bindParam(':tile_column', $tile_column);
$q->bindParam(':tile_rowTMS', $tile_rowTMS);
$q->bindParam(':tile_data', $tile_data, PDO::PARAM_LOB);
$q->execute();

After 1018 times looping (this number doesn't change no matter how many times I try), I get this error message:

SQLSTATE[HY000]: General error: 14 unable to open database file

I checked the solution written here: How to prevent SQLITE SQLSTATE[HY000] [14]? but the echoed message only appears at the first time of the loop, so I assume the PDO connection isn't closed.

I didn't find other documentation relevant to this error code.

What could possibly go wrong here?



via Chebli Mohamed

How to compute for the mean and sd

I need help on 4b please

  1. ‘Warpbreaks’ is a built-in dataset in R. Load it using the function data(warpbreaks). It consists of the number of warp breaks per loom, where a loom corresponds to a fixed length of yarn. It has three variables namely, breaks, wool, and tension.

    b. For the ‘AM.warpbreaks’ dataset, compute for the mean and the standard deviation of the breaks variable for those observations with breaks value not exceeding 30.

    data(warpbreaks)
    warpbreaks <- data.frame(warpbreaks)
    AM.warpbreaks <- subset(warpbreaks, wool=="A" & tension=="M")
    
    mean(AM.warpbreaks<=30)
    sd(AM.warpbreaks<=30)
    
    

This is what I understood this problem and typed the code as in the last two lines. However, I wasn't able to run the last two lines while the first 3 lines ran successfully. Can anybody tell me what is the error here? Thanks! :)



via Chebli Mohamed

Select all span elements except those which class contains the word icon

I'm implementing the following CSS Selector

Select all span elements except those which class contains the word icon

So the following seems to be working:

.music-site-refresh span:not([class*="icon"]) {
  font-family:Montserrat, sans-serif;
}

But I thought it should be like this:

.music-site-refresh span:not(span[class*="icon"]) {
  font-family:Montserrat, sans-serif;
}

But the second one doesn't work in my testbed.

Could anyone explain me which one is correct and why?



via Chebli Mohamed

CSS: fly-in menu on a centred site

Designers that don't need to write code.... sigh.

Before I go back and tell him it's not possible, I thought I'd canvas the stackoverflow brain.

A centred website, with a slide-in menu. My understanding is that slide-in menus generally work by hiding the menu off the left side of the viewport. i.e. only valid on a left anchored site.

I have a site that does it by expanding the side menu (i.e. it can sit invisible with a width:0 but not sliding in.



via Chebli Mohamed

dynamically create div and into a static div

On click of button i am trying to create one div and try to append static div into that and this is giving error.

Uncaught TypeError: elm.appendChild is not a function.

    <script>
        function s()
        {
            var elm = '<div' +
                'style="background-color:orange;height:125px;width:75px;"'+
                '</div>';           
            var x=document.getElementById("ss")         
            elm.appendChild(x);         
        }
    </script>       

    <div id="ss">
        <ul>
            <li style="background-color:grey;">
                <h2 class="wheater_CityName">Mumbai</h2><br><br>
                    <div style= 
                        "margin-left: 30%;
                        margin-top: -21%;"
                    >
                    </div>
                    <hr style= "margin-top: -83px; ">                   
            </li>
            <li>sad</li>
            <li>as</li>             
        </ul>
    </div>    
    <input type="button" value="ss" onclick="s()"/>



via Chebli Mohamed

ActionScript: using variables w/E4X descendant accessor (..)

I'm using a descendant accessor like so:

var myxml:XMLList = new XMLList;

...

myxml..node

and would like to replace it w/

const sNode:String = 'node';
myxml..[{sNode}]

This sort of thing has worked before.

const sAttrib:String = 'attrib';
myxml.@[{sAttrib}]

works, but trying the same sort of thing w/a descendant accessor causes a compiler error.

Yes, I could do

myxml.descendants(sNode)

but I'd rather do it w/operators, if I can.

The XML might be something like:

<map>
    <node>
       <node />
    </node>
</map>



via Chebli Mohamed

Unable to implement user subscription based Push Notifications when implemented with Adapter based authentication

I have defined an Adapter based as authentication.

Doing a custom security test which works successfully.

But when I wanted to implement User Subscription based Push Notifications and added a mobile security test in authentication Config.XML I am facing lot of issues.

As I'm trying to deploy the app and test in android device. I have also included the mobile security test in android tag of application-descriptor.xml. But facing lot of issues to deploy the adapter itself after this.

Can anyone guide me on this please?

Please refer to the below code snippets which I am using

authenticationConfig.xml

    <mobileSecurityTest name="MST1">
        <testUser realm="AdapterAuthRealm"/>
        <testDeviceId provisioningType="none"/>
    </mobileSecurityTest>

    <webSecurityTest name="WST1">
        <testUser realm="AdapterAuthRealm"/>
    </webSecurityTest>

    <customSecurityTest name="Master-Password">
        <test realm="AdapterAuthRealm" isInternalUserID="true"/>
    </customSecurityTest>

Authentication was running fine till I had only the customSecurityTest being defined.

After adding web and mobile security test, there is no response when I give the credentials and click login neither from GUI side nor from the console logs side.

I have also added security test in android tag in application-descriptor.xml as below

<android securityTest="MST1" version="1.0"> 
    <worklightSettings include="false"/>        
    <pushSender key="xxxxxxxxxxx" senderId="xxxxxxxxxxxxxxx"/>

    <security>
        <encryptWebResources enabled="false"/>
        <testWebResourcesChecksum enabled="false" ignoreFileExtensions="png, jpg, jpeg, gif, mp4, mp3"/>
        <publicSigningKey/>
        <packageName/>
    </security>
</android>



via Chebli Mohamed

Angularjs recursive directive

I am trying to write a recursive directive. I have seen this thread: Recursion in Angular directives

It works when you put the recursive directive under ul-li but goes into infinite loop with a table-tr

<table> 
  <tr>
    <td>{{ family.name  }}</td>
  </tr>
  <tr ng-repeat="child in family.children">
    <tree family="child"></tree>
  </tr>
</table>

Here is a plunker : http://ift.tt/1LnI4Uo

EDIT: I am not trying to build a tree directive.In my recursive directive I have to use table and tr tags.



via Chebli Mohamed

Linux Kernel Generic Netlink - Is it concurrent?

Say that i have registered a generic netlink interface using genl_register_family_with_ops with multiple callbacks.

I don't see any warnings about it and I assume the callbacks are serially called but there is no information about how the callbacks are called neither.

Is it possible that multiple callbacks are called concurrently on the same generic netlink interface I have registered? Do I need any synchronization between the callbacks?

To make the question simpler:

Can a single netlink callback be preempted or concurrently run in two cores?



via Chebli Mohamed

Android - API key for GoogleMaps API V2 for release

I have trouble with GoogleAPI in my app. I use Google Maps and Places - both needs API key. Everything works fine, until I upload my signed app to Google Play. From what I know and from what I read so far, the API key has to have the same fingerprint as my signed app to work properly from app downloaded from GP. So I created a new API key, add two fingerprints with package name to this key. First with fingerprint from debug.keystore and second from fingerprint from my keystore which I'm using for singning app when I do release build (I'm using android studio ->generate signed apk). This way I assumed that this will work for debug and release, but it work only for debug. To be sure that fingerprint of my app is the same as I have under Google API key I have implemented method which extract fingreprint of my app on runtime. They are match - when I do debug release I see fingerpring "A", when I do it for release I see "B" and I have both of then are the same as fingerprints which I have under API key (section Restrict usage to your Android apps). Note that package name is also correct.

Summary I don't know what I'm missing, or why this is not working when fingerprints are matched - result after release build is that Places api indicates KEY_INVALID and maps is gray, without titles.



via Chebli Mohamed

gender related translations with transchoice and lingohub

I have been trying to find a solution for this but have not found the answer that works for me. Basically what I want are gender specific translations in Symfony2 using twig and the service lingohub.

Our translations files for English look like this:

<trans-unit id="1234" resname="some_key">
  <source xml:lang="en">My text goes here </source>
  <target xml:lang="en">My text goes here </target>
</trans-unit>

for another language it would look like this:

<trans-unit id="2345" resname="some_key">
  <source xml:lang="en">My text goes here </source>
  <target xml:lang="es">My text in Spanish goes here</target>
</trans-unit>

what I now want is a gender specific translation. I would love to use transchoice and use the translations from my files

On the Symfony doc I can only find the example with static text.

Question is what do I have to put in twig and what into the translations files?

I tried to put the choices in twig but then it does not translate at all. I also tried to put one key and the choices in the translation file but this also does not work. It selects always the second option and also prints the text as it is (including {f} for female)

What I want is something like:

{% transchoice gender with {'%lastname%': user.lastname}  %}
  {f} key_for_female |{m} key_for_male | {u} key_for_unknown
{% endtranschoice %}

which will be replaced by translations like

<trans-unit id="1234" resname="key_for_female">
  <source xml:lang="en">Hello Ms %lastname% </source>
  <target xml:lang="en">Hello Ms %lastname%  </target>
</trans-unit>

so that the output is in the end "Hello Ms Doe". What is the correct syntax? ;)



via Chebli Mohamed

project folder, that contains sub-folder with .git folder seems issue

all the files in the folder are adding except the following one, i dont know what the issue, i guess there is a .git folder is that something related.

enter image description here

enter image description here

There are files and folders in the dompdf-module, need to be added to the repo.

enter image description here

These was the response after i add the files from the folder dino/dompdf-module

enter image description here



via Chebli Mohamed

ExtJs put a tooltip to the horizontal scroll controls Tab Panel

I have a tab panel with some items inside them, when I add many elements the panel puts a horizontal movement controlers, how can i do to put a tooltip in this controls?

Tab Panel

This is the definition of my tab Panel:

        var tabPanel = Ext.create('Ext.tab.Panel',{
        id: 'tabTabla',
        items: [{
            title: 'list1',
            tooltip: 'list1',
            items:[tree]
        }, {
            title: 'list2',
            tooltip: 'list2',
            autoWidth : true,
            autoHeight : true,
            plain : true,
            defaults : {
                autoScroll : true,
                bodyPadding : 0
            },
            items: [{
                xtype : 'label',
                text : 'list description.',
            },
            gridV]
        },{
            title: 'list3',
            tooltip: 'list3',
            autoWidth : true,
            autoHeight : true,
            plain : true,
            defaults : {
                autoScroll : true,
                bodyPadding : 0
            },
            items: [
                    gridC
                    ]
        }]
    });

In this tab Panel I add more panels:

    Ext.apply(this, {
        title: 'TITLE',
        constrain: true,
        header : {
            titlePosition : 2,
            titleAlign : 'center'
        },
        closable : false,
        x : 20,
        y : 270,
        layout : 'fit',
        animCollapse : true,
        collapsible : true,
        collapseDirection : Ext.Component.DIRECTION_LEFT,
        items: [tabPanel]
    });



via Chebli Mohamed

How to get raw User Timings data using Google Analytics Core Reporting API

I'm using User Timings to measure how long something takes, by doing e.g. ga('send', 'timing', 'jQuery', 'Load Library', 20, 'Google CDN');

In Google Analytics web interface at Behavior > Site Speed > User Timings I can see both an average and an histogram (by clicking the tab Distribution).

Using the Analytics Core Reporting API I'm able to retrieve the average user timing by querying on the metric ga:avgUserTimingValue. I was wondering if it's possible to retrieve the histogram or the raw data itself. I'm specifically looking to create a box plot using the user timings data.



via Chebli Mohamed

Decimal to Binary Java

I want convert just 256 numbers to binary without using if, while, etc., just by using the ? operator and four binary operators.

My programs works well for numbers 1 to 64, but after 64 it does not work! How can I do this? I must store all results in the variable b.

public class NaarBinair {
    public static int g=1,b=0;

    public static void main(String[] args){
        int r1 = g % 2 ;        
        int q1 = g / 2 ;
        int r2 = q1 % 2 ;
        int q2 = q1 / 2 ;
        int r3 = q2 % 2 ;       
        int q3 = q2 / 2 ;
        int r4 = q3 % 2 ;       
        int q4 = q3 / 2 ;
        int r5 = q4 % 2 ;       
        int q5 = q4 / 2 ;
        int r6 = q5 % 2 ;       
        int q6 = r5 / 2 ;
        int r7 = q6 % 2 ;       
        int q7 = r6 / 2 ;

        String s1 =  String.valueOf(r1) ;           
        String s2 =  String.valueOf(r2) ;
        String s3 =  String.valueOf(r3) ;
        String s4 =  String.valueOf(r4) ;       
        String s5 =  String.valueOf(r5) ;
        String s6 =  String.valueOf(r6) ;
        String s7 =  String.valueOf(r7) ;

        b = Integer.parseInt( s7 + s6 + s5 + s4 + s3 + s2 + s1 ) ;
        System.out.println(b);
    }
}



via Chebli Mohamed

Complex Join with AutoMapper and EF 6

I have a complex database Model with joins. I don't want to use store procedure so I want to use AutoMapper to flatten it so I can query it. I can't seem to figure out how to flatten it using AutoMapper and structuremap. Below are my classes generated from the Entity Framework using code first from existing database. I am using an Interface and Implementing a class to query the objects. I need to get users who has permissions to a contract.

[Table("Contract")] public class Contract { public Contract() { CDRLs = new HashSet(); ContractDocuments = new HashSet(); WDTOes = new HashSet(); }

[Table("PMO")]
public class PMO
{         
    public PMO()
    {
        Contracts = new HashSet<Contract>();
        Products = new HashSet<Product>();
        USERS = new HashSet<USER>();
    }

     [Table("USERS")]
public class USER
{

    public USER()
    {
        Organizations = new HashSet<Organization>();
        Organizations1 = new HashSet<Organization>();
        Products = new HashSet<Product>();
        Products1 = new HashSet<Product>();
        Programs = new HashSet<Program>();
        Programs1 = new HashSet<Program>();
        PMOes = new HashSet<PMO>();
        ROLES = new HashSet<ROLE>();
    }


    [Table("ROLES")]
public class ROLE
{

    public ROLE()
    {
        PERMISSIONS = new HashSet<PERMISSION>();
        USERS = new HashSet<USER>();
        LastModified = DateTime.Now;
        InsertDate = DateTime.Now;
    }

[Table("PERMISSIONS")] public class PERMISSION {

    public PERMISSION()
    {
        ROLES = new HashSet<ROLE>();
    }



via Chebli Mohamed

mardi 4 août 2015

XNA / Monogame Texture2D to to string

I want to store a small png image in a XML file and Load it back to Texture2D.

This is what I'm doing

Code for saving

I'm writing the data of the Texture2D with the BinaryWriter to a MemoryStream,

then converting the MemoryStream to an Array. I have to Convert the array to a Base64String because you can't save all characters

in a XML file.

The string is saved in my XML file.

    public static string SaveTextureData(this Texture2D texture)
    {
        int width = texture.Width;
        int height = texture.Height;
        Color[] data = new Color[width * height];
        texture.GetData<Color>(data, 0, data.Length);

        MemoryStream streamOut = new MemoryStream();

        BinaryWriter writer = new BinaryWriter(streamOut);

           writer.Write(width);
            writer.Write(height);
            writer.Write(data.Length);

            for (int i = 0; i < data.Length; i++)
            {
                writer.Write(data[i].R);
                writer.Write(data[i].G);
                writer.Write(data[i].B);
                writer.Write(data[i].A);
            } 

        return Convert.ToBase64String(streamOut.ToArray());
    }

Code for Loading

Same here.. I'm converting the Base64Str to an array and trying to read it.

But I cant read it back.

    public static Texture2D LoadTextureData(this string gfxdata, GraphicsDevice gfxdev)
    {
        byte[] arr = Convert.FromBase64String(gfxdata);

        MemoryStream input = new MemoryStream();

        BinaryWriter bw = new BinaryWriter(input);
        bw.Write(arr);

        using (BinaryReader reader = new BinaryReader(input))
        {
            var width = reader.ReadInt32();
            var height = reader.ReadInt32();
            var length = reader.ReadInt32();
            var data = new Color[length];

            for (int i = 0; i < data.Length; i++)
            {
                var r = reader.ReadByte();
                var g = reader.ReadByte();
                var b = reader.ReadByte();
                var a = reader.ReadByte();
                data[i] = new Color(r, g, b, a);
            }

            var texture = new Texture2D(gfxdev, width, height);
            texture.SetData<Color>(data, 0, data.Length);
            return texture;
        }
    }

Could need some help here.

Getting an exception in the reading method that the value couldnt read. in line var width = reader.ReadInt32();

R devtools fails as "Package libxml-2.0 was not found in the pkg-config search path"

I am trying to install devtools in R version 3.2.1, however when I do the following error is thrown:

Package libxml-2.0 was not found in the pkg-config search path.
Perhaps you should add the directory containing libxml-2.0.pc
to the PKG_CONFIG_PATH environment variable

when I run dpkg -L libxml2-dev in a terminal I find:

/usr
/usr/bin
/usr/bin/xml2-config
/usr/share
/usr/share/aclocal
/usr/share/aclocal/libxml2.m4
/usr/share/doc
/usr/share/doc/libxml2-dev
/usr/share/doc/libxml2-dev/copyright
/usr/share/man
/usr/share/man/man1
/usr/share/man/man1/xml2-config.1.gz
/usr/share/man/man3
/usr/share/man/man3/libxml.3.gz
/usr/lib
/usr/lib/x86_64-linux-gnu
/usr/lib/x86_64-linux-gnu/libxml2.a
/usr/lib/x86_64-linux-gnu/pkgconfig
/usr/lib/x86_64-linux-gnu/pkgconfig/libxml-2.0.pc
/usr/lib/x86_64-linux-gnu/xml2Conf.sh
/usr/include
/usr/include/libxml2
/usr/include/libxml2/libxml
/usr/include/libxml2/libxml/globals.h
/usr/include/libxml2/libxml/schematron.h
/usr/include/libxml2/libxml/xlink.h
/usr/include/libxml2/libxml/HTMLparser.h
/usr/include/libxml2/libxml/pattern.h
/usr/include/libxml2/libxml/xmlexports.h
/usr/include/libxml2/libxml/xmlschemas.h
/usr/include/libxml2/libxml/list.h
/usr/include/libxml2/libxml/entities.h
/usr/include/libxml2/libxml/xmlstring.h
/usr/include/libxml2/libxml/encoding.h
/usr/include/libxml2/libxml/hash.h
/usr/include/libxml2/libxml/xmlmemory.h
/usr/include/libxml2/libxml/relaxng.h
/usr/include/libxml2/libxml/xmlsave.h
/usr/include/libxml2/libxml/SAX2.h
/usr/include/libxml2/libxml/xmlIO.h
/usr/include/libxml2/libxml/xmlschemastypes.h
/usr/include/libxml2/libxml/xpathInternals.h
/usr/include/libxml2/libxml/schemasInternals.h
/usr/include/libxml2/libxml/xmlmodule.h
/usr/include/libxml2/libxml/valid.h
/usr/include/libxml2/libxml/c14n.h
/usr/include/libxml2/libxml/xmlwriter.h
/usr/include/libxml2/libxml/tree.h
/usr/include/libxml2/libxml/xmlunicode.h
/usr/include/libxml2/libxml/nanohttp.h
/usr/include/libxml2/libxml/catalog.h
/usr/include/libxml2/libxml/xmlerror.h
/usr/include/libxml2/libxml/nanoftp.h
/usr/include/libxml2/libxml/xmlautomata.h
/usr/include/libxml2/libxml/xinclude.h
/usr/include/libxml2/libxml/HTMLtree.h
/usr/include/libxml2/libxml/chvalid.h
/usr/include/libxml2/libxml/parserInternals.h
/usr/include/libxml2/libxml/xpointer.h
/usr/include/libxml2/libxml/xmlversion.h
/usr/include/libxml2/libxml/dict.h
/usr/include/libxml2/libxml/xmlregexp.h
/usr/include/libxml2/libxml/DOCBparser.h
/usr/include/libxml2/libxml/parser.h
/usr/include/libxml2/libxml/xmlreader.h
/usr/include/libxml2/libxml/SAX.h
/usr/include/libxml2/libxml/threads.h
/usr/include/libxml2/libxml/debugXML.h
/usr/include/libxml2/libxml/xpath.h
/usr/include/libxml2/libxml/uri.h
/usr/share/doc/libxml2-dev/README
/usr/share/doc/libxml2-dev/NEWS.gz
/usr/share/doc/libxml2-dev/AUTHORS
/usr/share/doc/libxml2-dev/TODO.gz
/usr/share/doc/libxml2-dev/changelog.Debian.gz
/usr/lib/x86_64-linux-gnu/libxml2.so

to try and add this to the PKG_CONFIG_PATH I tried: env PKG_CONFIG_PATH=/usr/lib/x86_64-linux-gnu/pkgconfig however this does not seem to work.

How to manipulate a tabbed view in Titanium and add SQLite content?

The Overview

I am fairly new to Titanium and I decided to finally start working with SQLite and some new UI features. I opted for the TabGroup as I felt that would be the best option. However I'm having a few issues. I am trying to simply get some quotes which have been inserted to a table (tested and working, I alerted them out and it worked) and I wish to display them out in the wiseWords tab, so the user can view them.

The Code

index.xml

<Alloy id="index">
    <TabGroup>
        <Require src="home"></Require>
        <Require src="wiseWords"></Require>
        <Require src="settings"></Require>
    </TabGroup>
</Alloy>

index.js

$.index.open(); 

/** Create and populate the wise words table. **/
Alloy.Globals.createRequiredTables();

var selectWiseWordsSQL = "SELECT * FROM wise_words";
var selectWiseWords = Titanium.App.db.execute(selectWiseWordsSQL);

while (selectWiseWords.isValidRow()) {
    /** Create labels for each quote. **/
    var addQuote = Titanium.UI.createLabel({
        text : selectWiseWords.fieldByName("saying") + " - " + selectWiseWords.fieldByName("quoted_by"),
    });

    /** Add quote to window (available in wiseWords.xml). **/
    $.wiseWordsWindow.add(addQuote);

    selectWiseWords.next();
}
selectWiseWords.close();

wiseWords.xml

<Alloy>
    <Tab id="wiseWordsTab" title="Wise Words">
        <Window id="wiseWordsWindow" class="container" title="Wise Words">  
        </Window>
    </Tab>
</Alloy>

The Error(s)

Runetime Error

Location: alloy/controllers/index.js

Uncaught TypeError: Cannot call method 'add' of undefined.

Source: $.wiseWordsWindow.add(addQuote);

To Clarify...

I understand what the error means, but don't understand why it is being thrown.

  1. Why can't I access the view for wiseWords.xml in index.js even though wiseWords is referenced in index.xml through the <Require> tag?

registerClassCommandBinding / Ribbon Class - Binding not firing

I'm trying to implement contextual help, when a button in the Ribbon Class has been selected. Try as I might, I can't seem to get the button firing on the Application Help command via this binding:

            CommandManager.RegisterClassCommandBinding(typeof(UIElement), new CommandBinding(ApplicationCommands.Help, new ExecutedRoutedEventHandler(ShowHelpExecuted),
                   new CanExecuteRoutedEventHandler(ShowHelpCanExecute)));

I've even tried this:

                CommandManager.RegisterClassCommandBinding(typeof(**RibbonToggleButton**), new CommandBinding(ApplicationCommands.Help, new ExecutedRoutedEventHandler(ShowHelpExecuted),
                   new CanExecuteRoutedEventHandler(ShowHelpCanExecute)));

For a direct binding to the button class, but I still don't get called when the Help (F1) button is called.

What does happen is the method is invoked, but the sender of the method is the main from that the control resides on, rather than the actual button that has focus. I want to provide help specific to the control that has focus (in this case the button), rather than just the form that the button resides on.

Here's a portion of the XML for the ribbon until the first toggle button

<Grid Name="GridRibbonBar"
          Grid.Row="0"
          Grid.Column="0"
          IsHitTestVisible="True">


        <Ribbon x:Name="RibbonMain"
                Background="AliceBlue"
                ContextMenu="{x:Null}"
                PreviewMouseLeftButtonDown="RibbonMain_OnPreviewMouseLeftButtonDown"
                ShowQuickAccessToolBarOnTop="False">


            <Ribbon.TitleTemplate>
                <DataTemplate>
                    <TextBlock TextAlignment="Center"
                               HorizontalAlignment="Center"
                               VerticalAlignment="Center"
                               FontWeight="SemiBold"
                               Width="{Binding ElementName=Window, Path=ActualWidth}"
                               Text="{x:Static p:Resources.Title}">
                        <TextBlock.Effect>
                            <DropShadowEffect ShadowDepth="0"
                                              Color="MintCream "
                                              BlurRadius="10" />
                        </TextBlock.Effect>
                    </TextBlock>
                </DataTemplate>
            </Ribbon.TitleTemplate>

            <Ribbon.ApplicationMenu>
                <RibbonApplicationMenu Visibility="Collapsed" />
            </Ribbon.ApplicationMenu>

            <!--Options Tab-->
            <RibbonTab Header="{x:Static p:Resources.treeHdrOptions}"
                       ContextMenu="{x:Null}">
                <RibbonGroup Header="{x:Static p:Resources.ribbonGroupGuestAccount}"
                             Visibility="{Binding Path=LoginViewModel.User.IsOwnerOrPowerOfAttorney,Converter={StaticResource VisibilityConverter},Source={StaticResource ViewModelLocatorService}}"
                             ContextMenu="{x:Null}">
                    <RibbonGroup.ItemsPanel>
                        <ItemsPanelTemplate>
                            <WrapPanel Orientation="Horizontal"
                                       Width="50" />
                        </ItemsPanelTemplate>
                    </RibbonGroup.ItemsPanel>
                    <RibbonToggleButton Name="guestacount"
                                        Visibility="{Binding Path=LoginViewModel.User.IsOwnerOrPowerOfAttorney,Converter={StaticResource VisibilityConverter},Source={StaticResource ViewModelLocatorService}}"
                                        Label="{x:Static p:Resources.treeGuest}"
                                        SmallImageSource="../images/RibbonIcons/PNGFormat/GeneralGuest.png"
                                        LargeImageSource="../images/RibbonIcons/PNGFormat/GeneralGuest.png"
                                        Checked="RibbonToggleButton_OnChecked"
                                        ContextMenu="{x:Null}" />
                </RibbonGroup>
            </RibbonTab>