vendredi 11 septembre 2015

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

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?

Here is some barfed html for example purposes:

<span class="cmImageSliderIndicatorActive icon-circle-blank" data-set="0"></span>

<div class="janrain-share-providerslist-provider-image janrain-provider-icon-grayscale-email"></div>

There are more icons. It is not an icon class, that is why I'm using class*



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

Find the unique integer in an array

I am looking for an algorithm to solve the following problem: Given an integer array of size n, find one (arbitrary) element of this array which occurs exactly once. All numbers which do not fit this requirement occur an even number of times in the array. If the array does not contain any such number, the result is irrelevant.

An example would be the input [1, 2, 2, 4, 4, 2, 2, 3] with both 1 and 3 being a correct output.

Most importantly, the algorithm should run in O(n) time and require only O(1) additional space. I have been told that this is possible but could not come up with a solution myself.



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

Fixed topcontainer makes everything fixed

I am trying to make a website with a topcontainer with fixed position, giving id position:fixed; in CSS. However, this makes the following class fixed aswell even though I use postion:relative;. Can somebody please help me?

The HTML:

<!DOCTYPE HTML>
<html>
</html>
<body>
<link rel="stylesheet" href="../../css/style_four_sprint.css"/>


<script type="text/javascript">

    function selected_four_sprint(val){
    if (val == "next"){
        document.write(5 + 6)

        }

}
 </script>
<head>
<title>Hello Wolrd</title>
</head>

    <div class="top_container"> 
    <div class="top_container"> 
    <img id="loggo" src="../../images/logo_top_small.png"/>

    <div id="toolname">Love to all!</div>   

    <div class="select">
        <table>
            <tr>
                <td>What do you want?</td>
                <td>
                    <select id="four_sprint_select" onchange="selected_four_sprint(value);">
                        <option>Select</option>
                        <option value="next">Next</option>
                </td>
            </tr>
        <table>
    </div>
</div>
<div class="teams_container">
  <div id="no_team"> No team </div>
  <div id="bamse"> Bamse </div>
  <div id="skalman"> Skalman </div>
</div>

</body>

The css:

body, html {
padding:0;
width:100%;
margin:0;
height:2000px;
z-index:1;
background:white;
font-family:'Open Sans', 'Helvetica Neue', Helvetica, Arial, sans-serif;     
}

