vendredi 11 septembre 2015

In Pandoc, how do I add a newline between authors through the YAML metablock without modifying the template?

I am trying to add a a couple of authors to a report I am writing. Preferably, the second author would appear on a new line after the first. I know I can modify the template to add a new field or the multiple author example given in the Pandoc readme. However, I wonder if there is any character I can use to insert a new line between authors directly in the metablock. So far I have tried \newline, \\, | with newline and space, <br>, <div></div>, and making the author list a string with newline or double spaces between author names, but nothing has worked. My desired output is pdf.



via Chebli Mohamed

Angular $modal scope - Passing an object to $modal

I am attempting to pass angular's bootstrap modal the url of the image that was clicked in a angular masonry gallery. What I have is very close to the demo in the documentation with only a few changes. I know this is completely an issue with my own understanding of scope.

My modal HTML:

    <div class="modal-header">
        <h3 class="modal-title">I'm a modal!</h3>
    </div>
    <div class="modal-body">
        <ul>
            <li ng-repeat="item in items">
                <a href="#" ng-click="$event.preventDefault(); selected.item = item">{{ item }}</a>
            </li>
        </ul>
    </div>
    <div class="modal-footer">
        <button class="btn btn-primary" type="button" ng-click="ok()">OK</button>
        <button class="btn btn-warning" type="button" ng-click="cancel()">Cancel</button>
    </div>

And in my Controller:

angular.module('testApp').controller('GalleryCtrl', function ($scope, $modal, $log) {
  $scope.animationsEnabled = true;
  $scope.items = ['item1', 'item2', 'item3'];
  // Temporary Generation of images to replace with about us images
  function genBrick() {
      var height = ~~(Math.random() * 500) + 100;
      var id = ~~(Math.random() * 10000);
      return {
        src: 'http://placehold.it/' + width + 'x' + height + '?' + id
      };
  };
  this.bricks = [
    genBrick(),
    genBrick(),
    genBrick(),
    genBrick(),
    genBrick(),
    genBrick()
  ];
  this.showImage = function(item){
    alert(item.src); // gives me exactly what im trying to pass to the modal
    var modalInstance = $modal.open({
      animation: $scope.animationsEnabled,
      templateUrl: 'views/modal.html',
      scope: $scope,
      controller: 'GalleryCtrl',
      resolve: {
        items: function () {
          return $scope.items;
        }
      }
    });

    modalInstance.result.then(function (selectedItem) {
      $scope.selected = selectedItem;
    }, function () {
      $log.info('Modal dismissed at: ' + new Date());
    });

  }
});

Lastly for clarity, this is my masonry code

<div masonry>
    <div class="masonry-brick" ng-repeat="brick in gallery.bricks">
        <img ng-src="{{ brick.src }}" alt="A masonry brick" ng-click="gallery.showImage(brick)">
    </div>
</div>

Right now this works fine to return the items objects 3 values in li tags to the modal just like in the original example. What id really like to pass into the model is the (item.src) but no matter what i change it never seems to get passed in so that i can display it.



via Chebli Mohamed

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

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

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

Configure HTTPS port using netbeans

I have created one website using Netbeans on apache tomcat server using JSP. Currently, website is running on HTTP protocol. I just wanted to change the protocol from HTTP to secure protocol HTTPS. My website should only run on HTTPS port.

What configuration is required on server?

Please help me on this.



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

link in fastboot adb libraries into executeble

we are implementing an application in c/c++ which uses adb and fastboot. To use my application adb and fastboot should be installed. Is there any way to link in the fastboot, adb libraries into the executable so that its self-contained?

Thanks in Advance



via Chebli Mohamed

Get Cell Value with column name in Php Excel

This is my excel sheet Excel Sheet it has got lots of columns but i'm breaking down for ease in understanding the question

I'm reading Excel Sheet using PHP Excel and using rangeToArray() which give me all row from excel but i want the output as

Column as Key:Cell Value as Value

Currently I'm get output as

Col Index :Cell Value

So my Question is which is that function in Php Excel which return array with Column name and it Cell value?