.top_container{
top:3px;
left:0px;
position:fixed;
height:43px;
width:100%;
border-bottom:1px solid #bcbaba;
z-index:15000;
background: #ffffff; /* Old browsers */
background: -moz-linear-gradient(top,  #ffffff 0%, #e5e5e5 100%); /* FF3.6+ */
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#ffffff), color-stop(100%,#e5e5e5)); /* Chrome,Safari4+ */
background: -webkit-linear-gradient(top,  #ffffff 0%,#e5e5e5 100%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(top,  #ffffff 0%,#e5e5e5 100%); /* Opera 11.10+ */
background: -ms-linear-gradient(top,  #ffffff 0%,#e5e5e5 100%); /* IE10+ */
background: linear-gradient(to bottom,  #ffffff 0%,#e5e5e5 100%); /* W3C */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffffff', endColorstr='#e5e5e5',GradientType=0 ); /* IE6-9 */
}

#toolname{
color:black;
float:left;
padding-right:20px;
position:relative;
margin-left:10px;
font-family:'Ericsson Capital TT';
z-index:2000;
font-size:15px;
margin-top:7px;
line-height:30px;
height:30px;
border-right:1px solid #DEDEDE;
/* border-bottom:1px solid #bcbaba;  */
}

#loggo{
margin-top:8px;
margin-left:8px;
float:left;
}

.select{
margin-left:10px;
float:left;
font-size:14px;
height:30px;
line-height:30px;
margin-top:5px;
border-right:1px solid #DEDEDE;
padding-right:10px;
}

.teams_container{
width:100%;
background-color:#55555;
padding-top:35px;   
position:relative;
right:200px;
font-size:25px;
}



via Chebli Mohamed

How to close the setting screen in android programmatically

I need close the settings screen from another app, how to works appLock.

here:

http://ift.tt/1EKZZaT

my service code, this code works OK

final ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
    Timer timer = new Timer();
    timer.scheduleAtFixedRate(
            new TimerTask() {
                public void run() {
                    String appProcesses = activityManager.getRunningTasks(1).get(0).topActivity.getPackageName();

                    if (appProcesses.equals("com.android.settings")) {
                        Intent i1=new Intent(service.this, LockedScreen.class);
                        i1.setAction(Intent.ACTION_MAIN);
                        i1.addCategory(Intent.CATEGORY_HOME);
                        i1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        i1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                        i1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                        startActivity(i1);

                    }
                }
            }
            , 0, 1000);

my lock screen code in backpresed and this code don't close settings activity:

 @Override
public void onBackPressed() {
    super.onBackPressed();
    try {
        ActivityManager am = (ActivityManager) getApplicationContext().getSystemService("Settings");
        Method forceStopPackage;
        forceStopPackage = am.getClass().getDeclaredMethod("forceStopPackage", String.class);
        forceStopPackage.setAccessible(true);
        forceStopPackage.invoke(am, "com.android.settings");
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
}

error in backpressed, this error is in forceStopPackage = am.getClass().getDeclaredMethod("forceStopPackage", String.class);:

09-11 09:35:21.315    3037-3037/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
        at pe.com.oscar.settingsintent.LockedScreen.onBackPressed(LockedScreen.java:41)
        at android.app.Activity.onKeyUp(Activity.java:2361)
        at android.view.KeyEvent.dispatch(KeyEvent.java:2707)
        at android.app.Activity.dispatchKeyEvent(Activity.java:2594)
        at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchKeyEvent(PhoneWindow.java:2098)
        at android.view.ViewRootImpl.deliverKeyEventPostIme(ViewRootImpl.java:3608)
        at android.view.ViewRootImpl.handleImeFinishedEvent(ViewRootImpl.java:3578)
        at android.view.ViewRootImpl$ViewRootHandler.handleMessage(ViewRootImpl.java:2828)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:153)
        at android.app.ActivityThread.main(ActivityThread.java:5071)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
        at dalvik.system.NativeStart.main(Native Method)

HELPP PLEASE!!



via Chebli Mohamed

how unreferred values from string pool get remove?

I'm curious, how values from string-pool get removed?

suppose:

String a = "ABC"; // has reference of string-pool
String b = new String("ABC"); // has heap reference

b = null;
a= null;

In case of GC, "ABC" from heap get collected.But "ABC" still there in pool(because its in permGen and GC would not effect it).

if we keep adding values like

String c = "ABC"; // pointing to 'ABC' in pool. 

    for(int i=0; i< 10000; i++) {
      c = ""+i; // each iteration add new value in pool. and pervious values has no pointer  

    } 

I want to know, will pool remove unreferred values? if not, it's mean pool eating up unnecessary memory. than what's a point, jvm is using pool? when it could be a performance risk?



via Chebli Mohamed

IOS Developing:Tab Bar Item's Image Display a Blue Square

The bar item images I prepared are about 35*35 and I use the Sketch to export the [1x & 2x] size images; (I can't insert any images for instances at here because of my zero reputation//Sorry about this!)

Then it displays a blue square :<

the function and title of Item is OK

BUT just the icons are wrong

Could someone tells me how to fix it! Appreciate!!!



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

How can I connect to a MySQL database with passwords and usernames in Swift

Is it possible to connect to a MySQL from Swift with out having a .php script echoing JSON? I want to use it for passwords etc. So I can't have it visible for every one else.



via Chebli Mohamed

How to set React to production mode when running behind a python webserver

I need to run React in production mode, which presumably entails defining the following somewhere in the enviornment:

process.env.NODE_ENV = 'production';

The issue is that I'm running this behind Tornado (a python web-server), not Node.js. I also use Supervisord to manage the tornado instances, so it's not abundantly clear how to set this in the running environment.

I do however use Gulp to build my jsx files to javascript.

Is it possible to somehow set this inside Gulp? And if so, how do I check that React is running in production mode?

Here is my Gulpfile.js:

'use strict';

var gulp = require('gulp'),
        babelify = require('babelify'),
        browserify = require('browserify'),
        browserSync = require('browser-sync'),
        source = require('vinyl-source-stream'),
        uglify = require('gulp-uglify'),
        buffer = require('vinyl-buffer');

var vendors = [
    'react',
    'react-bootstrap',
    'jquery',
];

gulp.task('vendors', function () {
        var stream = browserify({
                        debug: false,
                        require: vendors
                });

        stream.bundle()
                    .pipe(source('vendors.min.js'))
                    .pipe(buffer())
                    .pipe(uglify())
                    .pipe(gulp.dest('build/js'));

        return stream;
});

gulp.task('app', function () {
        var stream = browserify({
                        entries: ['./app/app.jsx'],
                        transform: [babelify],
                        debug: false,
                        extensions: ['.jsx'],
                        fullPaths: false
                });

        vendors.forEach(function(vendor) {
                stream.external(vendor);
        });

        return stream.bundle()
                                 .pipe(source('build.min.js'))
                                 .pipe(buffer())
                                 .pipe(uglify())
                                 .pipe(gulp.dest('build/js'));

});

gulp.task('watch', [], function () {
    // gulp.watch(['./app/**/*.jsx'], ['app', browserSync.reload]);
    gulp.watch(['./app/**/*.jsx'], ['app']);
});

gulp.task('browsersync',['vendors','app'], function () {
        browserSync({
            server: {
                baseDir: './',
            },
            notify: false,
            browser: ["google chrome"]
    });
});

gulp.task('default',['browsersync','watch'], function() {});



via Chebli Mohamed

Optimize delivery of the same SVG image on a web page?

I have a SVG image that is typically displayed numerous times on a single page. I use the exact same tag each time I include the image.

<object width="50px" height="50px" data="/img/uimg0.svg" type="image/svg+xml">

For some reason web browsers are using multiple requests to repeatedly get the exact same SVG image file. Can this be coded differently so the data is downloaded once and reused?

enter image description here



via Chebli Mohamed

notifyDataSetChanged() crash app when call

I am using Fragment to create a app which i can slide left and right to view questions. When i submit a question from another fragement it will update the 2nd listFragment/listView. However it always crash. Furthermore i tried storing stuff into the variable '"storeText"', it will be null after onActivityCreated.

import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.widget.ArrayAdapter;

import java.util.ArrayList;



public class UserQuestion extends ListFragment {
    ArrayAdapter<String> adapter;
    private UserQuestionStorage storage = new UserQuestionStorage();
    private String storeText;

   @Override
   public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        //Set the list that was needed
        ArrayList<String> getQuestionList = storage.getQuestionList();
        this.adapter = new ArrayAdapter<String>(getActivity(),                       android.R.layout.simple_list_item_1, getQuestionList);

       //Test Storage
       this.storeQuestion(123, 1111, "Question 1", "true", "false");
       this.storeQuestion(123, 1111, "Question 2", "true", "false");

       storeText = "Storing this to variable.";

       setListAdapter(this.adapter);
    }

  public void storeQuestion(int id, int ownerID, String questionText, String optionOne, String optionTwo) {
      Question userQuestion = new Question();
      userQuestion.createQuestion(id, ownerID, questionText, optionOne, optionTwo);

      this.storage.storeQuestion(questionText);

      //TODO: This is not working
      Log.d("QUESTION", "" + this.storage.getQuestionList()); //Storage is always wipe.
      Log.d("ADAPTER", "" + adapter);
      Log.d("TESTSTRING", "" + storeText);
      //refreshList();
  }

  public void refreshList(){
      this.adapter.notifyDataSetChanged();
  }

}



via Chebli Mohamed

jQuery animation to make a png appear at a random point on the screen?

Again, working on a Chrome extension here. This time, I'm looking to make a transparent png appear at a random place within the window. I feel like I could somehow use jQuery .animate() somehow? I would like to make the image appear somewhere random on the screen, or have it appear on top of a random element on the screen, be it text of an image etc. I have not an idea where to even begin. Any ideas? All input appreciated!



via Chebli Mohamed

Intern: Chaining operations not returning promise

Using Intern I have to get an hidden json object from the page and then build a dictionary. After this, querying this dictionary I should perform an other action on the DOM. The problem is that I do not know how to bind these 2 things, because I want the second operation is executed after the first one is completed.

My code is something like:

    var self._formMap = null;

if(self._formMap === null || Object.keys(self._formMap).length === 0) {
    return remote.findByXpath(selector)
        .getAttribute('value')
        .then(function(value) {
            var jsonValue = JSON.parse(value);
            var formMap = {};
            for (var item in jsonValue) {
                if (jsonValue.hasOwnProperty(item)) {
                    var key = jsonValue[item][0].split(/[\/]+/).pop();
                    formMap[key] = item;
                }
            }
            return formMap;
        }).then(function (map) {
                self._formMap = map;
                return _super_.setInputInForm.call(this, [..., formMap, ..]); // function in another file, but that shares the same remote object.
        });

}

In the second step, when I call the setInputInForm, it's like the remote is undefined. Is it maybe because I'm returning the formMap in the first step? Could be a problem of promise? Furthermore, I would like to isolate the first steps, and put it into a function, always returning a promise.

Thanks.



via Chebli Mohamed

Angular tags directive issue

I am using pretty nice plugin which provides tags input directive for AngularJS.

I'm using the parameter onTagAdding to check tag's value before it will be added to input.

on-tag-adding="{expression}" 

So, as documentation says:

Expression to evaluate that will be invoked before adding a new tag. The new tag is available as $tag. This method must return either true or false. If false, the tag will not be added.

So here is an live example.

$scope.checkTag = function(tag) {
     angular.forEach($scope.forbiddenTags, function(e){
        if (e.text === tag.text) {
            alert('Tag is forbidden')
            return false;
        }
     })

     alert('Execution is continuing');
}

I'm expecting that if entered value matches one for those tags from $scope.forbiddenTags array, then false should be returned and function's execution should be stopped, but it works not like i am expecting =). I have tried just with return but it doesn't work either.

Any help and suggestions will be appreciated! Thanks in advance!



via Chebli Mohamed

Error installing XercesC with MinGW

I'm trying to build XercesC-3.2.1 with MinGW.

After running $ mingw32-make in the xerces directory, I get the following error:

mingw32-make[4]: Entering directory '/my/path/to/xerces-c-3.1.2/src'
process_begin: CreateProcess(NULL, /bin/mkdir -p xercesc/util, ...) failed.
make (e=2): The system cannot find the file specified.

Following the XercesC build instructions, I'm running the configure script as

$ ./configure CC=mingw32-gcc CXX=mingw32-g++

but without the variable LDFLAGS=-no-undefined. This is opposed to the build instructions in the XercesC webpage because otherwise the configure script will not work (the flag is not recognized by gcc). The configure script seems to run fine, however. After that, running mingw32-make gives the error above.

My mingw32-make and mingw32-gcc versions are

  • mingw32-gcc/g++ 4.8.1
  • mingw32-make 3.82.90

I tried adding C:\MinGW\libexec\gcc\mingw32\4.8.1 to my PATH, as suggested here but had no exit.

I also fresh installed MinGW in another machine that has no other compiler (or Cygwin, or anything) and got the same results.



via Chebli Mohamed

Circular dependency in rails form with nested attributes

I have the following model structure:

class Test < ActiveRecord::Base
  has_many :questions
end

class Question < ActiveRecord::Base
  belongs_to :test
  belongs_to :answer, class_name: 'Choice'
  has_many :choices, dependent: :destroy
end

class Choice < ActiveRecord::Base
  belongs_to :question
  has_one :question_answered, dependent: :nullify, class_name: 'Question', foreign_key: 'answer_id'
end

Now I wanted to create a single form where the user could create/save the tests params and edit all the questions and their choices, and also select which one is the correct answer.

The problem arrives when the user is creating a new question. None of the choices have an id and, therefore, I don't know how to define which will be the correct answer without having to write extra code on my controller (only using accepts_nested_attributes_for).

What I did is: Before saving the nested attributes of Test (but saving test before), I fetch from params all the questions and choices that don't have an id and save them. After that I update the answer_id params for all the questions.

This solutions is working right now but I don't think it's the most elegant one. Knowing Rails and its awesomeness, I know there is a better way of doing this. What do you guys suggest?



via Chebli Mohamed

How to use a html email signature that is hosted online?

for my email signature I want to use a hosted HTML code that is generated through a PHP script, since I may want to change information of the signature I really want that hosted solution to be sure that not only mails in the future, but also sent mails have the "new" signature.

I have a PHP script behind "http://ift.tt/1FBNQ2Z" (yes, no .php ending) waiting for a call. If i open that domain it will output valid HTML code.

But how can I embed the output in my mails as html signature? Iframes are not an option, since they dont work everywhere. Html img tags dont work since that url doesnt output an image.

Any ideas? :-) - Thanks!