try {
    $inputFileType = PHPExcel_IOFactory::identify($inputFileName);
    $objReader = PHPExcel_IOFactory::createReader($inputFileType);
    $objPHPExcel = $objReader->load($inputFileName);
} catch(Exception $e) {
    die('Error loading file"'.pathinfo($inputFileName,PATHINFO_BASENAME).'": '.$e->getMessage());
}
//  Get worksheet dimensions
$sheet = $objPHPExcel->getSheet(0); 
$highestRow = $sheet->getHighestRow(); 
$highestColumn = $sheet->getHighestColumn();
for ($row = 2; $row <= $highestRow; $row++){ 
    //  Read a row of data into an array
    $rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row,
                                            NULL,
                                            TRUE,
                                            FALSE);
    printArr($rowData);
    printArr("-------");

}

I get output as

Array
(
    [0] => Array
        (
            [0] => 27745186
            [1] => 42058
            [2] => DELL INTERNATIONAL SERVICES INDIA PVT LTD
            ...
            ...
         )
    [1] => Array
        (
            [0] => 27745186
            [1] => 42058
            [2] => DELL INTERNATIONAL SERVICES INDIA PVT LTD
            ...
            ...
         )
)

Desire Output

Array
(
    [0] => Array
        (
            [Invoice_no] => 27745186
            [Invoice Date] => 42058
            [Description] => DELL INTERNATIONAL SERVICES INDIA PVT LTD
            ...
            ...
         )
    [1] => Array
        (
            [Invoice_no] => 27745186
            [Invoice Date] => 42058
            [Description] => DELL INTERNATIONAL SERVICES INDIA PVT LTD
            ...
            ...
         )
)



via Chebli Mohamed

Angular datatable add row keep search value / display selected record

I have an angular datatable that is displaying "multiple" pages of 10 records each. If I use the search box to only view selected records and add a new row the table completely refreshes. The value in the search box is reset and my view goes back to the first page of records. Is it possible to maintain the value in the search box?

Similar but different. I have a radio button to select a record in the table. Is it possible when the table is redrawn to show the page with the selected record and not the first page.

enter image description here



via Chebli Mohamed

c++ not recognizing negative number as a number entered

In a program I have to write for class, I can not get the code to read a negative from cin to increment a variable by one.

int input;

while (input != 9999)
{
    sum += input;
    count ++;
}

There is other code that counts the number of pos, neg, and zeros entered. this is the only place count is used. so if I enter -10 then 9999, the sum is -10 and the number of negative is 1 but count says zero. i am using dev c++ as a compiler. and windows 10



via Chebli Mohamed

How can I show two background images, using internet explorer 6?

I need to show two background images. I'm doing this:

table.grid thead.grid-header th
{
    background: url('../images/up-down-arrow.gif') no-repeat center right, url('../images/tt-caption-light.gif') repeat;
}

This work fine in internet explorer 11, but I need to do this for internet explorer 6. How can I resolve it? Thank you very much!



via Chebli Mohamed

Invalid Swift Support - Files don’t match

I just re-wrote an app in Swift 2. I'm trying to upload the app to iTunesConnect (via Xcode 7 GM) for internal testing.

I wrestled with an "Invalid Swift Support" error for awhile (which has other, related questions) ... but now it's changed to something a little different.

The error from Apple now says:

Invalid Swift Support

The files libswiftCoreLocation.dylib, libswiftCoreMedia.dylib, libswiftCoreData.dylib, libswiftAVFoundation.dylib don’t match

/Payload/http://ift.tt/1XTi1Om, /Payload/http://ift.tt/1FBPwcO, /Payload/http://ift.tt/1XTi1Oo, /Payload/http://ift.tt/1FBPyBu

Make sure the files are correct (?), rebuild your app, and resubmit it.

Don’t apply post-processing to

/Payload/http://ift.tt/1XTi1Om, /Payload/http://ift.tt/1FBPwcO, /Payload/http://ift.tt/1XTi1Oo, /Payload/http://ift.tt/1FBPyBu.

I've been unable to find similar errors by searching for "Don’t apply post-processing", "Make sure the files are correct (?), rebuild your app, and resubmit it", etc.

Does anyone know how I can "Make sure the files are correct" --or-- any other recommendations? Thank you.



via Chebli Mohamed

C# FTP Download large files

i know this is probably not the first time, this is asked. But i can't find the solution to the problem..

  private void bgftpdownload_DoWork(object sender, DoWorkEventArgs e)
    {
        FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpurl + "/" + clientlabel.Text + "/data.7z");
        request.Credentials = new NetworkCredential(ftpuser, ftppass);
        request.Method = WebRequestMethods.Ftp.GetFileSize;
        request.Proxy = null;

        FtpWebResponse response = (FtpWebResponse)request.GetResponse();
        long fileSize = response.ContentLength;

        request = (FtpWebRequest)WebRequest.Create(ftpurl + "/" + clientlabel.Text + "/data.7z");
        request.Credentials = new NetworkCredential(ftpuser, ftppass);
        request.Method = WebRequestMethods.Ftp.DownloadFile;
        using (FtpWebResponse responseFileDownload = (FtpWebResponse)request.GetResponse())
        using (Stream responseStream = responseFileDownload.GetResponseStream())
        using (FileStream writeStream = new FileStream(LocationFile, FileMode.Create))
        {

            int Length = 2048;
            Byte[] buffer = new Byte[Length];
            int bytesRead = responseStream.Read(buffer, 0, Length);
            int bytes = 0;

            while (bytesRead > 0)
            {
                writeStream.Write(buffer, 0, bytesRead);
                bytesRead = responseStream.Read(buffer, 0, Length);
                bytes += bytesRead;
                int totalSize = (int)(fileSize / 1048576);
                bgftpdownload.ReportProgress((bytes / 1048576) * 100 / totalSize, totalSize);
            }
        }
    }
    private void bgftpdownload_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
            progresslabel.Text = e.ProgressPercentage * (int)e.UserState / 100 + " Mb / " + e.UserState + " Mb";
            progressBar1.Value = e.ProgressPercentage;
    }

I have this code, and its working great.. until its hitting a 2 gb file on the ftp server

I can read on other forums, the value limit for (int) is = 2147483591 So the problem is off cause my byte is getting higher than limit (2147483591)

What can i do to fix this problem?



via Chebli Mohamed

Comparing fix fields in quickfix for python

How can I compare two fix fields in quickfix for python? I've tried this:

execType = fix.ExecType(fix.Exectype_NEW)
if execType == fix.ExecType(fix.ExecType_NEW):
   print 'success'

, but didn't succed. Is there any other way to do it?



via Chebli Mohamed

Spring cannot create filter on online server only (works fine on the localhost)

My Spring application deploys and works fine on my localhost but fails on the online server with the following exception:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'webSecurityConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private it.kahoot.robot.rest.filter.SimpleCORSFilter it.kahoot.robot.rest.config.WebSecurityConfiguration.simpleCORSFilter; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'simpleCORSFilter': Requested bean is currently in creation: Is there an unresolvable circular reference?
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanP

The filter class is:

@Component
public class SimpleCORSFilter implements Filter {

    private static Logger logger = LoggerFactory.getLogger(SimpleCORSFilter.class);

    private static final String ORIGIN = "Origin";
    private static final String OPTIONS = "OPTIONS";
    private static final String OK = "OK";

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;

        if (httpServletRequest.getHeader(ORIGIN) != null) {
            String origin = httpServletRequest.getHeader(ORIGIN);
            httpServletResponse.setHeader("Access-Control-Allow-Origin", origin);
            httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
            httpServletResponse.setHeader("Access-Control-Max-Age", "3600");
            httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
            httpServletResponse.setHeader("Access-Control-Allow-Headers", "Accept-Language,Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,Authorization,Content-Disposition,Content-Length,"+CommonConstants.EXPORT_FILENAME_HEADER_NAME+","+CommonConstants.AUTH_HEADER_NAME);
            // Allow more than the 6 default headers to be returned, as the content length is required for a download file request to get the file size 
            httpServletResponse.setHeader("Access-Control-Expose-Headers", "Accept-Language,Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,Authorization,Content-Disposition,Content-Length,"+CommonConstants.EXPORT_FILENAME_HEADER_NAME+","+CommonConstants.AUTH_HEADER_NAME);
        }

        if (httpServletRequest.getMethod().equals(OPTIONS)) {
            try {
                httpServletResponse.getWriter().print(OK);
                httpServletResponse.getWriter().flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            filterChain.doFilter(servletRequest, servletResponse);
        }       
    }

    public void init(FilterConfig filterConfig) {
    }

    public void destroy() {
    }

}

Again, it works just fine on my localhost.



via Chebli Mohamed

Should i implement a database or let operating system manage files(Media Library Application)

I'm writing a media library application.(Like iTunes). Users can have thousands of media files.(Some files may be small like music and some files may be large like movies) Users should do operations like search,add,remove,change info etc. fast enough. I'm trying to make a decision about how i store & retrive these files.