via Chebli Mohamed

How to listen to a port(69) of a server using the TFTP session in java?

I want to get a file thrown by the client using the TFTP session. I mean the TFTP session has to listen to the port continuously and catch the file that was thrown from the client.

I have googled it and couldn't find any library except "package org.apache.commons.net.tftp". In this library I can able to find the methods for transferring the file from server from TFTP session and placing it in users PC and vice versa. but could not able to receive the file which is thrown by the client to the server.

Manually i can achieve this by starting the "pumpkin" as the tftp server and accept the file thrown by the client up on receiving the file through tftp session.where pumpkin will acts like a server on my system.

I can find the python library for the same it's "TFTPY".Can any one help me in doing this in java.Thanks in advance.



via Chebli Mohamed

Write a program to find whether the given string is Lucky or not using functions

Write a program to find whether the given string is Lucky or not.

A string is said to be lucky if the sum of the ASCII values of the characters in the string is even.

Function specifications:

  • int checkLucky(char * a)
  • The function accepts a pointer to a string and returns an int.
  • The return value is 1 if the string is lucky and 0 otherwise.


via Chebli Mohamed

MPMediaPlayer indexOfNowPlayingItem giving current index of 9223372036854775807

I am trying to make a music player, this is where I've put the NSLog to show the current index:

- (void) handle_NowPlayingItemChanged: (id) notification
{
    MPMediaItem *currentItem = [musicPlayer nowPlayingItem];
    NSUInteger currentIndex = [musicPlayer indexOfNowPlayingItem];
    UIImage *artworkImage = [UIImage imageNamed:@"NoSongImage.png"];
    MPMediaItemArtwork *artwork = [currentItem valueForProperty:MPMediaItemPropertyArtwork];

if (artwork) {
    artworkImage = [artwork imageWithSize: CGSizeMake (200, 200)];
}

[self.artwork setImage:artworkImage];

NSString *titleString = [currentItem valueForProperty:MPMediaItemPropertyTitle];
if (titleString) {
    self.songName.text = [NSString stringWithFormat:@"%@",titleString];
} else {
    self.songName.text = @"Unknown title";
}

    NSLog(@"%li", currentIndex);
}

this is my didSelectRowAtIndexPath for my UITableView:

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
if (songsList == YES){
    NSUInteger selectedIndex = [[self.tableView indexPathForSelectedRow] row];
    MPMediaItem *selectedItem = [[songs objectAtIndex:selectedIndex] representativeItem];
    [musicPlayer setQueueWithItemCollection:[MPMediaItemCollection collectionWithItems:[songsQuery items]]];
    [musicPlayer setNowPlayingItem:selectedItem];
    [musicPlayer play];
    songsList = NO;
}
else if (albumsList == YES && albumsSongsList == NO){
    albumsSongsList = YES;
    NSUInteger selectedIndex = [[self.tableView indexPathForSelectedRow] row];
    MPMediaItem *selectedItem = [[albums objectAtIndex:selectedIndex] representativeItem];
    albumTitle = [selectedItem valueForProperty:MPMediaItemPropertyAlbumTitle];
    MPMediaItemArtwork *albumArtwork = [selectedItem valueForProperty:MPMediaItemPropertyArtwork];
    albumSelected = [albumArtwork imageWithSize: CGSizeMake (44, 44)];
    [self.tableView reloadData];
    [self.tableView setContentOffset:CGPointZero animated:NO];
}
else if (albumsSongsList == YES){
    albumsSongsList = NO;
    MPMediaQuery *albumQuery = [MPMediaQuery albumsQuery];
    MPMediaPropertyPredicate *albumPredicate = [MPMediaPropertyPredicate predicateWithValue: albumTitle forProperty: MPMediaItemPropertyAlbumTitle];
    [albumQuery addFilterPredicate:albumPredicate];
    NSArray *albumTracks = [albumQuery items];
    NSUInteger selectedIndex = [[self.tableView indexPathForSelectedRow] row];
    MPMediaItem *selectedItem = [[albumTracks objectAtIndex:selectedIndex] representativeItem];
    [musicPlayer setQueueWithItemCollection:[MPMediaItemCollection collectionWithItems:[albumQuery items]]];
    [musicPlayer setNowPlayingItem:selectedItem];
    [musicPlayer play];
    }
}