One way: Like itunes i can create a folder for library, in that folder i can create another folder for each artist, in each artist folder i can create a folder for each album and at last in album folder i can store music files. I'll create another file for storing information about music files(Album arts, lyrics and etc.) This way is easy to implement and manage. It will be fast also.

Second way: I can store everything in 1 file. I can use a database to store everything or i can use other methods like BinarySerialization and creating my own file type. This file type can have media file itself and it's information in it. I don't know if its possible. I don't know if it will be fast enough to extract a file and change smthng on it and storing it back.

Should i use itune's way or can you recommand another way to do it.



via Chebli Mohamed

JQuery hide Class if other class is visible

I know this question already have asked before and i also tried the answer and it almost worked for me but there is one issue which i can't able to sort i tried plenty of ways but all in wain. This is the div i want to hide

    <div class="price-box" itemprop="offers" itemscope="" itemtype="http://schema.org/Offer">

       <p class="price"><span class="special-price" style="display: none;">
        <span class="amount">$43.50</span>
        </span>
       </p>
    </div>

when this div is not empty

<div class="single_variation"><span class="price"><span class="amount">$43.50</span></span></div>

This is what i implement

  jQuery(document).ready(function() {

    if( jQuery('.single_variation').is(':empty') ){
      alert('hi');
        jQuery('.price-box').show();
      }

});

and also

if($('.price').length){ $('.price-box').hide(); }



via Chebli Mohamed

Is the $scope.$apply() call warranted for this scenario?

New to AngularJS (and JavaScript frankly), but from what I've gathered, explicit calls to $scope.$apply() are only needed when changes happen outside of angular's radar. The code below (pasted in from this plunker) makes me think it wouldn't be a case where the call is required, but it's the only way I can get it to work. Is there a different approach I should be taking?

index.html:

<html ng-app="repro">
  <head> 
    ...
  </head>
  <body class="container" ng-controller="pageController">
    <table class="table table-hover table-bordered">
        <tr class="table-header-row">
          <td class="table-header">Name</td>
        </tr>
        <tr class="site-list-row" ng-repeat="link in siteList">
          <td>{{link.name}}
            <button class="btn btn-danger btn-xs action-button" ng-click="delete($index)">
              <span class="glyphicon glyphicon-remove"></span>
            </button>
          </td>
        </tr>
    </table>
  </body>
</html>

script.js:

var repro = angular.module('repro', []);

var DataStore = repro.service('DataStore', function() {
  var siteList = [];

  this.getSiteList = function(callback) {
    siteList = [ 
      { name: 'One'}, 
      { name: 'Two'}, 
      { name: 'Three'}];

    // Simulate the async delay
    setTimeout(function() { callback(siteList); }, 2000);
  }

  this.deleteSite = function(index) {
    if (siteList.length > index) {
      siteList.splice(index, 1);
    }
  };
});

repro.controller('pageController', ['$scope', 'DataStore', function($scope, DataStore) {
  DataStore.getSiteList(function(list) {

    $scope.siteList = list; // This doesn't work
    //$scope.$apply(function() { $scope.siteList = list; }); // This works

  });

  $scope.delete = function(index) {
    DataStore.deleteSite(index);
  };
}]);



via Chebli Mohamed

lifetime of a variable inside a self invoking anonymous function - function closures

I'm studying function closures from http://ift.tt/1vKs8WG

I don't understand the below code. variable add refers to a self-invoking anonymous function which returns an anonymous function. In this case, what happens to variable counter? when we call function add, what happens?

<!DOCTYPE html>
<html>
<body>

<p>Counting with a local variable.</p>

<button type="button" onclick="myFunction()">Count!</button>

<p id="demo">0</p>

<script>
var add = (function () {
    var counter = 0;    })();
    return function () {return counter += 1;}


function myFunction(){
    document.getElementById("demo").innerHTML = add();
}
</script>

</body>
</html>

in addition I dont understand why the code below does not work?

<!DOCTYPE html>
<html>
<body>

<p>Counting with a local variable.</p>

<button type="button" onclick="myFunction()">Count!</button>

<p id="demo">0</p>

<script>
var add = (function () {
    var counter = 0;
    return function () 
           {
             var semih=0;
             if(counter >5) 
             {
                 return function(){ semih += 5;  }
             }
             return counter += 1;}
           }
)();