The BOOLS determine to the tableView willDisplayCell which table to load. The above all display the UITableView correctly with the correct content. The problem is, when I open Albums, and select a song, it seems to play the first song of the album (at the top of the tableView) instead. If I then again go back to albums and select a different song, the correct song is selected. Then again, if I go back once more and select a song, the first song is played again and repeats so on...

In my NSLog, the reason its playing the first song due to a currentIndex of 9223372036854775807

Why is it returning this number, what am I doing incorrectly? Your help is very much appreciated.



via Chebli Mohamed

SQL Server 2014 read only connections not forwarding after reboot

I have a four node SQL Server 2014 (12.0.4416) environment with one node acting as a read only node. When I setup routing, I can use the applicationintent = readonly property and everything seems to work. My connections that use applicationintent readonly forward to the correct server. Confirmed by running a select @@servername.

However, when I disconnect the readonly replica from the network or reboot it, the connections now go back to reading from the primary.

Do you have to enable anything to get it working again after a reboot?



via Chebli Mohamed

C programming - While loop and scanf

Could anyone advise why my scanf function only works once and it ends in a continuous loop.

#include <stdio.h>
#include <conio.h>

int main(void)
{
    int accno;
    float bbal, charge, rebate, limit, balance;

    printf("Enter account number (-1 to end):");
    scanf("%d", &accno);

    while (accno != -1) // User input phase
    {
        printf("Enter beginning balance:"); // User input phase
        scanf(" %.2f ", &bbal); // leave space after scanf(" 

        printf("Enter total charges:");
        scanf(" %.2f ", &charge);

        printf("Enter total rebates:");
        scanf(" %.2f ", &rebate);

        printf("Enter credit limit:");
        scanf(" %.2f ", &limit);

        balance = bbal - charge + rebate;

        // credit limit exceeded phase
        if (balance > limit)
        {
            printf("Account: %u", accno);
            printf("Credit limit: %.2f", limit);

            balance = bbal - charge + rebate;

            printf("Balance: %.2f", balance);
            printf("Credit limit exceeded!");
        }
        printf("Enter account number (-1 to end):");
        scanf("%d", &accno);
    }

    getch();
}



via Chebli Mohamed

How would I sed replace a $VARIABLE in a $VARIABLE2 filename in a BASh (3.2) script for Mac

I have a BASh script which produces a script at /directory/filename.sh The file location and filename are a single variable. Because I used cat <<"EOT" >$FILELOCATION to produce the file, the file string is literal so I wasn't able to evaluate the variables inside it at the time it was produced. Instead, I used placeholders, then used sed afterwards.

Here is what I tried; in each instance, $NEWSTRING was not evaluated.

sed -i 's/STRINGTOREPLACE/$NEWSTRING/g' $FILELOCATION
sed -i 's/STRINGTOREPLACE/"$NEWSTRING"/g' $FILELOCATION
sed -i 's/STRINGTOREPLACE/'"$NEWSTRING"'/g' $FILELOCATION

Please advise on the correct way to evaluate a variable in sed within a BASh script.

Thank you!



via Chebli Mohamed

SQL Query to fetch information based on one or more condition. Getting combinations instead of exact number

I have two tables. Table 1 has about 750,000 rows and table 2 has 4 million rows. Table two has an extra ID field in which I am interested, so I want to write a query that will check if the 750,000 table 1 records exist in table 2. For all those rows in table 1 that exist in table 2, I want the respective ID based on same SSN. I tried the following query:

SELECT distinct b.UID, a.* 
  FROM [Analysis].[dbo].[Table1] A, [Proteus_8_2].dbo.Table2 B
  where a.ssn = b.ssn

Instead of getting 750,000 rows in the output, I am getting 5.4 million records. Where am i going wrong? Please help?



via Chebli Mohamed

Update dropdown option value and script onchange rather than onclick

I am simply trying to do away with the 'Result' button in the following script. I am happy for the first dropdown options to be selected on page load, and the script to already have run based on this output:

var dd1 = document.getElementById("dropdown");
var dd2 = document.getElementById("dropdown2");
var res = document.getElementById("result");
var output = document.getElementById("output");