function myFunction(){
    document.getElementById("demo").innerHTML = add();
}
</script>

</body>
</html>



via Chebli Mohamed

Assign line colors in pandas

I am trying to plot some data in pandas and the inbuilt plot function conveniently plots one line per column. What I want to do is to manually assign each line a color based on a classification I make.

The following works:

df = pd.DataFrame({'1': [1, 2, 3, 4], '2': [1, 2, 1, 2]})
s = pd.Series(['c','y'], index=['1','2'])
df.plot(color = s)

But when my indices are integers it no longer works and throws as KeyError:

df = pd.DataFrame({1: [1, 2, 3, 4], 2: [1, 2, 1, 2]})
s = pd.Series(['c','y'], index=[1,2])
df.plot(color = s)

The way I understand it is that when an integer index is used it somehow has to start from 0. That is my guess since the following works as well:

df = pd.DataFrame({0: [1, 2, 3, 4], 1: [1, 2, 1, 2]})
s = pd.Series(['c','y'], index=[1,0])
df.plot(color = s)

My question is:

  • What is happening here?
  • Assuming I have an integer index that does not start from 0 or is not formed of successive numbers, how can I make this work without having to convert the index to string or reindex starting from 0?

EDIT:

I realised that even in the first case, the code doesn't do what I expected it to do. It seems like pandas matches the index of DataFrame and Series only if both are integer indices starting from 0. If that isn't the case, a KeyError is thrown or if the index is a str the order of the elements is used.

Is this correct? And is there a way to match the Series and DataFrame indices? Or do I have to make sure I pass a list of colours in the right order?



via Chebli Mohamed

How to inscribe the following shape with CSS inside div?

FIDDLE enter image description here

HTML

<div id="DiamondCenter">
    <div id="triangle-topleft"></div>
</div>

CSS

#DiamondCenter {
    position:fixed;
    top:2%;
    left:48%;
    background: #24201a;
    height:40px;
    width:40px;
    -webkit-transform: rotate(45deg);
    -moz-transform: rotate(45deg);
    -ms-transform: rotate(45deg);
    -o-transform: rotate(45deg);
    transform: rotate(45deg);
    z-index:20 !important;
}
#triangle-topleft {
    width: 0;
    height: 0;
    border-top: 40px solid gray;
    border-right: 40px solid transparent;
}



via Chebli Mohamed

Roslyn - how to reliably format whitespace for a class

I need to format a class to ensure it's easily human readable. I have the syntax tree, the root CompilationUnitSyntax and the ClassDeclarationSyntax. I format the whitespace as follows.

root = root.ReplaceNode(classSyntax, classSyntax.NormalizeWhitespace(elasticTrivia: true));
syntaxTree = syntaxTree.WithRootAndOptions(root, syntaxTree.Options);

Before:

#region MyRegion
public class MyClass
{

    // Info about MyClass

}
#endregion

After:

#region MyRegion
public class MyClass
{
// Info about MyClass    
}#endregion

Why is the class's closing brace slammed into the #endregion?

If I run NormalizeWhitespace once more on the 'After' text, #endregion is moved back down onto its own line. Then a further call to NormalizeWhitespace moves it back up again. What is going on?



via Chebli Mohamed

Total time in python's line profiler is strange

This is my insertion.py:

import random

#@profile
def insertion_sort(l):
    for j in range(1, len(l)):
        k = l[j]
        i = j - 1
        while i >= 0 and l[i] > k:
            l[i + 1] = l[i]
            i -= 1
        l[i + 1] = k


if __name__ == '__main__':
    l = range(5000)
    random.shuffle(l)
    insertion_sort(l)

When I run time python insertion.py, I get:

real    0m0.823s
user    0m0.818s
sys     0m0.004s

But when I uncomment the profile decorator and run: kernprof -l -v insertion.py, I get:

Wrote profile results to insertion.py.lprof
Timer unit: 1e-06 s

Total time: 7.25971 s
File: insertion.py
Function: insertion_sort at line 4

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
 4                                           @profile
 5                                           def insertion_sort(l):
 6      5000         2110      0.4      0.0      for j in range(1, len(l)):
 7      4999         1929      0.4      0.0          k = l[j]
 8      4999         1719      0.3      0.0          i = j - 1
 9   6211255      2695158      0.4     37.1          while i >= 0 and l[i] > k:
10   6206256      2396675      0.4     33.0              l[i + 1] = l[i] 
11   6206256      2160158      0.3     29.8              i -= 1
12      4999         1959      0.4      0.0          l[i + 1] = k

My question is why total time of line profiler is much greater than the system time? I thought "Total time" of line profiler was describing how much time the function decorated with @profile was running. In my head, the output from time should be greater or at least close to line profiler. Am I interpreting the results wrong? Is line profiler adding its own time to "Total time"?



via Chebli Mohamed

Flattening an array recursively (withoout looping) javascript

I'm practicing recursion and am trying to flatten an array without looping (recursion only). As a first step I did the iterative approach and it worked, but am stuck on the pure recursion version:

function flattenRecursive(arr) {
    if (arr.length === 1) {
        return arr;
    }

    return Array.isArray(arr) ? arr = arr.concat(flattenRecursive(arr)) : flattenRecursive(arr.slice(1))
}

console.log(flattenRecursive([
    [2, 7],
    [8, 3],
    [1, 4], 7
])) //should return [2,7,8,3,1,4,7] but isn't - maximum call stack error


//working version (thanks @Dave!):

function flattenRecursive(arr) {
    if (arr.length === 1) {
        return arr;
    }

    return arr[0].concat(Array.isArray(arr) ? flattenRecursive(arr.slice(1)) : arr);
}

console.log(flattenRecursive([
    [2, 7],
    [8, 3],
    [1, 4], 7
]))

//returns [ 2, 7, 8, 3, 1, 4, 7 ]



via Chebli Mohamed

Insert data to MySQL database - iOS

I'm trying to insert data to table in MySQL database but it's not working. Code in .php file is correct but I think is something wrong with my app in objective-c. Problem is the data is not insert to database. Could you help me how can I insert data?

This is .php file:

<?php

    if (isset ($_POST["name"]) && isset ($_POST["age"])){
        $name = $_POST["name"];
        $age = $_POST["age"];
    }
    else {
        $name = "";
        $age = "";
    }

try {

    $con = new PDO("my domain without http://", "login", "password");
    $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $sql = "INSERT INTO NameOfDatabase.NameOfTable (NameOfColumn1, NameOfColumn2) VALUES ('$name', '$age')";
    // use exec() because no results are returned
    $con->exec($sql);
    echo "New record created successfully";
}
catch(PDOException $e)
{
    echo $sql . "<br>" . $e->getMessage();
}

$con = null;

?>

and this is code in app (objective-c):

NSString *strURL = [NSString stringWithFormat:@"my domain without http://?name=%@&age=%@", self.name.text, self.age.text];
    NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];
    NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
    NSLog(@"%@", strResult);



via Chebli Mohamed

Are Grails getDirtyPropertyNames and getPersistentValue supported by MongDB?

I am using Grails version 2.4.2 and MongoDB 2.6 Created a Domain class Foo

class Foo {
  String slug
  String name
  String toString(){
    "${name}"
  }
  static constraints = {
    name blank: false
  }
  @Override
  def beforeUpdate(){
  if(isDirty("slug"){
    println "beforeUpdate() current value is  " +  this.slug
    println "original property names that were changed = " +     this.getDirtyPropertyNames()
    println "original value = " + this.getPersistentValue("slug")
  } 
 }
}

I created a FooController with scaffolding

class FooController{
  static scaffold = true
}

I run the app and create a new foo enter a name field and a slug field value then update the slug field

Are these methods supported by MongoDB? getPersistentValue getDirtyPropertyNames



via Chebli Mohamed

What really happens on inheritance in Java?

Suppose I have two classes Parent and Child, and Child inherits from Parent. I have three methods in Parent, out of which two are public and one is private.

Normally we say that all the non-private methods are inherited into the Child class, but I'm confused about exactly what happens. Does Java make a copy of the methods in the Child class, or does it use some kind of reference to maintain the relationship?

class Parent{
    // Private method
    private void method1(){
        System.out.println("In private method of Parent class");
    }
    void method2(){
    // calling private method
        method1();
    }
    void method3(){
    // calling private method
        method1();
    }
}

class Child extends Parent{

}

class MainClass{
   public static void main(String[] args){
       Child child = new Child();
       // calling non-private method which internally calls the private method
       child.method2();
   }
}



via Chebli Mohamed