function getSpecificText(v1, v2) {
    var con = v1.toString() + v2.toString();
    var res = "";
    switch (con) {
      case "500012":
        res = text1 ";
                break;
            case "
        500024 ":
                res = "
        text2 ";
                break;
            case "
        500036 ":
                res = "
        text3 ";
                break;
            case "
        500048 ":
                res = "
        text4 ";
                break;
            case "
        500060 ":
                res = "
        text1 ";
                break;
            case "
        1000012 ":
                res = "
        text2 ";
                break;
            case "
        1000024 ":
                res = "
        text3 ";
                break;
            case "
        1000036 ":
                res = "
        text4 ";
                break;
            case "
        1000048 ":
                res = "
        text1 ";
                break;
            case "
        1000060 ":
                res = "
        text2 ";
                break;
            case "
        1500012 ":
                res = "
        text3 ";
                break;
            case "
        1500024 ":
                res = "
        text4 ";
                break;
            case "
        1500036 ":
                res = "
        text1 ";
                break;
            case "
        1500048 ":
                res = "
        text2 ";
                break;
            case "
        1500060 ":
                res = "
        text3 ";
                break;
            case "
        2000012 ":
                res = "
        text3 ";
                break;
            case "
        2000024 ":
                res = "
        text4 ";
                break;
            case "
        2000036 ":
                res = "
        text1 ";
                break;
            case "
        2000048 ":
                res = "
        text2 ";
                break;
            case "
        2000060 ":
                res = "
        text3 ";
                break;
            case "
        2500012 ":
                res = "
        text3 ";
                break;
            case "
        2500024 ":
                res = "
        text4 ";
                break;
            case "
        2500036 ":
                res = "
        text1 ";
                break;
            case "
        2500048 ":
                res = "
        text2 ";
                break;
            case "
        2500060 ":
                res = "
        text3 ";
                break;
            // ...
        }
        return res
    }
    
    function getSelected() {
        var v1 = dd1.options[dd1.selectedIndex].value;
        var v2 = dd2.options[dd2.selectedIndex].value;
        output.innerHTML = getSpecificText(v1, v2);
    }
    
    res.addEventListener("
        click ", getSelected);
<p>
  Value:
  <select name="dropdown" id="dropdown">
    <option value="5000">5000</option>
    <option value="10000">10000</option>
    <option value="15000">15000</option>
    <option value="20000">20000</option>
    <option value="25000">25000</option>
  </select>
  Months:
  <select name="dropdown2" id="dropdown2">
    <option value="12">12</option>
    <option value="24">24</option>
    <option value="36">36</option>
    <option value="48">48</option>
    <option value="60">60</option>
  </select>
  Months
  <button id="result">Result</button>
  <div id="output"></div>
</p>


via Chebli Mohamed

Exclude a member for MDX forecasting using linear regression

I want to forecast measure value for the next month using data from complete previous months.

For example in this moment September 11, I have to forecast the value of the September month (cause the September month is not over) based on January-August values.

I am using MDX function LinRegPoint with the hierarchy detailed below

  • DimTime
    • Hierarchy Time
      • Year
      • Quarter
      • Month

This is the query I been trying without success:

WITH 
  MEMBER [Measures].[Trend] AS 
    LinRegPoint
    (
      Rank
      (
        [Time].[Hierarchy Time].CurrentMember
       ,[Time].[Hierarchy Time].CurrentMember.Level.MEMBERS
      )
     ,Descendants
      (
        [Time].[Hierarchy Time].[2015]
       ,[Time].[Hierarchy Time].CurrentMember.Level
      )
     ,[Measures].[Quality]
     ,Rank
      (
        [Time].[Hierarchy Time]
       ,[Time].[Hierarchy Time].Level.MEMBERS
      )
    ) 
SELECT 
  {
    [Measures].[Quality]
   ,[Measures].[Trend]
  } ON COLUMNS
 ,Descendants
  (
    [Time].[Hierarchy Time].[2015]
   ,[Time].[Hierarchy Time].[Month]
  ) ON ROWS
FROM [Cube];

The above query return all month forecasted values to today date including the September month, however It forecasts the September value taking the real values from January to September current date. I need the LinRegPoint function just takes the previous complete months in this case January to August.

enter image description here

Note the query returns a forecasted value for 9 month (September) but it is using the real value to calculate it. It would result in a misunderstood line as shown in the below images.

This image shows the drawn line taking the previous full-month (1-8): enter image description here

Note the positive slope line.

This image shows the drawn line taking all months (1-9) enter image description here

Note the negative slope line.

Question: How can I exclude the no complete current month from real values but allowing the forecasted value be calculated.

EDIT: The set should be changing to exclude the last month member in real values but calculating the forecasted value for it.

Thanks for considering my question.



via Chebli Mohamed

JavaScript's try-catch is failing on typeerror

Just saw this error today on our application. We have a small box on top right of the webpage. It gets updated every minute. What it does is make a jsonp call to each of our hospital partners via intranet and pulls the latest news. The issue doesn't happen often. I actually found out why the error is happening.

Uncaught TypeError: jQuery11020382352269484832883_1441911920555 is not a function

This error shows up in console when a jsonp request doesn't get the response from the jsonp service within the time assigned on the jsonp timeout.

I wrapped our endpoint call with try-catch but it is still spitting out that error. I want to get rid of "Uncaught TypeError" and display our own custom error.



via Chebli Mohamed

How to read a 10 GB txt file consisting of tab-separated double data line by line in C

I have a txt file consisting of tab-separated data with type double. The data file is over 10 GB, so I just wish to read the data line-by-line and then do some processing. Particularly, the data is layout as an matrix with, say 1001 columns, and millions of rows. Below is just a fake sample to show the layout.

10.2  30.4  42.9 ... 3232.000 23232.45
...
...
7.234  824.23232 ... 4009.23  230.01
...

For each line I'd like to store the first 1000 values in an array, and the last value in a separate variable. I am new to C, so it would be nice if you could kindly point out major steps.

Update:

Thanks for all valuable suggestions and solutions. I just figured out one simple example where I just read a 3-by-4 matrix row by row from a txt file. For each row, the first 3 elements are stored in x, and the last element is stored in vector y. So x is a n-by-p matrix with n=p=3, y is a 1-by-3 vector.

Below is my data file and my code.

Data file:

1.112272    -0.345324   0.608056    0.641006
-0.358203   0.300349    -1.113812   -0.321359
0.155588    2.081781    0.038588    -0.562489

My code:

#include<math.h>
#include <stdlib.h>
#include<stdio.h>
#include <string.h>

#define n 3
#define p 3

void main() {

    FILE *fpt;
    fpt = fopen("./data_temp.txt", "r");    

    char line[n*(p+1)*sizeof(double)];
    char *token;
    double *x;
    x = malloc(n*p*sizeof(double));
    double y[n];

    int index = 0;
    int xind = 0;
    int yind = 0;

    while(fgets(line, sizeof(line), fpt)) {
        //printf("%d\n", sizeof(line));
        //printf("%s\n", line);

        token = strtok(line, "\t");
        while(token != NULL) {
            printf("%s\n", token);

            if((index+1) % (p+1) == 0) { // the last element in each line;
                yind = (index + 1) / (p+1) - 1; // get index for y vector;
                sscanf(token, "%lf", &(y[yind]));
            } else {
                sscanf(token, "%lf", &(x[xind]));
                xind++;
            }
            //sscanf(token, "%lf", &(x[index]));
            index++;
            token = strtok(NULL, "\t");
        } 
    }

    int i = 0;
    int j = 0;
    puts("Print x matrix:");
    for(i = 0; i < n*p; i++) {
        printf("%f\n", x[i]);
    }
    printf("\n");

    puts("Print y vector:");
    for(j = 0; j < n; j++) {
        printf("%f\t", y[j]);
    }
    printf("\n");
    free(x);
    fclose(fpt);
}

With above, hopefully things will work if I replace data_temp.txt with my raw 10 GB data file (of course change values of n,p, and some other code wherever necessary.)

I have additional questions that I wish if you could help me.

  1. I first initialized char line[] as char line[(p+1)*sizeof(double)] (note not multiplying n). But the line cannot be read completely. How could I assign memory JUST for one single line? What's the lenght? I assume it's (p+1)*sizeof(double) since there are (p+1) doubles in each line. Should I also assign memory for \t and \n? If so, how?
  2. Does the code look reasonable to you? How could I make it more efficient since this code will be executed over millions of rows?
  3. If I don't know the number of columns or rows in the raw 10 GB file, how could I quickly count rows and columns?

Again I am new to C, any comments are very appreciated. Thanks a lot!



via Chebli Mohamed

Spark: split rows and accumulate

I have this code:

val rdd = sc.textFile(sample.log")
val splitRDD = rdd.map(r => StringUtils.splitPreserveAllTokens(r, "\\|"))
val rdd2 = splitRDD.filter(...).map(row => createRow(row, fieldsMap))
sqlContext.createDataFrame(rdd2, structType).save(
    org.apache.phoenix.spark, SaveMode.Overwrite, Map("table" -> table, "zkUrl" -> zkUrl))

def createRow(row: Array[String], fieldsMap: ListMap[Int, FieldConfig]): Row = {
    //add additional index for invalidValues
    val arrSize = fieldsMap.size + 1
    val arr = new Array[Any](arrSize)
    var invalidValues = ""
    for ((k, v) <- fieldsMap) {
      val valid = ...
      var value : Any = null
      if (valid) {
        value = row(k)
        // if (v.code == "SOURCE_NAME") --> 5th column in the row
        // sourceNameCount = row(k).split(",").size
      } else {
        invalidValues += v.code + " : " + row(k) + " | "
      }
      arr(k) = value
    }
    arr(arrSize - 1) = invalidValues
    Row.fromSeq(arr.toSeq)
}

fieldsMap contains the mapping of the input columns: (index, FieldConfig). Where FieldConfig class contains "code" and "dataType" values.

TOPIC -> (0, v.code = "TOPIC", v.dataType = "String")
GROUP -> (1, v.code = "GROUP")
SOURCE_NAME1,SOURCE_NAME2,SOURCE_NAME3 -> (4, v.code = "SOURCE_NAME")

This is the sample.log:

TOPIC|GROUP|TIMESTAMP|STATUS|SOURCE_NAME1,SOURCE_NAME2,SOURCE_NAME3|
SOURCE_TYPE1,SOURCE_TYPE2,SOURCE_TYPE3|SOURCE_COUNT1,SOURCE_COUNT2,SOURCE_COUNT3|
DEST_NAME1,DEST_NAME2,DEST_NAME3|DEST_TYPE1,DEST_TYPE2,DEST_TYPE3|
DEST_COUNT1,DEST_COUNT2,DEST_COUNT3|

The goal is to split the input (sample.log), based on the number of source_name(s).. In the example above, the output will have 3 rows:

TOPIC|GROUP|TIMESTAMP|STATUS|SOURCE_NAME1|SOURCE_TYPE1|SOURCE_COUNT1|
|DEST_NAME1|DEST_TYPE1|DEST_COUNT1|

TOPIC|GROUP|TIMESTAMP|STATUS|SOURCE_NAME2|SOURCE_TYPE2|SOURCE_COUNT2|
DEST_NAME2|DEST_TYPE2|DEST_COUNT2|

TOPIC|GROUP|TIMESTAMP|STATUS|SOURCE_NAME3|SOURCE_TYPE3|SOURCE_COUNT3|
|DEST_NAME3|DEST_TYPE3|DEST_COUNT3|

This is the new code I am working on (still using createRow defined above):

      val rdd2 = splitRDD.filter(...).flatMap(row => {

        val srcName = row(4).split(",")
        val srcType = row(5).split(",")
        val srcCount = row(6).split(",")

        val destName = row(7).split(",")
        val destType = row(8).split(",")
        val destCount = row(9).split(",")

        var newRDD: ArrayBuffer[Row] = new ArrayBuffer[Row]()

        //if (srcName != null) {
        println("\n\nsrcName.size: " + srcName.size + "\n\n")
        for (i <- 0 to srcName.size - 1) {
          // missing column: destType can sometimes be null

          val splittedRow: Array[Any] = Array(Row.fromSeq(Seq((row(0), row(1), row(2), row(3), 
            srcName(i), srcType(i), srcCount(i), destName(i), "", destCount(i)))))

          newRDD = newRDD ++ Seq(createRow(splittedRow, fieldsMap))
        }
        //}

        Seq(Row.fromSeq(Seq(newRDD)))

    })



via Chebli Mohamed

Width of selected text - jquery

I'm trying to get the width of a selected text in pixels and show it as an alert();. Does this exist?

EDIT (copied it from the comment I wrote below)

I did many efforts but all went in vain, now i'm trying to see if I can get the value of selection.toString() and then bind it to .width() if i can manage to do it, i'm pretty sure i can combine them both to get the width I'm looking for.

EDIT 12:42 am

I tried this

if(selection.toString() != '' ){
    var selected = selection.toString();
    alert($(selected).width());
}

I get the value of null



via Chebli Mohamed