问:
Accessing variables shared between classes within an aggregator class
I have a problem in hand which requires to make a very modular design for different algorithms. For example population based optimization algorithms like genetic algorithm, particle swarm algorithm etc. There are several variants of these algorithms, therefore I planned to make the smaller building blocks as an abstract class and let the specific building block to be plugged in.

For example lets say we have algo1 which can be divided in the following subroutines

```<code>algo1
loop
{
  sub1 ()
  sub2 ()
  sub3 ()
}
</code>```

For this I can create three interfaces which the implementation will override as per their implementation. Therefore

```<code>//Sub1Class, Sub2Class, Sub3Class are interfaces/abstract classes
class algo1
{
  sub1Class *sub1Obj;
  sub2Class *sub2Obj;
  sub3Class *sub3Obj;
}

// constructor or setter method to set the implementation
algo1 (Sub1Class *myAlgo1Obj, Sub2Class myAlgo1Obj, Sub3Class myAlgo1Obj)
{
  sub1Obj = myAlgo1Obj;
  sub2Obj = myAlgo2Obj;
  sub3Obj = myAlgo3Obj;
}

doAlgo1
{
  loop
  {
    sub1Obj->algo ();
    sub2Obj->algo ();
    sub3Obj->algo ();
  }
}
</code>```

This can be done, but all the algorithms uses the attributes of the algo class and there are intermediate variables shared by the algorithms which I do not want to give a getter/setter.

My question is what are the techniques which can be used to manage the shared intermediate variables between the algorithms. I can pass it as the algo method implementation argument, but the number of intermediates and the types may change from one implementation to another. In that case will it be a good idea to create a separate class of temporary variable or make something like friend in cpp? Note that the intermediate results can be large vectors and matrices.

Please let me know if you need more information or clarification.

NOTE: I can possibly omit the variables shared between the algorithms by introducing locals and re-computation, but the algorithms are iterative and computation intensive involving large matrices therefore I want to make object creation and destruction as minimum as possible.

答:
I can propose to use Inverse of Control container to solve your problem.

First you should create several abstract classes to keep it in the container:

```<code>class ISubroutineState {
public:
    ISubroutineState() = default;

    virtual int getVar1() const = 0;
    virtual void setVar1(int v1) = 0;
};

class ISubroutineState1 : public ISubroutineState {
public:

    virtual std::string getVar2() const = 0;
    virtual void setVar2(std::string& v2) = 0;
};
</code>```

The example of the subroutine state class implementation:

```<code>class SubState1 : public ISubroutineState1 {
    int var1;
    std::string var2;

public:
    int getVar1() const {
        return var1;
    }

    std::string getVar2() const {
        return var2;
    }

    void setVar1(int v1) { var1 = v1; }
    void setVar2(std::string& v) { var2 = v; }
};
</code>```

The the IoC container (please note it can be accessed in any way allowed - i used just static pointer for simplicity):

```<code>class StateBroker
{
    std::map<const char*, ISubroutineState*> *storage;
public:
    StateBroker();

    template <class S>
    void StateBroker::bind(S* state) {
        storage->emplace(typeid(S).name(), state);
    }

    template <class S>
    S* StateBroker::get() const {
        auto found = storage->find(typeid(S).name());
        if (found == storage->end()) return NULL;
        return (S*)found->second;
    }

    ~StateBroker();
};

StateBroker* stateBroker;
</code>```

Now you can implement any type of the subroutines:

```<code> class ISubroutine {
 public:
    virtual void Execute() = 0;
 };

class Sub1Class : public ISubroutine {
public:
    void Execute()
    {
        if (stateBroker == NULL)
        {
            std::cout << "Sub1 called" << std::endl;
        }
        else {
            ISubroutineState1* ss1 = stateBroker->get<ISubroutineState1>();
            std::cout << "Sub1 with state called" << std::endl;
            ss1->setVar1(1);
            ss1->setVar2(std::string("State is changed by Sub1Class"));
            std::cout << *static_cast<SubState1*>(ss1) << std::endl;
        }
    }
};

class Sub2Class : public ISubroutine {
public:
    void Execute()
    {
        if (stateBroker == NULL)
        {
            std::cout << "Sub2 called" << std::endl;
        }
        else {
            ISubroutineState* ss1 = stateBroker->get<ISubroutineState>();
            std::cout << "Sub2 with state called" << std::endl;
            ss1->setVar1(2);
            std::cout << *static_cast<SubState1*>(ss1) << std::endl;
        }
   }
};

class Sub3Class : public ISubroutine {
public:
    void Execute()
    {
        if (stateBroker == NULL)
        {
            std::cout << "Sub3 called" << std::endl;
        }
        else {
            ISubroutineState1* ss1 = stateBroker->get<ISubroutineState1>();
            std::cout << "Sub3 with state called" << std::endl;
            ss1->setVar1(3);
            ss1->setVar2(std::string("State is changed by Sub3Class"));
            std::cout << *static_cast<SubState1*>(ss1) << std::endl;
        }
    }
};
</code>```

Also please note that subroutine' Execute() can request any type of subroutine state it requires to perform their tasks. It can even create additional state instances (to use in later stage of the algorithm, for example).

Now the main algorithm would look like this:

```<code>class Algo {
private:
    Sub1Class* sub1;
    Sub2Class* sub2;
    Sub3Class* sub3;

public:
    Algo(Sub1Class* s1, Sub2Class* s2, Sub3Class* s3) : sub1(s1), sub2(s2), sub3(s3){}

    void Execute()
    {
        sub1->Execute();
        sub2->Execute();
        sub3->Execute();
    }
 };
</code>```

... and it's usage (please note it can be used as stateless and as statefull depending on the fact the StateBroker is initialized or not)

```<code>Sub1Class s1;
Sub2Class s2;
Sub3Class s3;
std::cout << "Stateless algorithm" << std::endl;
Algo mainAlgo(&s1, &s2, &s3);
mainAlgo.Execute();

stateBroker = new StateBroker();
SubState1* state = new SubState1();
stateBroker->bind<ISubroutineState>(state);
stateBroker->bind<ISubroutineState1>(state);

std::cout << "Statefull algorithm" << std::endl;
Algo statefulAlgo(&s1, &s2, &s3);
statefulAlgo.Execute();
</code>```

Please note that Algo class doesn't know anything about subroutine states, state broker, etc.; Sub2Class doesn't know about ISubroutineState1; and StateBroker doesn't care about state and subroutine implementation.

BTW, you can review the example project at https://github.com/ohnefuenfter/cppRestudy (VS2015)

Body:
I have a problem in hand which requires to make a very modular design for different algorithms. For example population based optimization algorithms like genetic algorithm, particle swarm algorithm etc. There are several variants of these algorithms, therefore I planned to make the smaller building blocks as an abstract class and let the specific building block to be plugged in.

For example lets say we have algo1 which can be divided in the following subroutines

algo1
loop
{
  sub1 ()
  sub2 ()
  sub3 ()
}

For this I can create three interfaces which the implementation will override as per their implementation. Therefore

//Sub1Class, Sub2Class, Sub3Class are interfaces/abstract classes
class algo1
{
  sub1Class *sub1Obj;
  sub2Class *sub2Obj;
  sub3Class *sub3Obj;
}

// constructor or setter method to set the implementation
algo1 (Sub1Class *myAlgo1Obj, Sub2Class myAlgo1Obj, Sub3Class myAlgo1Obj)
{
  sub1Obj = myAlgo1Obj;
  sub2Obj = myAlgo2Obj;
  sub3Obj = myAlgo3Obj;
}

doAlgo1
{
  loop
  {
    sub1Obj->algo ();
    sub2Obj->algo ();
    sub3Obj->algo ();
  }
}

This can be done, but all the algorithms uses the attributes of the algo class and there are intermediate variables shared by the algorithms which I do not want to give a getter/setter.

My question is what are the techniques which can be used to manage the shared intermediate variables between the algorithms. I can pass it as the algo method implementation argument, but the number of intermediates and the types may change from one implementation to another. In that case will it be a good idea to create a separate class of temporary variable or make something like friend in cpp? Note that the intermediate results can be large vectors and matrices.

Please let me know if you need more information or clarification.

NOTE: I can possibly omit the variables shared between the algorithms by introducing locals and re-computation, but the algorithms are iterative and computation intensive involving large matrices therefore I want to make object creation and destruction as minimum as possible.

Body:
I can propose to use Inverse of Control container to solve your problem.

First you should create several abstract classes to keep it in the container:

class ISubroutineState {
public:
    ISubroutineState() = default;

    virtual int getVar1() const = 0;
    virtual void setVar1(int v1) = 0;
};

class ISubroutineState1 : public ISubroutineState {
public:

    virtual std::string getVar2() const = 0;
    virtual void setVar2(std::string& v2) = 0;
};

The example of the subroutine state class implementation:

class SubState1 : public ISubroutineState1 {
    int var1;
    std::string var2;

public:
    int getVar1() const {
        return var1;
    }

    std::string getVar2() const {
        return var2;
    }

    void setVar1(int v1) { var1 = v1; }
    void setVar2(std::string& v) { var2 = v; }
};

The the IoC container (please note it can be accessed in any way allowed - i used just static pointer for simplicity):

class StateBroker
{
    std::map<const char*, ISubroutineState*> *storage;
public:
    StateBroker();

    template <class S>
    void StateBroker::bind(S* state) {
        storage->emplace(typeid(S).name(), state);
    }

    template <class S>
    S* StateBroker::get() const {
        auto found = storage->find(typeid(S).name());
        if (found == storage->end()) return NULL;
        return (S*)found->second;
    }

    ~StateBroker();
};

StateBroker* stateBroker;

Now you can implement any type of the subroutines:

 class ISubroutine {
 public:
    virtual void Execute() = 0;
 };

class Sub1Class : public ISubroutine {
public:
    void Execute()
    {
        if (stateBroker == NULL)
        {
            std::cout << "Sub1 called" << std::endl;
        }
        else {
            ISubroutineState1* ss1 = stateBroker->get<ISubroutineState1>();
            std::cout << "Sub1 with state called" << std::endl;
            ss1->setVar1(1);
            ss1->setVar2(std::string("State is changed by Sub1Class"));
            std::cout << *static_cast<SubState1*>(ss1) << std::endl;
        }
    }
};

class Sub2Class : public ISubroutine {
public:
    void Execute()
    {
        if (stateBroker == NULL)
        {
            std::cout << "Sub2 called" << std::endl;
        }
        else {
            ISubroutineState* ss1 = stateBroker->get<ISubroutineState>();
            std::cout << "Sub2 with state called" << std::endl;
            ss1->setVar1(2);
            std::cout << *static_cast<SubState1*>(ss1) << std::endl;
        }
   }
};

class Sub3Class : public ISubroutine {
public:
    void Execute()
    {
        if (stateBroker == NULL)
        {
            std::cout << "Sub3 called" << std::endl;
        }
        else {
            ISubroutineState1* ss1 = stateBroker->get<ISubroutineState1>();
            std::cout << "Sub3 with state called" << std::endl;
            ss1->setVar1(3);
            ss1->setVar2(std::string("State is changed by Sub3Class"));
            std::cout << *static_cast<SubState1*>(ss1) << std::endl;
        }
    }
};

Also please note that subroutine' Execute() can request any type of subroutine state it requires to perform their tasks. It can even create additional state instances (to use in later stage of the algorithm, for example).

Now the main algorithm would look like this:

class Algo {
private:
    Sub1Class* sub1;
    Sub2Class* sub2;
    Sub3Class* sub3;

public:
    Algo(Sub1Class* s1, Sub2Class* s2, Sub3Class* s3) : sub1(s1), sub2(s2), sub3(s3){}

    void Execute()
    {
        sub1->Execute();
        sub2->Execute();
        sub3->Execute();
    }
 };

... and it's usage (please note it can be used as stateless and as statefull depending on the fact the StateBroker is initialized or not)

Sub1Class s1;
Sub2Class s2;
Sub3Class s3;
std::cout << "Stateless algorithm" << std::endl;
Algo mainAlgo(&s1, &s2, &s3);
mainAlgo.Execute();

stateBroker = new StateBroker();
SubState1* state = new SubState1();
stateBroker->bind<ISubroutineState>(state);
stateBroker->bind<ISubroutineState1>(state);

std::cout << "Statefull algorithm" << std::endl;
Algo statefulAlgo(&s1, &s2, &s3);
statefulAlgo.Execute();

Please note that Algo class doesn't know anything about subroutine states, state broker, etc.; Sub2Class doesn't know about ISubroutineState1; and StateBroker doesn't care about state and subroutine implementation.

BTW, you can review the example project at https://github.com/ohnefuenfter/cppRestudy (VS2015)


来源: stackexchange

问:
Laravel with xampp
I need to understand this behavior.

I use xampp for web development. I start to apache server in the xampp gui and then I can start my projects in the browser via localhost...

Since yesterday I have added laravel to my mac book. My project is in the xampp htdocs folder and I want to use it witch xampp. But when the xampp apache server instance is running, nothing is happened to my laravel project until I run php artisan serve in the cmd.

How can I combine larael with xampp?
And what exactly does php artisan serve do? Start another apache server instance?

答:
The artisan command is just a command line utility for laravel.  The serve command just starts up the PHP server.

to run it without artisan you can Configure a server virtual-host (Apache or Nginx) which have the public directory of your project as root directory. Since you are using a MAC I can't exactly instruct you to how to do that.

NOTE

this will help to create the virtual host. but i haven't tried that

ContentLicense: CC BY-SA 4.0

Title: Laravel with xampp


问:
Copy img styled with CSS into canvas to get final dataUrl
Let's say I have cat.png at 800x600 pixel.

Then I put it into img and apply CSS object-fit like below:

```<code>#cat {
  width: 100px;
  height: 100px;
  object-fit: cover;
}

<img src="cat.png" id="cat">
</code>```

Now I have on screen a 100x100 image.

How to transfer this final result into canvas, so that I could get the dataUrl and save as cat_thumb.png at 100x100 pixel?

These codes simply ignore the CSS applied to the img:

```<code>var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById("cat");
ctx.drawImage(img,0,0,100,100);
console.log(c.toDataURL());
</code>```

答:
Looks like there are 2 fixes needed:

Use the img height and width in drawImage to use the height and width of the CSS being applied to the image.

Use img.onload to wait for the image to be loaded before creating the canvas, adding the image and using toDataURL().

Because you're using object-fit: cover to crop the image we'll also need to some some calculation on how to crop the image before its placed into the canvas.

One side effect of this method, the downsampling when transferring to the canvas creates a noticeable loss in quality. This is less of an issue when the resizing of the image is less, and becomes more noticeable when downsizing a large image to a much smaller size.

I have added a very simple downsampling loop to reduce the effects of this. In short, it creates an offscreen canvas, and scales it down by 50% until the image is close to the desired size.

More info and possible solutions for this issue can be found in many other questions/answers.

var imgEl = document.getElementById("cat");
var img = new Image();
img.crossOrigin = "anonymous";
img.src = imgEl.src;

img.onload = function() {
  // Create an offscreen canvas for downsampling the image
  var oc = document.createElement("canvas");
  var occtx = oc.getContext("2d");

  oc.width = img.width * 0.5;
  oc.height = img.height * 0.5;
  occtx.drawImage(img, 0, 0, oc.width, oc.height);

  var c = document.getElementById("myCanvas");
  var ctx = c.getContext("2d");
  var imgRatio = imgEl.width / imgEl.height;
  var sx, sy, sWidth, sHeight;

  if (imgRatio > 1) {
    sx = 0;
    sy = (oc.height / imgRatio) / 2;
    sWidth = oc.width;
    sHeight = oc.height / imgRatio;
  } else if (imgRatio < 1) {
    sx = (oc.width * imgRatio) / 2;
    sy = 0;
    sWidth = oc.width * imgRatio;
    sHeight = oc.height;
  } else {
    sx = 0;
    sy = 0;
    sWidth = oc.width;
    sHeight = oc.height;
  }

  c.width = imgEl.width;
  c.height = imgEl.height;
  ctx.drawImage(oc, sx, sy, sWidth, sHeight, 0, 0, imgEl.width, imgEl.height);
  console.log(c.toDataURL());
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.img-container {
  position: relative;
  margin-top: 0;
}

#cat {
  width: 300px;
  height: 150px;
  object-fit: cover;
}</code>```

<canvas id="myCanvas"></canvas>```

ContentLicense: CC BY-SA 3.0

Body:
Let's say I have cat.png at 800x600 pixel.

Then I put it into img and apply CSS object-fit like below:

#cat {
  width: 100px;
  height: 100px;
  object-fit: cover;
}

Now I have on screen a 100x100 image.

How to transfer this final result into canvas, so that I could get the dataUrl and save as cat_thumb.png at 100x100 pixel?

These codes simply ignore the CSS applied to the img:

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById("cat");
ctx.drawImage(img,0,0,100,100);
console.log(c.toDataURL());

Body:
Looks like there are 2 fixes needed:

Use the img height and width in drawImage to use the height and width of the CSS being applied to the image.

Use img.onload to wait for the image to be loaded before creating the canvas, adding the image and using toDataURL().

Because you're using object-fit: cover to crop the image we'll also need to some some calculation on how to crop the image before its placed into the canvas.

One side effect of this method, the downsampling when transferring to the canvas creates a noticeable loss in quality. This is less of an issue when the resizing of the image is less, and becomes more noticeable when downsizing a large image to a much smaller size.

I have added a very simple downsampling loop to reduce the effects of this. In short, it creates an offscreen canvas, and scales it down by 50% until the image is close to the desired size.

More info and possible solutions for this issue can be found in many other questions/answers.

var imgEl = document.getElementById("cat");
var img = new Image();
img.crossOrigin = "anonymous";
img.src = imgEl.src;

img.onload = function() {
  // Create an offscreen canvas for downsampling the image
  var oc = document.createElement("canvas");
  var occtx = oc.getContext("2d");

  oc.width = img.width * 0.5;
  oc.height = img.height * 0.5;
  occtx.drawImage(img, 0, 0, oc.width, oc.height);

  var c = document.getElementById("myCanvas");
  var ctx = c.getContext("2d");
  var imgRatio = imgEl.width / imgEl.height;
  var sx, sy, sWidth, sHeight;

  if (imgRatio > 1) {
    sx = 0;
    sy = (oc.height / imgRatio) / 2;
    sWidth = oc.width;
    sHeight = oc.height / imgRatio;
  } else if (imgRatio < 1) {
    sx = (oc.width * imgRatio) / 2;
    sy = 0;
    sWidth = oc.width * imgRatio;
    sHeight = oc.height;
  } else {
    sx = 0;
    sy = 0;
    sWidth = oc.width;
    sHeight = oc.height;
  }

  c.width = imgEl.width;
  c.height = imgEl.height;
  ctx.drawImage(oc, sx, sy, sWidth, sHeight, 0, 0, imgEl.width, imgEl.height);
  console.log(c.toDataURL());
}

.img-container {
  position: relative;
  margin-top: 0;
}

#cat {
  width: 300px;
  height: 150px;
  object-fit: cover;
}

<div class="img-container"><img src="https://i.imgur.com/nZmjnkH.jpg" id="cat" crossOrigin="anonymous"></div>

<canvas id="myCanvas"></canvas>


问:
Passing props to a dynamically created component
I dynamically create a component and like to pass some props into it as the following

```<code>import ResouceUsageGadget from './ResouceUsage/ResouceUsageGadget'
  constructor() {
    ...
    this.gadgetStateMap = {
            "ResouceUsageGadget":{"name":"ResouceUsageGadget", "type":ResouceUsageGadget, "state":"normal"}
    }
  }
...
render(){
  let aa = this.gadgetStateMap["ResouceUsageGadget"].type
  return (
     <aa gadgets={this.props.gadgets}/>
  )
}

const DashboardContainer = connect(
          store => {
                return {
                    gadgets: store.DashboardReducer.gadgets
                };
              }
            )(_DashboardContainer);
export default DashboardContainer
</code>```

I got a warning:

Warning: Unknown prop gadgets on  tag. Remove this prop from the element.
    in aa (created by _DashboardContainer)
    in div (created by _DashboardContainer)
    in div (created by _DashboardContainer)
    in _DashboardContainer (created by Connect(_DashboardContainer))
    in Connect(_DashboardContainer) (created by _MainContainer)

And the component never shown up...

Anything wrong?

答:
From the React docs:

Caveat:

Always start component names with a capital letter.

For example,
 represents a DOM tag, but <Welcome /> represents a component and requires Welcome to be in scope.

Try changing

```<code>render(){
  let aa = this.gadgetStateMap["ResouceUsageGadget"].type
  return (
     <aa gadgets={this.props.gadgets}/>
  )
}
</code>```

to be

```<code>render(){
  let Aa = this.gadgetStateMap["ResouceUsageGadget"].type
  return (
     <Aa gadgets={this.props.gadgets}/>
  )
}
</code>```

and see if that helps.

Body:
I dynamically create a component and like to pass some props into it as the following

import ResouceUsageGadget from './ResouceUsage/ResouceUsageGadget'
  constructor() {
    ...
    this.gadgetStateMap = {
            "ResouceUsageGadget":{"name":"ResouceUsageGadget", "type":ResouceUsageGadget, "state":"normal"}
    }
  }
...
render(){
  let aa = this.gadgetStateMap["ResouceUsageGadget"].type
  return (
     <aa gadgets={this.props.gadgets}/>
  )
}

const DashboardContainer = connect(
          store => {
                return {
                    gadgets: store.DashboardReducer.gadgets
                };
              }
            )(_DashboardContainer);
export default DashboardContainer

I got a warning:

Warning: Unknown prop gadgets on  tag. Remove this prop from the element.
    in aa (created by _DashboardContainer)
    in div (created by _DashboardContainer)
    in div (created by _DashboardContainer)
    in _DashboardContainer (created by Connect(_DashboardContainer))
    in Connect(_DashboardContainer) (created by _MainContainer)

And the component never shown up...

Anything wrong?

Body:
From the React docs:

Caveat:

Always start component names with a capital letter.

For example, <div /> represents a DOM tag, but <Welcome /> represents a component and requires Welcome to be in scope.

Try changing

render(){
  let aa = this.gadgetStateMap["ResouceUsageGadget"].type
  return (
     <aa gadgets={this.props.gadgets}/>
  )
}

to be

render(){
  let Aa = this.gadgetStateMap["ResouceUsageGadget"].type
  return (
     <Aa gadgets={this.props.gadgets}/>
  )
}

and see if that helps.


问:
jQuery UI resizable containment not responding to newly created element
I am using the jQuery UI resizable and draggable functions. First I create a new element, append it to the body and set the containments

```<code>function setDraggable(){
    $div = $(document.createElement('div')).css({
        //blah blah (tested and working perfectly)
    });
    $('body').append($div);
    $('div#dragBox'). draggable({
            containment : $div
    }). resizable({
            containment : $div
    })
}
</code>```

It works for the draggable but not for the resizable

答:
Here you go with the solution https://jsfiddle.net/wx4r7kz6/

setDraggable = function(){
    $div = $(document.createElement('div')).css({
        //blah blah (tested and working perfectly)
        'width': '100px',
        'height': '100px',
        'display': 'inline-block',
      'border': '1px solid'
    });
    $div.attr("id", "dragBox");
    $('body').append($div);
    $('div#dragBox').draggable().resizable();
}

setDraggable();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script></code>```

Body:
I am using the jQuery UI resizable and draggable functions. First I create a new element, append it to the body and set the containments

function setDraggable(){
    $div = $(document.createElement('div')).css({
        //blah blah (tested and working perfectly)
    });
    $('body').append($div);
    $('div#dragBox'). draggable({
            containment : $div
    }). resizable({
            containment : $div
    })
}

It works for the draggable but not for the resizable

Body:
Here you go with the solution https://jsfiddle.net/wx4r7kz6/

setDraggable = function(){
    $div = $(document.createElement('div')).css({
        //blah blah (tested and working perfectly)
        'width': '100px',
        'height': '100px',
        'display': 'inline-block',
      'border': '1px solid'
    });
    $div.attr("id", "dragBox");
    $('body').append($div);
    $('div#dragBox').draggable().resizable();
}

setDraggable();

<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>


问:
How do I merge two sorted object lists based on common attribute in Java
I have two object lists both with a common attribute called timestamp and both are sorted by timestamp.

I want to broadcast these objects one by one based on the timestamp, example if first object of 1st list has timestamp < first object of 2nd list, broadcast first object of the 1st list and then compare second object of the 1st list with the first object of the 2nd list.

I am a newbie in java. This is what I have come up with:

```<code> //Merge the 2 object lists based on timestamp
        ListIterator<x> xIterator = list1.listIterator();
        ListIterator<y> yIterator = list2.listIterator();
        while (xIterator.hasNext() && yIterator.hasNext()) {
            if (xIterator.next().timestamp <= yIterator.next().timestamp) {
                Bundle extra = new Bundle();
                extra.putParcelable(LocalBroadcastConstants.ACTION, xIterator.previous());
                MyBroadcastManager.getInstance(getTargetContext()).sendBroadcast(
                        new Intent(LocalBroadcastConstants.ACTION_SEND).putExtras(extra)
                );
                yIterator.previous();
            } else {
                Bundle extra = new Bundle();
                extra.putParcelable(LocalBroadcastConstants.ACTION,
                        yIterator.previous());
                MyBroadcastManager.getInstance(getTargetContext()).sendBroadcast(
                        new Intent(LocalBroadcastConstants.ACTION_SEND).putExtras(extra)
                );
                xIterator.previous();
            }
</code>```

I know my logic is incorrect because for the first item in the Iterators, xIterator.previous and yIterator.previous will point to nothing. I can't seem to find the correct solution for this problem statement. Please help.

答:
Use indexes instead of iterator. You can also use methods to prevent code redundancy

```<code>int xIndex = 0;
int yIndex = 0;

while (xIndex < list1.size() && yIndex < list2.size()) {
    if (list1[xIndex].timestamp <= list2[yIndex].timestamp) {
        broadcast(list1, xIndex);
        ++xIndex;
    }
    else {
        broadcast(list2, yIndex);
        ++yIndex;
    }
}

dealWithLeftovers(list1, xIndex);
dealWithLeftovers(list2, yIndex);
</code>```

broadcast:

```<code>private void broadcast(List<> list, int index) {
    Bundle extra = new Bundle();
    extra.putParcelable(LocalBroadcastConstants.ACTION, list[index]);
    MyBroadcastManager.getInstance(getTargetContext()).sendBroadcast(
        new Intent(LocalBroadcastConstants.ACTION_SEND).putExtras(extra)
    );
}
</code>```

dealWithLeftovers:

```<code>private void dealWithLeftovers(List<> list, int index) {
    for (int i = index; i < list.size() ; ++i) {
        broadcast(list, i);
    }
}
</code>```

Body:
I have two object lists both with a common attribute called timestamp and both are sorted by timestamp.

I want to broadcast these objects one by one based on the timestamp, example if first object of 1st list has timestamp < first object of 2nd list, broadcast first object of the 1st list and then compare second object of the 1st list with the first object of the 2nd list.

I am a newbie in java. This is what I have come up with:

 //Merge the 2 object lists based on timestamp
        ListIterator<x> xIterator = list1.listIterator();
        ListIterator<y> yIterator = list2.listIterator();
        while (xIterator.hasNext() && yIterator.hasNext()) {
            if (xIterator.next().timestamp <= yIterator.next().timestamp) {
                Bundle extra = new Bundle();
                extra.putParcelable(LocalBroadcastConstants.ACTION, xIterator.previous());
                MyBroadcastManager.getInstance(getTargetContext()).sendBroadcast(
                        new Intent(LocalBroadcastConstants.ACTION_SEND).putExtras(extra)
                );
                yIterator.previous();
            } else {
                Bundle extra = new Bundle();
                extra.putParcelable(LocalBroadcastConstants.ACTION,
                        yIterator.previous());
                MyBroadcastManager.getInstance(getTargetContext()).sendBroadcast(
                        new Intent(LocalBroadcastConstants.ACTION_SEND).putExtras(extra)
                );
                xIterator.previous();
            }

I know my logic is incorrect because for the first item in the Iterators, xIterator.previous and yIterator.previous will point to nothing. I can't seem to find the correct solution for this problem statement. Please help.

Body:
Use indexes instead of iterator. You can also use methods to prevent code redundancy

int xIndex = 0;
int yIndex = 0;

while (xIndex < list1.size() && yIndex < list2.size()) {
    if (list1[xIndex].timestamp <= list2[yIndex].timestamp) {
        broadcast(list1, xIndex);
        ++xIndex;
    }
    else {
        broadcast(list2, yIndex);
        ++yIndex;
    }
}

dealWithLeftovers(list1, xIndex);
dealWithLeftovers(list2, yIndex);

broadcast:

private void broadcast(List<> list, int index) {
    Bundle extra = new Bundle();
    extra.putParcelable(LocalBroadcastConstants.ACTION, list[index]);
    MyBroadcastManager.getInstance(getTargetContext()).sendBroadcast(
        new Intent(LocalBroadcastConstants.ACTION_SEND).putExtras(extra)
    );
}

dealWithLeftovers:

private void dealWithLeftovers(List<> list, int index) {
    for (int i = index; i < list.size() ; ++i) {
        broadcast(list, i);
    }
}


问:
extract data from csv file based on two lists with priority for items in the first list
I have csv files and I want to extract part of data form each one into another file based on keywords from two different lists. That is, the the program should match every line in the original file with the keywords in the first list and write those lines until a match is found. once match is found, it should break the execution. In case the program reached the last line in the csv file without finding any match, then it should start matching with the second list and repeat the same.
I want to give the priority to the first list and if there is no match then start the process using the second list.

```<code>The first list fruit=['orange', 'apple', 'grape', 'banana','phone', 'TV', 'w']
The second list veg=['tomato','potato','onion']
</code>```

following is a sample of the contents of one of the files called srcfile1

```<code> paper
 wood
 plastic
 fire
 water
 house
 onion
 ginger
 mints
 banana
 TV
 watermelon
 phone
 pepper
</code>```

I have written following python code:

```<code>import os
from tqdm import *
import time
import pandas as pd
import numpy as nb
line = fr.readline()
fr = open('d:\\srcfile1')
fw = open('destfile1', 'w')
found=False
while line:
      line = fr.readline()
      if any (item.lower() in line.lower() for item in fruit):
          found=True
          fw.close()
          break
      elif any (item.lower() in line.lower() for item in veg) and found==False:
            fw.close()
            break
      fw.writelines(line)

fr.close()
fw.close()
</code>```

The desired outcome from the code should be:

```<code> paper
 wood
 plastic
 fire
 water
 house
 onion
 ginger
 mints
</code>```

But When I run this code, it just match any element from both lists and does not give the priority to fruit list. It just give the following output:

```<code> paper
 wood
 plastic
 fire
 water
 house
</code>```

I would be grateful if anybody could help me in this.

答:
I suggest to use set and intersection method to find your result</p>

```<code>fruits = {fruit.lower() for fruit in fruits}
with open('d:\\srcfile1') as f:
       data = {key.lower() for key  in f.read().split('\n')}
data.intersection(fruits)
</code>```

Body:
I have csv files and I want to extract part of data form each one into another file based on keywords from two different lists. That is, the the program should match every line in the original file with the keywords in the first list and write those lines until a match is found. once match is found, it should break the execution. In case the program reached the last line in the csv file without finding any match, then it should start matching with the second list and repeat the same.
I want to give the priority to the first list and if there is no match then start the process using the second list.

The first list fruit=['orange', 'apple', 'grape', 'banana','phone', 'TV', 'w']
The second list veg=['tomato','potato','onion']

following is a sample of the contents of one of the files called srcfile1

 paper
 wood
 plastic
 fire
 water
 house
 onion
 ginger
 mints
 banana
 TV
 watermelon
 phone
 pepper

I have written following python code:

import os
from tqdm import *
import time
import pandas as pd
import numpy as nb
line = fr.readline()
fr = open('d:\\srcfile1')
fw = open('destfile1', 'w')
found=False
while line:
      line = fr.readline()
      if any (item.lower() in line.lower() for item in fruit):
          found=True
          fw.close()
          break
      elif any (item.lower() in line.lower() for item in veg) and found==False:
            fw.close()
            break
      fw.writelines(line)

fr.close()
fw.close()

The desired outcome from the code should be:

 paper
 wood
 plastic
 fire
 water
 house
 onion
 ginger
 mints

But When I run this code, it just match any element from both lists and does not give the priority to fruit list. It just give the following output:

 paper
 wood
 plastic
 fire
 water
 house

I would be grateful if anybody could help me in this.

Body:
I suggest to use set and intersection method to find your result

fruits = {fruit.lower() for fruit in fruits}
with open('d:\\srcfile1') as f:
       data = {key.lower() for key  in f.read().split('\n')}
data.intersection(fruits)


问:
Topdown camera focus with angle
I'm making a topdown game with the camera at 40 degree angle. What I want to do is when i click an gameobject, It will move the camera and position the object at the left side from the center of  the camera view regardless of its rotation. So that I can place a menu at the right side. How do I get the offset of the angled camera so that the object is in the middle left side of the camera view?

Right now i use lerp but it overshoots the target because of the cameras angle. Sorry for the noob question I'm new to unity3d.

```<code>transform.position = Vector3.Lerp(transform.position, new Vector3(target.transform.position.x, transform.position.y, target.transform.position.z), 0.1f);
</code>```

答:
First of all you should start by finding point that your camera will move/lerp to.

In your case in can be simplified to 2D-Space:

It shouldnt be tough to find that one.

Use transform.forward of camera to get vector (Vector3 cameraDir) of direction your camera is looking at

Rotate by horizontal fov / 4 around y axis:

Vector3 cameraDirRotated = Quaternion.AngleAxis(hFov/4f, Vector3.up) * cameraDir;

-cameraDirRotated will be vector from Cube To point P you're looking for, u can also scale it:
Vector3 PtoMoveTo = cube.transform.position - cameraDirRotated.normalized * 5f;

Full:

```<code>Vector3 FindCameraTarget(Transform targetObj, float hFov)
{
    Vector3 cameraDir = transform.forward;
    Vector3 cameraDirRotated = Quaternion.AngleAxis(hFov / 4f, Vector3.up) * cameraDir;
    Vector3 target = targetObj.transform.position - cameraDirRotated.normalized * 5f;
    return target;
}
</code>```

Then:

```<code>transform.position = Vector3.Lerp(transform.position, FindCameraTarget(target, 90f) , 2f * Time.deltaTime);
</code>```

For performance u can save that target vector once if Cube is not moving. Search web how to precisely count horizontal fov. Multiply speed by Time.timeDelta if u lerp in Update().

Title: Topdown camera focus with angle

Body:
I'm making a topdown game with the camera at 40 degree angle. What I want to do is when i click an gameobject, It will move the camera and position the object at the left side from the center of  the camera view regardless of its rotation. So that I can place a menu at the right side. How do I get the offset of the angled camera so that the object is in the middle left side of the camera view?

Right now i use lerp but it overshoots the target because of the cameras angle. Sorry for the noob question I'm new to unity3d.

transform.position = Vector3.Lerp(transform.position, new Vector3(target.transform.position.x, transform.position.y, target.transform.position.z), 0.1f);

Body:
First of all you should start by finding point that your camera will move/lerp to.

In your case in can be simplified to 2D-Space:

It shouldnt be tough to find that one.

Use transform.forward of camera to get vector (Vector3 cameraDir) of direction your camera is looking at

Rotate by horizontal fov / 4 around y axis:

Vector3 cameraDirRotated = Quaternion.AngleAxis(hFov/4f, Vector3.up) * cameraDir;

-cameraDirRotated will be vector from Cube To point P you're looking for, u can also scale it:
Vector3 PtoMoveTo = cube.transform.position - cameraDirRotated.normalized * 5f;

Full:

Vector3 FindCameraTarget(Transform targetObj, float hFov)
{
    Vector3 cameraDir = transform.forward;
    Vector3 cameraDirRotated = Quaternion.AngleAxis(hFov / 4f, Vector3.up) * cameraDir;
    Vector3 target = targetObj.transform.position - cameraDirRotated.normalized * 5f;
    return target;
}

Then:

transform.position = Vector3.Lerp(transform.position, FindCameraTarget(target, 90f) , 2f * Time.deltaTime);

For performance u can save that target vector once if Cube is not moving. Search web how to precisely count horizontal fov. Multiply speed by Time.timeDelta if u lerp in Update().


问:
Karma, Rails preprocessing coffeescript erb files from gem dependencies
I have a karma test runner that dynamically writes rail's javascript files to a karma.conf.js file.

Now, everything works (the tests run) if I remove actioncable's javascript files manually from the files list. However, when actioncable's files are added, the preprocessor chokes.

24 08 2016 16:56:22.095:ERROR [preprocessor.coffee]: unexpected <
    at /home/vagrant/.rvm/gems/ruby-2.2.2/bundler/gems/actioncable-6be2604aa719/lib/assets/javascripts/cable.coffee.erb:4
  24 08 2016 16:56:22.296:INFO [karma]: Karma v0.13.14 server started at http://localhost:9876/
  24 08 2016 16:56:22.309:INFO [launcher]: Starting browser PhantomJS
  24 08 2016 16:56:23.106:INFO [PhantomJS 1.9.8 (Linux 0.0.0)]: Connected on socket RyL0QOEWkq8inzwAAAAA with id 22283032
  PhantomJS 1.9.8 (Linux 0.0.0) ERROR
    You need to include some adapter that implements karma.start method!

Oke doke. So looking at the actioncable erb file:

```<code>#= require_self
#= require cable/consumer

@Cable =
  INTERNAL: <%= ActionCable::INTERNAL.to_json %>

  createConsumer: (url) ->
    new Cable.Consumer url
</code>```

So the preprocessor is definitely choking on the erb tags in this specific file. I have erb tags in other files, that get processed fine, but those are wrapped in quotes. Is this a preprocessor bug, or is there a quick fix for this that I'm not thinking of?

答:
I ran into this too. My understanding is that you need to compile the erb files down to js files, which will remove the rails syntax. What I did was add to my development.rb file:

config.assets.prefix = "/dev-assets"

Which creates the finger printed application.js file with all of your compiled scripts, same as production, and places it into public/dev-assets

In my karma.conf I have:

```<code>files: [
  './public/dev-assets/*.js',
   ...
]
</code>```

It's not exactly ideal, since you're working with one big file when writing/debugging tests, but it works with the asset pipeline.

Before I came to that solution, I did add only my specific ng folders to the files array, skipping the cables file (you could add it to the excluded files list), which resolved the issue too, but I went with this route because I couldn't get it to play nice with angular-rails-templates

Body:
I have a karma test runner that dynamically writes rail's javascript files to a karma.conf.js file.

Now, everything works (the tests run) if I remove actioncable's javascript files manually from the files list. However, when actioncable's files are added, the preprocessor chokes.

24 08 2016 16:56:22.095:ERROR [preprocessor.coffee]: unexpected <
    at /home/vagrant/.rvm/gems/ruby-2.2.2/bundler/gems/actioncable-6be2604aa719/lib/assets/javascripts/cable.coffee.erb:4
  24 08 2016 16:56:22.296:INFO [karma]: Karma v0.13.14 server started at http://localhost:9876/
  24 08 2016 16:56:22.309:INFO [launcher]: Starting browser PhantomJS
  24 08 2016 16:56:23.106:INFO [PhantomJS 1.9.8 (Linux 0.0.0)]: Connected on socket RyL0QOEWkq8inzwAAAAA with id 22283032
  PhantomJS 1.9.8 (Linux 0.0.0) ERROR
    You need to include some adapter that implements karma.start method!

Oke doke. So looking at the actioncable erb file:

#= require_self
#= require cable/consumer

@Cable =
  INTERNAL: <%= ActionCable::INTERNAL.to_json %>

  createConsumer: (url) ->
    new Cable.Consumer url

So the preprocessor is definitely choking on the erb tags in this specific file. I have erb tags in other files, that get processed fine, but those are wrapped in quotes. Is this a preprocessor bug, or is there a quick fix for this that I'm not thinking of?

Body:
I ran into this too. My understanding is that you need to compile the erb files down to js files, which will remove the rails syntax. What I did was add to my development.rb file:

config.assets.prefix = "/dev-assets"

Which creates the finger printed application.js file with all of your compiled scripts, same as production, and places it into public/dev-assets

In my karma.conf I have:

files: [
  './public/dev-assets/*.js',
   ...
]

It's not exactly ideal, since you're working with one big file when writing/debugging tests, but it works with the asset pipeline.

Before I came to that solution, I did add only my specific ng folders to the files array, skipping the cables file (you could add it to the excluded files list), which resolved the issue too, but I went with this route because I couldn't get it to play nice with angular-rails-templates


问:
Angular 2 - NgForm null when submit a form
Hi everyone i am doing a "dinamic" form with Angular and i am having some problems to get the values that input in form, my code is:

HTML

```<code><form  #myForm="ngForm" (ngSubmit)="onSubmit(myForm)" *ngFor="let con of controls" novalidate>
  <div class="form-group" *ngIf = "con.type != 'submit'">
    <label for="{{con.id}}">{{con.label}}</label>
    <input [(ngModel)]="con.name" type="{{con.type}}" class="{{con.class}}" name="{{con.id}}">
 </div>
 <input  *ngIf = "con.type == 'submit'"  type="submit" class="{{con.class}}" value={{con.label}}>
</form>
</code>```

Component:

```<code>import { Component ,Input} from '@angular/core';
import { NgForm } from '@angular/forms';

@Component({
  selector: 'form-tag',
  templateUrl: './form.html',
})

export class FormComponent {
    @Input() controls: any[];

    onSubmit(sub: NgForm)
    {
        console.log(sub.email);
    }
}
</code>```

the problem is that when i submit the form console.log(sub.email); return an empty object

答:
I'm not really really sure what you're trying to do but it seems like you're looping over controls with the <form> tag instead of just with the div.form-group and the <input /> itself.

Maybe wrap those in an <ng-template /> and loop through it and not the <form> tag?

So something like this:

<form  #myForm="ngForm" (ngSubmit)="onSubmit(myForm)" novalidate>
    <ng-template *ngFor="let con of controls">

        {{con.label}}
        <input [(ngModel)]="con.name" type="{{con.type}}" class="{{con.class}}" name="{{con.id}}" />

     <input *ngIf="con.type == 'submit'" type="submit" class="{{con.class}}" [value]="con.label" />
</form>
```

Body:
Hi everyone i am doing a "dinamic" form with Angular and i am having some problems to get the values that input in form, my code is:

HTML

<form  #myForm="ngForm" (ngSubmit)="onSubmit(myForm)" *ngFor="let con of controls" novalidate>

    {{con.label}}
    <input [(ngModel)]="con.name" type="{{con.type}}" class="{{con.class}}" name="{{con.id}}">

 <input  *ngIf = "con.type == 'submit'"  type="submit" class="{{con.class}}" value={{con.label}}>
</form>

Component:

import { Component ,Input} from '@angular/core';
import { NgForm } from '@angular/forms';

@Component({
  selector: 'form-tag',
  templateUrl: './form.html',
})

export class FormComponent {
    @Input() controls: any[];

    onSubmit(sub: NgForm)
    {
        console.log(sub.email);
    }
}

the problem is that when i submit the form console.log(sub.email); return an empty object

Body:
I'm not really really sure what you're trying to do but it seems like you're looping over controls with the <form> tag instead of just with the div.form-group and the <input /> itself.

Maybe wrap those in an <ng-template /> and loop through it and not the <form> tag?

So something like this:

<form  #myForm="ngForm" (ngSubmit)="onSubmit(myForm)" novalidate>
    <ng-template *ngFor="let con of controls">
      <div class="form-group" *ngIf="con.type != 'submit'">
        <label for="{{con.id}}">{{con.label}}</label>
        <input [(ngModel)]="con.name" type="{{con.type}}" class="{{con.class}}" name="{{con.id}}" />
     </div>
     <input *ngIf="con.type == 'submit'" type="submit" class="{{con.class}}" [value]="con.label" />
</form>


Title: How to avoid sorting pivot table by index

Body:
I have a dataframe:

t1=r.data[(r.data['test_num']==2) & (r.data['el_num'] < 4)]

     test_num  el_num  file_num     dose  is_anneal     value   fail
99          2       1         0    100.0      False -0.000056  False
100         2       1         1   5052.0      False -0.000056  False
101         2       1         2  10107.0      False -0.000056  False
102         2       1         3  16561.0      False -0.000056  False
103         2       1         4  22536.0      False -0.000056  False
104         2       1         5  25020.0      False -0.000056  False
105         2       1         6  35123.0      False -0.000056  False
106         2       1         7     24.0       True -0.000056  False
107         2       1         8    168.0       True -0.000055  False
108         2       2         0    100.0      False -0.000056  False
109         2       2         1   5052.0      False -0.000056  False
110         2       2         2  10107.0      False -0.000056  False
111         2       2         3  16561.0      False -0.000056  False
112         2       2         4  22536.0      False -0.000056  False
113         2       2         5  25020.0      False -0.000056  False
114         2       2         6  35123.0      False -0.000056  False
115         2       2         7     24.0       True -0.000056  False
116         2       2         8    168.0       True -0.000055  False
117         2       3         0    100.0      False -0.000060  False
118         2       3         1   5052.0      False -0.000061  False
119         2       3         2  10107.0      False -0.000061  False
120         2       3         3  16561.0      False -0.000061  False
121         2       3         4  22536.0      False -0.000061  False
122         2       3         5  25020.0      False -0.000061  False
123         2       3         6  35123.0      False -0.000061  False
124         2       3         7     24.0       True -0.000061  False
125         2       3         8    168.0       True -0.000061  False

When I want to create pivot table, I get this:

print(t1.pivot(index='dose',columns='el_num',values='value'))

el_num          1         2         3
dose
24.0    -0.000056 -0.000056 -0.000061
100.0   -0.000056 -0.000056 -0.000060
168.0   -0.000055 -0.000055 -0.000061
5052.0  -0.000056 -0.000056 -0.000061
10107.0 -0.000056 -0.000056 -0.000061
16561.0 -0.000056 -0.000056 -0.000061
22536.0 -0.000056 -0.000056 -0.000061
25020.0 -0.000056 -0.000056 -0.000061
35123.0 -0.000056 -0.000056 -0.000061

But I want the dose column to have an order like in the main table:

100.0
5052.0
10107.0
16561.0
22536.0
25020.0
35123.0
24.0
168.0

How to avoid sorting in pivot table?

Body:
You can use solution what is similar pivot_table, but if duplicates it aggregate values:

df = t1.groupby(['dose','el_num'], sort=False)['value'].mean().unstack()
print (df)
el_num          1         2         3
dose
100.0   -0.000056 -0.000056 -0.000060
5052.0  -0.000056 -0.000056 -0.000061
10107.0 -0.000056 -0.000056 -0.000061
16561.0 -0.000056 -0.000056 -0.000061
22536.0 -0.000056 -0.000056 -0.000061
25020.0 -0.000056 -0.000056 -0.000061
35123.0 -0.000056 -0.000056 -0.000061
24.0    -0.000056 -0.000056 -0.000061
168.0   -0.000055 -0.000055 -0.000061

Another solution is use pivot and then reindex by custom order:

a = t1.loc[t1['el_num'] == 1,'dose']

df = t1.pivot(index='dose',columns='el_num',values='value').reindex(a)
print (df)
el_num          1         2         3
dose
100.0   -0.000056 -0.000056 -0.000060
5052.0  -0.000056 -0.000056 -0.000061
10107.0 -0.000056 -0.000056 -0.000061
16561.0 -0.000056 -0.000056 -0.000061
22536.0 -0.000056 -0.000056 -0.000061
25020.0 -0.000056 -0.000056 -0.000061
35123.0 -0.000056 -0.000056 -0.000061
24.0    -0.000056 -0.000056 -0.000061
168.0   -0.000055 -0.000055 -0.000061


问:
Having two different GIT repo's in one directory for the same project
I wanted to know if it is possible to have 2 different GIT repositories in one root folder for the same project, and if I can add/commit/push to both of them without anything getting messed up.

Example of what I want to achieve:

I have a Django project and I have it in 2 different repositories. One being on https://github.com that I use for automatic deployment on Heroku, and the second repository on https://gitlab.com where I have all my legit commits/Messages/Tickets/Issues/CI/etc.

Is it possible to somehow get both repos to be in 1 directory where my Django project is and then for me to just do

git add .

git commit -m "message"

git push origin "whatever"

and get my commits pushed to both repos?

At the moment I have the project in 2 different directories where the gitlab one is my main project and then I copy paste the files into the github one and push there so I can deploy the changes on Heroku.

P.S I would prefer to have my automatic deploys from the github repo without setting up any deployments from gitlab.

Thanks, please comment if you are downvoting this post, so I can improve quality. This is my 1st question!

Thank you!

EDIT 09-07-2017:

I have found a way to easily deploy my Django Project to Heroku without the need of a github repo. For any future people that might come across this question, here is how I achieved deploying my Django Project to Heroku via a https://gitlab.com repo in the most hacky/fast way without much of a setup:

Locate your Heroku-API key Heroku, if the link no longer works just go to your Heroku Account settings and in there you will find your Heroku API key

After you have setup your Procfile, wsgi.py, etc (all the Deployment setup), push all the changes to your master branch on gitlab.

Finally you want to do the following commands in order to deploy to Heroku:

git remote add heroku https://"API-key"@git.heroku.com/"app_name".git

(without the quotes example: https://xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx@git.heroku.com/django_app.git)

then you fire up this:

git push -f heroku master

This might ask you to authenticate, so just use your heroku credentials.

Hope this was of help to you!

答:
AFIR Gitlab.com has option to push mirror repository to other git servers. Go to Project Settings -> Repository -> Push to a remote repository

Set up the remote repository that you want to update with the content of the current repository every time someone pushes to it. Read more
  Remote mirror repository

Automatically update the remote mirror's branches, tags, and commits from this repository every time someone pushes to it.

With that you can have only one remote origin and Gitlab will push all your changes to Github. I wish that feature could be added to self-hosted Gitlab-CE.


问:
where is default installation directory for mongodb
I installed mongodb by following the instructions from its site. To open the shell I must go to the installation directory of mongodb, and then type

```<code>./bin/mongo
</code>```

I don't know the default directory. where might it be?

答: Use the which mongo command to look for the location of the mongo executable.

Body:
I installed mongodb by following the instructions from its site. To open the shell I must go to the installation directory of mongodb, and then type

./bin/mongo

I don't know the default directory. where might it be?


问:
Animation with canvas
I need to create animation with circle. When we see a block with a circle, then the animation starts to fill the boundary of the circle and stops in a certain position. Interesting how to do this animation on native js.
enter image description here</p>

答:
The best option is to call window.requestAnimationFrame, which calls your render function. Within your render function you have to measure the elapsed time since your last animation frame (and calculate your new angle), redraw the animation and call requestAnimationFrame.

I quickly made a sample at CodePen:

```<code>function draw(angle) { ... }

var duration = 3000; // duration of the animation in ms
var max_angle = 3 / 2 * Math.PI; // maximum animation angle

var angle = 0; // current animation angle
var lastRendered = performance.now();

function render(timestamp) {
  angle += (timestamp - lastRendered) * 2 * Math.PI / duration; // calculate new angle
  if (angle > max_angle) angle = max_angle;
  lastRendered = timestamp;
  draw(angle);
  if (angle < max_angle) requestAnimationFrame(render);
}

requestAnimationFrame(render);
</code>```

Title: Animation with canvas

Body:
The best option is to call window.requestAnimationFrame, which calls your render function. Within your render function you have to measure the elapsed time since your last animation frame (and calculate your new angle), redraw the animation and call requestAnimationFrame.

I quickly made a sample at CodePen:

function draw(angle) { ... }

var duration = 3000; // duration of the animation in ms
var max_angle = 3 / 2 * Math.PI; // maximum animation angle

var angle = 0; // current animation angle
var lastRendered = performance.now();

function render(timestamp) {
  angle += (timestamp - lastRendered) * 2 * Math.PI / duration; // calculate new angle
  if (angle > max_angle) angle = max_angle;
  lastRendered = timestamp;
  draw(angle);
  if (angle < max_angle) requestAnimationFrame(render);
}

requestAnimationFrame(render);


问:
fetching hierarchical data
i have table like:

```<code>emp id | post  | manager id
----------------------------
1       | l1   | 2
2       | l2   | 3
4       |l1    | 2
3       | l3   | null
-----------------------------
</code>```

I have a another table like:

```<code>emp id | target achived | given target |
----------------------------------------
1      |  200            |  300
---------------------------------------
4      |  400            | 500
</code>```

I have a function which make a notification, like

```<code>l1 id----target achived/target given
</code>```

1       ,   200     /300
4       ,   400    /500

(above mentioned notification emp id 2 will get, who is a l2)
all l2 will get notification like this.

l3 will get sms of l2 only
for given case l2 target achived =all target achived by his all l1

so emp id 3 will get like--------

```<code>empid 2--- 2, 600/800
</code>```

how to design the query is generalized way that depth of hierarchy may be anything.. actual work is done by l1 only.
notification will be like--
l2 will get result of his own l1 only.
l3 will get result of his own l2 (sum of result of corresponding l1) and corresponding l2 sms also...so on.....

答:
In Oacle you have "Connected by" to run hierachical queries.

Here is a link to AskTom about this subject. You can also google "Oracle Connected By".

CONNECT BY basics

I don't have Oracle installed so I cannot test it but this is how you can get the achieved/target totals by manager:

Get the hierarchical results for the manager's reports by manager.
Get the stats for each manager as if they were their own bosses so as to to include the info in their own report.
Union the two sets of information.
And summarize the information by manager.

Again the query may have typos but the stratergy presented should work.

```<code>select sum(c_achieved), sum(c_target), c_manager
from
(
  -- Get the metrics of each manager's reports
  select all_info.t_achieved c_achieved, all_info.t_target c_target, all_info.manager c_manager
  from
    (select emp_id, post, manager, t_achieved, t_target
    from emps, targets
    where emps.emp_id = targets.emp_id) all_info
  start with all_info.manager is null
  connect by prior all_info.emp_id = all_info.manager
  union
  --Get the metrics of the managers to add them to themelves
  select all_info2.t_achieved, all_info2.t_target, all_info2.emp_id
  from
    (select null, post, emp_id, t_achieved, t_target
    from emps, targets
    where emps.emp_id in (select distinct manager from emps) all_info_2
  where all_info_2.emp_id = all_info_2.manager
) stats_by_manager
group by c_manager
</code>```

Title: fetching hierarchical data

Body:
i have table like:

emp id | post  | manager id
----------------------------
1       | l1   | 2
2       | l2   | 3
4       |l1    | 2
3       | l3   | null
-----------------------------

I have a another table like:

emp id | target achived | given target |
----------------------------------------
1      |  200            |  300
---------------------------------------
4      |  400            | 500

I have a function which make a notification, like

l1 id----target achived/target given

1       ,   200     /300
4       ,   400    /500

(above mentioned notification emp id 2 will get, who is a l2)
all l2 will get notification like this.

l3 will get sms of l2 only
for given case l2 target achived =all target achived by his all l1

so emp id 3 will get like--------

empid 2--- 2, 600/800

how to design the query is generalized way that depth of hierarchy may be anything.. actual work is done by l1 only.
notification will be like--
l2 will get result of his own l1 only.
l3 will get result of his own l2 (sum of result of corresponding l1) and corresponding l2 sms also...so on.....

Body:
In Oacle you have "Connected by" to run hierachical queries.

Here is a link to AskTom about this subject. You can also google "Oracle Connected By".

CONNECT BY basics

I don't have Oracle installed so I cannot test it but this is how you can get the achieved/target totals by manager:

Get the hierarchical results for the manager's reports by manager.
Get the stats for each manager as if they were their own bosses so as to to include the info in their own report.
Union the two sets of information.
And summarize the information by manager.

Again the query may have typos but the stratergy presented should work.

select sum(c_achieved), sum(c_target), c_manager
from
(
  -- Get the metrics of each manager's reports
  select all_info.t_achieved c_achieved, all_info.t_target c_target, all_info.manager c_manager
  from
    (select emp_id, post, manager, t_achieved, t_target
    from emps, targets
    where emps.emp_id = targets.emp_id) all_info
  start with all_info.manager is null
  connect by prior all_info.emp_id = all_info.manager
  union
  --Get the metrics of the managers to add them to themelves
  select all_info2.t_achieved, all_info2.t_target, all_info2.emp_id
  from
    (select null, post, emp_id, t_achieved, t_target
    from emps, targets
    where emps.emp_id in (select distinct manager from emps) all_info_2
  where all_info_2.emp_id = all_info_2.manager
) stats_by_manager
group by c_manager


答:
sorry i can't comment due to reputation :/ i use lumen (rest api of laravel) with xampp and it works fine. Can you provide somemore details?
I also think the path is the problem. Which path you use to access it via a browser? for lumen its /htdocs/project/public/ so in browser: http://localhost/project/public/
there i can access the api. should be similar for full laravel project?</p>

Title: Laravel with xampp

Body:
I need to understand this behavior.

I use xampp for web development. I start to apache server in the xampp gui and then I can start my projects in the browser via localhost...

Since yesterday I have added laravel to my mac book. My project is in the xampp htdocs folder and I want to use it witch xampp. But when the xampp apache server instance is running, nothing is happened to my laravel project until I run php artisan serve in the cmd.

How can I combine larael with xampp?
And what exactly does php artisan serve do? Start another apache server instance?


问:
Git pushing to repo with existing history (1 commit)
I have this project for which I've used repo started locally (and pushed to a private Github repo, but that is probably besides the question).

Now the client wants the code (with history, obviously) and want it pushed to their own repo, problem being that they created the remote repo with an initial commit (with an empty README) so now there are 2 histories, the project's and the remote's single-commit histories. Client says they can't create a completely empty repo, that at least that initial commit has to exist.

What would be the 'proper' way of pushing to this repository and merge their histories?

ETA: Client has refused the idea of just forcing the push and actually want the code push to be a pull request.

答:
Condolences. Anyway, you can force the merge with --allow-unrelated-histories:

```<code>git remote add origin ssh://git@github.com/YourClient/TheRepository
git fetch origin
git branch --set-upstream-to origin/master
git pull --allow-unrelated-histories
git push
</code>```

Body:
Condolences. Anyway, you can force the merge with --allow-unrelated-histories:

git remote add origin ssh://git@github.com/YourClient/TheRepository
git fetch origin
git branch --set-upstream-to origin/master
git pull --allow-unrelated-histories
git push


问:
REACT fetch post request
I have problem with routing post request
I need to build register form and post input from form to mongodb
I made router and post route on server side and it works ok (when I use postman)

//form is required model

router.route('/').post(function(req,res,next){
 res.send(req.body)
 form.create(
  {"first_name": req.body.first_name,
  "last_name": req.body.last_name
 })
  .then(function(data){
  res.send(data);
  console.log(data);
 }).catch(function(err){console.log(err)});
});```
</div>
</div>
</p>

<p>But I need to fire it form client side, not postman. And here i am lost. I can do it with  but when i add onSubmit action it doesnt work. And I need to use new function to fire another thing without redirecting to another page. How to pass this.refs.first_name.value to body so that i could use fetch function??
Below react component</p>

<p>added this JavaScript/JSON snippet</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>export default class Form extends React.Component {
 constructor(props){
  super(props);
  this.handleSubmit = this.handleSubmit.bind(this);
 }
 handleSubmit(event){
  event.preventDefault();
  console.log(this.refs.first_name.value);
  fetch('/', {
   method: 'post',
   body: {
    "first_name": this.refs.first_name.value
   }
  });
 };
 render () {
  return (

   <div id="signup">
    <form onSubmit={this.handleSubmit}>
        <input ref="first_name" placeholder="First Name" type="text" name="first_name"/><br />
        <input placeholder="Last Name" type="text" name="last_name"/><br />
       <button type="Submit">Start</button>
    </form>

   </div>

  )
 }
}</code>```

答:
I guess the way you are using ref has been deprecated. try below see if you have any luck.

export default class Form extends React.Component {
 constructor(props){
  super(props);
  this.handleSubmit = this.handleSubmit.bind(this);
 }

 handleSubmit(event){
  event.preventDefault();
  fetch('/', {
   method: 'post',
   headers: {'Content-Type':'application/json'},
   body: {
    "first_name": this.firstName.value
   }
  });
 };

 render () {
  return (

    <form onSubmit={this.handleSubmit}>
        <input ref={(ref) => {this.firstName = ref}} placeholder="First Name" type="text" name="first_name"/>

        <input ref={(ref) => {this.lastName = ref}} placeholder="Last Name" type="text" name="last_name"/>

       <button type="Submit">Start</button>
    </form>

  )
 }
}```

Here is a link to react docs about refs

Title: REACT fetch post request

Body:
I have problem with routing post request
I need to build register form and post input from form to mongodb
I made router and post route on server side and it works ok (when I use postman)

//form is required model

router.route('/').post(function(req,res,next){
 res.send(req.body)
 form.create(
  {"first_name": req.body.first_name,
  "last_name": req.body.last_name
 })
  .then(function(data){
  res.send(data);
  console.log(data);
 }).catch(function(err){console.log(err)});
});

But I need to fire it form client side, not postman. And here i am lost. I can do it with  but when i add onSubmit action it doesnt work. And I need to use new function to fire another thing without redirecting to another page. How to pass this.refs.first_name.value to body so that i could use fetch function??
Below react component

added this JavaScript/JSON snippet

export default class Form extends React.Component {
 constructor(props){
  super(props);
  this.handleSubmit = this.handleSubmit.bind(this);
 }
 handleSubmit(event){
  event.preventDefault();
  console.log(this.refs.first_name.value);
  fetch('/', {
   method: 'post',
   body: {
    "first_name": this.refs.first_name.value
   }
  });
 };
 render () {
  return (

    <form onSubmit={this.handleSubmit}>
        <input ref="first_name" placeholder="First Name" type="text" name="first_name"/>

        <input placeholder="Last Name" type="text" name="last_name"/>

       <button type="Submit">Start</button>
    </form>

  )
 }
}

Body:
I guess the way you are using ref has been deprecated. try below see if you have any luck.

export default class Form extends React.Component {
 constructor(props){
  super(props);
  this.handleSubmit = this.handleSubmit.bind(this);
 }

 handleSubmit(event){
  event.preventDefault();
  fetch('/', {
   method: 'post',
   headers: {'Content-Type':'application/json'},
   body: {
    "first_name": this.firstName.value
   }
  });
 };

 render () {
  return (

   <div id="signup">
    <form onSubmit={this.handleSubmit}>
        <input ref={(ref) => {this.firstName = ref}} placeholder="First Name" type="text" name="first_name"/><br />
        <input ref={(ref) => {this.lastName = ref}} placeholder="Last Name" type="text" name="last_name"/><br />
       <button type="Submit">Start</button>
    </form>

   </div>

  )
 }
}

Here is a link to react docs about refs


问:
Is it safe to cast jlong to long?
I'm developing a native plugin for Android with JNI in C++. I want to print out a jlong value, which is defined as a 64-bit value. Is it safe to cast it directly to a long, or are there any platform-specific issues I should be aware of?

```<code>jlong foo = 2;

// This results in the following warning:
// Format specifier '%ld' requires 'long' argument instead of 'jlong'.
printf("%ld", foo);

// This works without a warning.
printf("%ld", (long)foo);
</code>```

答:
The minimum range of values the C++ standard requires a long to represent (-2147483647 to 2147483647), which means it could be a 32-bit type.   Converting a jlong value to long that exceeds the range of a 32-bit type - if that is what a long is for your target implementation - will yield undefined behaviour.

The minimum required range (-9223372036854775807 to 9223372036854775807) of values that a long long can represent means it is a 64-bit type (or better).

The potential problem results from edge-cases: specifically the extreme (largest representable negative or largest positive values in the types), since 64-bit integral types can represent an even number of values, one of which is zero.  This means the number of positive values a 64-bit type can represent is one different (either more or less) than the number of negative values it can represent.  If jlong represents a different range of values than a long long  (e.g. jlong represents the range -9223372036854775807 to 9223372036854775808, while long long represents -9223372036854775808 to 9223372036854775807)  then the result of converting such extreme values can give undefined behaviour.

In short, there no guarantee that a long long will be able to represent exactly the same range of values as a jlong.  Practically, you will find most modern target platforms will be alright.  However, this was not true of some older systems and (theoretically at least) could change again in future.

If you can guarantee (e.g. through analysis of your Java code) that your jlong never holds one of the offending extreme values that a long long may not be able to represent, then there will be no problem converting to a long long.  There will also be no problem if you can guarantee (e.g. by referring to documentation for each target system and C++ compiler) that a long long supports at least the same range of values as a jlong.

You probably would be better off printing using C++ streams (which have insertion operators overloaded for each standard type) than using C I/O (which relies on you getting the format string right).

Title: Is it safe to cast jlong to long?

Body:
I'm developing a native plugin for Android with JNI in C++. I want to print out a jlong value, which is defined as a 64-bit value. Is it safe to cast it directly to a long, or are there any platform-specific issues I should be aware of?

jlong foo = 2;

// This results in the following warning:
// Format specifier '%ld' requires 'long' argument instead of 'jlong'.
printf("%ld", foo);

// This works without a warning.
printf("%ld", (long)foo);


问:
Spring cloud Feign:no suitable HttpMessageConverter found for response type [class org.springframework.web.servlet.ModelAndView]
I have a service which has a url that return ModelAndView Object.

In its own point, I can access the website. But when I use spring cloud feign to invoke that url, it comes out that no suitable HttpMessageConverter found for response type [class org.springframework.web.servlet.ModelAndView] and contentType text/html. Here is my feign client.

答:
Please try to change empList() method in your ConsumerController class like below.

```<code>public String empList() {
    return empService.empList();
}
</code>```

ModelAndView is not the actual response of /emplist from EmpController. It will be handled by DispatchServlet and ViewResolver will resolve the actual view with your view name - emp. So, from the view of ConsumerController, The response will be String object.

Anyway, I'm not sure that it's a good idea that accessing another web page via feign client in your case. Because if the original html page contains additional resources like images that existing in your origin server, it will not be served.

Body:
Please try to change empList() method in your ConsumerController class like below.

public String empList() {
    return empService.empList();
}

ModelAndView is not the actual response of /emplist from EmpController. It will be handled by DispatchServlet and ViewResolver will resolve the actual view with your view name - emp. So, from the view of ConsumerController, The response will be String object.

Anyway, I'm not sure that it's a good idea that accessing another web page via feign client in your case. Because if the original html page contains additional resources like images that existing in your origin server, it will not be served.


问:
Accord framework PrincipalComponentAnalysis on large data
I'm using the Accord dotnet framework to do PrincipalComponentAnalysis.

I have a computed distance matrix, then I apply the KPCA on it:

```<code>Dim pca = new KernelPrincipalComponentAnalysis()
pca.Learn(distances)
pca.NumberOfOutputs = 2
Dim actual()() As double = pca.Transform(distances)
</code>```

This is working well. However if the matrix is quite big (e.g 2000x2000), pca.learn takes several minutes.
Is there a way to learn with a sampling matrix (e.g 500x500) in order to transform the big matrix ?
I have tried:

```<code>pca.Learn(sampling)
pca.Transform(distances)
</code>```

But I get an error because the matrix does not have the right size.

Best Regards
Jean-Michel

答:
What you ask should be possible to do if the matrix you refer to as a distance matrix is actually a kernel matrix. Since you are using KPCA I am assuming this can be the case, so I will show below a way to create use KPCA learn and transform methods using kernel matrices with different sizes.

```<code>// Let's say those were our original data points
double[][] data =
{
    new double[] { 2.5,  2.4 },
    new double[] { 0.5,  0.7 },
    new double[] { 2.2,  2.9 },
    new double[] { 1.9,  2.2 },
    new double[] { 3.1,  3.0 },
    new double[] { 2.3,  2.7 },
    new double[] { 2.0,  1.6 },
    new double[] { 1.0,  1.1 },
    new double[] { 1.5,  1.6 },
    new double[] { 1.1,  0.9 }
};
</code>```

Now, let's say that we already have their kernel matrix K available somehow. Note: a way to compute K would have been something similar to

```<code>double[] mean = data.Mean(dimension: 0);
double[][] x = data.Subtract(mean, dimension: 0);
Linear kernel = new Linear();
double[][] K = kernel.ToJagged(x);
</code>```

Now, assuming that K is already available, we can create a KPCA as

```<code>var pca = new KernelPrincipalComponentAnalysis(kernel, PrincipalComponentMethod.KernelMatrix);
</code>```

And then learn it using

```<code>pca.Learn(K); // note: we pass the kernel matrix instead of the data points
</code>```

For the example above, we would have

```<code>// Those are the expected eigenvalues, in descending order:
double[] eigenvalues = pca.Eigenvalues.Divide(data.Length - 1); //  { 1.28, 0.049 };

// And this will be their proportion:
double[] proportions = pca.ComponentProportions; // { 0.96, 0.03 };

// We can transform the inputs using
double[][] actual = pca.Transform(K);

// The output should be similar to
double[,] expected = new double[,]
{
    {  0.827970186, -0.175115307 },
    { -1.77758033,   0.142857227 },
    {  0.992197494,  0.384374989 },
    {  0.274210416,  0.130417207 },
    {  1.67580142,  -0.209498461 },
    {  0.912949103,  0.175282444 },
    { -0.099109437, -0.349824698 },
    { -1.14457216,   0.046417258 },
    { -0.438046137,  0.017764629 },
    { -1.22382056,  -0.162675287 },
}.Multiply(-1);
</code>```

Now, finally, to answer the question about how to use our KPCA to transform a kernel matrix of a different size, we can use

```<code>double[][] newData = // this is a smaller matrix than the original
{
    new double[] { 2.2,  2.7 },
    new double[] { 1.2,  4.9 },
    new double[] { 1.8,  0.2 },
};

// Subtract the mean before computing a kernel matrix
double[][] y = newData.Subtract(mean, dimension: 0);

// Create the kernel matrix for new data
double[][] newK = kernel.ToJagged2(y, x);

// Transform using the new kernel matrix
double[][] output = pca.Transform(newK);

// Output will be similar to
double[][] expected =
{
    new double[] { -0.845161763306007, -0.24880030917481 },
    new double[] { -1.78468140697569,  -2.47530044148084 },
    new double[] {  1.26393423496622,   1.15181172492746 }
};
</code>```

Body:
I'm using the Accord dotnet framework to do PrincipalComponentAnalysis.

I have a computed distance matrix, then I apply the KPCA on it:

Dim pca = new KernelPrincipalComponentAnalysis()
pca.Learn(distances)
pca.NumberOfOutputs = 2
Dim actual()() As double = pca.Transform(distances)

This is working well. However if the matrix is quite big (e.g 2000x2000), pca.learn takes several minutes.
Is there a way to learn with a sampling matrix (e.g 500x500) in order to transform the big matrix ?
I have tried:

pca.Learn(sampling)
pca.Transform(distances)

But I get an error because the matrix does not have the right size.

Best Regards
Jean-Michel

Body:
What you ask should be possible to do if the matrix you refer to as a distance matrix is actually a kernel matrix. Since you are using KPCA I am assuming this can be the case, so I will show below a way to create use KPCA learn and transform methods using kernel matrices with different sizes.

// Let's say those were our original data points
double[][] data =
{
    new double[] { 2.5,  2.4 },
    new double[] { 0.5,  0.7 },
    new double[] { 2.2,  2.9 },
    new double[] { 1.9,  2.2 },
    new double[] { 3.1,  3.0 },
    new double[] { 2.3,  2.7 },
    new double[] { 2.0,  1.6 },
    new double[] { 1.0,  1.1 },
    new double[] { 1.5,  1.6 },
    new double[] { 1.1,  0.9 }
};

Now, let's say that we already have their kernel matrix K available somehow. Note: a way to compute K would have been something similar to

double[] mean = data.Mean(dimension: 0);
double[][] x = data.Subtract(mean, dimension: 0);
Linear kernel = new Linear();
double[][] K = kernel.ToJagged(x);

Now, assuming that K is already available, we can create a KPCA as

var pca = new KernelPrincipalComponentAnalysis(kernel, PrincipalComponentMethod.KernelMatrix);

And then learn it using

pca.Learn(K); // note: we pass the kernel matrix instead of the data points

For the example above, we would have

// Those are the expected eigenvalues, in descending order:
double[] eigenvalues = pca.Eigenvalues.Divide(data.Length - 1); //  { 1.28, 0.049 };

// And this will be their proportion:
double[] proportions = pca.ComponentProportions; // { 0.96, 0.03 };

// We can transform the inputs using
double[][] actual = pca.Transform(K);

// The output should be similar to
double[,] expected = new double[,]
{
    {  0.827970186, -0.175115307 },
    { -1.77758033,   0.142857227 },
    {  0.992197494,  0.384374989 },
    {  0.274210416,  0.130417207 },
    {  1.67580142,  -0.209498461 },
    {  0.912949103,  0.175282444 },
    { -0.099109437, -0.349824698 },
    { -1.14457216,   0.046417258 },
    { -0.438046137,  0.017764629 },
    { -1.22382056,  -0.162675287 },
}.Multiply(-1);

Now, finally, to answer the question about how to use our KPCA to transform a kernel matrix of a different size, we can use

double[][] newData = // this is a smaller matrix than the original
{
    new double[] { 2.2,  2.7 },
    new double[] { 1.2,  4.9 },
    new double[] { 1.8,  0.2 },
};

// Subtract the mean before computing a kernel matrix
double[][] y = newData.Subtract(mean, dimension: 0);

// Create the kernel matrix for new data
double[][] newK = kernel.ToJagged2(y, x);

// Transform using the new kernel matrix
double[][] output = pca.Transform(newK);

// Output will be similar to
double[][] expected =
{
    new double[] { -0.845161763306007, -0.24880030917481 },
    new double[] { -1.78468140697569,  -2.47530044148084 },
    new double[] {  1.26393423496622,   1.15181172492746 }
};


问:
How to save the data into File in java?
I have one problem, that is I have one string of data and I want to save it into a separate file every time. Please give me a suggestion.

Thanks,
vara kumar.pjd

答:
A one liner. Using base 36 for the ids will make the file names shorter.

IOUtils.write(text, new FileWriter(Long.toString(System.currentTimeMillis(), 36)+".txt")));

http://commons.apache.org/io/

ContentLicense: CC BY-SA 2.5

Title: How to save the data into File in java?


问:
maven system scope dependency could not be resolved
I have an application which run on IBM Was. It is a maven Project and On its dependency tree There are some was runtime dependencies but their scopes are system.

These system scope jars do not exists in .m2/repository or our local nexus. But I can compile Project (mvn clean install) in my local environment. Some how, maven could find these jars.

```<code>[INFO] |  |  +- com.ibm.was:was-server-runtime-lib:pom:7.0.0:provided
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:com.ibm.ws.wccm:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:com.ibm.ws.emf:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:j2ee:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:mail-impl:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:com.ibm.ws.runtime:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:com.ibm.ws.ejbportable:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:com.ibm.ws.admin.core:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:com.ibm.ws.admin.services:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:com.ibm.ws.portletcontainer:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:bootstrap:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:com.ibm.ws.sib.server:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:com.ibm.ws.sip.container:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:com.ibm.ws.sip.interface:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:com.ibm.ws.webcontainer:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:marshall:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:ffdcSupport:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:wsatlib:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:com.ibm.ws.runtime.dist:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:com.ibm.mq:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:com.ibm.mq.headers:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:com.ibm.mq.pcf:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:com.ibm.mq.jmqi:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:com.ibm.mq.connector:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:com.ibm.mq.commonservices:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:dhbcore:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:org.eclipse.emf.common:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:org.eclipse.emf.commonj.sdo:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:org.eclipse.emf.ecore.change:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:org.eclipse.emf.ecore.sdo:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:org.eclipse.emf.ecore.xmi:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:org.eclipse.emf.ecore:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:com.ibm.ws.prereq.wsdl4j:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:com.ibm.jaxb.tools:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:com.ibm.jaxws.tools:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:com.ibm.wsfp.main:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:com.ibm.ws.prereq.vajava:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:rsadbutils:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:com.ibm.ws.jpa:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:com.ibm.ws.prereq.commonj-twm:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:com.ibm.ws.prereq.soap:jar:7.0.0:system
[INFO] |  |  |  \- com.ibm.websphere.application.server.v7.0:com.ibm.mqjms:jar:7.0.0:system
</code>```

But, On build server these jar could not be found and following error occurs.

```<code>The following artifacts could not be resolved: com.ibm.websphere.application.server.v7.0:com.ibm.ws.wccm:jar:7.0.0, com.ibm.websphere.application.server.v7.0:com.ibm.ws.emf:jar:7.0.0, com.ibm.websphere.application.server.v7.0:j2ee:jar:7.0.0, com.ibm.websphere.application.server.v7.0:mail-impl:jar:7.0.0, com.ibm.websphere.application.server.v7.0:com.ibm.ws.runtime:jar:7.0.0, com.ibm.websphere.application.server.v7.0:com.ibm.ws.ejbportable:jar:7.0.0, com.ibm.websphere.application.server.v7.0:com.ibm.ws.admin.core:jar:7.0.0, com.ibm.websphere.application.server.v7.0:com.ibm.ws.admin.services:jar:7.0.0, com.ibm.websphere.application.server.v7.0:com.ibm.ws.portletcontainer:jar:7.0.0, com.ibm.websphere.application.server.v7.0:bootstrap:jar:7.0.0, com.ibm.websphere.application.server.v7.0:com.ibm.ws.sib.server:jar:7.0.0, com.ibm.websphere.application.server.v7.0:com.ibm.ws.sip.container:jar:7.0.0, com.ibm.websphere.application.server.v7.0:com.ibm.ws.sip.interface:jar:7.0.0, com.ibm.websphere.application.server.v7.0:com.ibm.ws.webcontainer:jar:7.0.0, com.ibm.websphere.application.server.v7.0:marshall:jar:7.0.0, com.ibm.websphere.application.server.v7.0:ffdcSupport:jar:7.0.0, com.ibm.websphere.application.server.v7.0:wsatlib:jar:7.0.0, com.ibm.websphere.application.server.v7.0:com.ibm.ws.runtime.dist:jar:7.0.0, com.ibm.websphere.application.server.v7.0:com.ibm.mq:jar:7.0.0, com.ibm.websphere.application.server.v7.0:com.ibm.mq.headers:jar:7.0.0, com.ibm.websphere.application.server.v7.0:com.ibm.mq.pcf:jar:7.0.0, com.ibm.websphere.application.server.v7.0:com.ibm.mq.jmqi:jar:7.0.0, com.ibm.websphere.application.server.v7.0:com.ibm.mq.connector:jar:7.0.0, com.ibm.websphere.application.server.v7.0:com.ibm.mq.commonservices:jar:7.0.0, com.ibm.websphere.application.server.v7.0:dhbcore:jar:7.0.0, com.ibm.websphere.application.server.v7.0:org.eclipse.emf.common:jar:7.0.0, com.ibm.websphere.application.server.v7.0:org.eclipse.emf.commonj.sdo:jar:7.0.0, com.ibm.websphere.application.server.v7.0:org.eclipse.emf.ecore.change:jar:7.0.0, com.ibm.websphere.application.server.v7.0:org.eclipse.emf.ecore.sdo:jar:7.0.0, com.ibm.websphere.application.server.v7.0:org.eclipse.emf.ecore.xmi:jar:7.0.0, com.ibm.websphere.application.server.v7.0:org.eclipse.emf.ecore:jar:7.0.0, com.ibm.websphere.application.server.v7.0:com.ibm.ws.prereq.wsdl4j:jar:7.0.0, com.ibm.websphere.application.server.v7.0:com.ibm.jaxb.tools:jar:7.0.0, com.ibm.websphere.application.server.v7.0:com.ibm.jaxws.tools:jar:7.0.0, com.ibm.websphere.application.server.v7.0:com.ibm.wsfp.main:jar:7.0.0, com.ibm.websphere.application.server.v7.0:com.ibm.ws.prereq.vajava:jar:7.0.0, com.ibm.websphere.application.server.v7.0:rsadbutils:jar:7.0.0, com.ibm.websphere.application.server.v7.0:com.ibm.ws.jpa:jar:7.0.0, com.ibm.websphere.application.server.v7.0:com.ibm.ws.prereq.commonj-twm:jar:7.0.0, com.ibm.websphere.application.server.v7.0:com.ibm.ws.prereq.soap:jar:7.0.0, com.ibm.websphere.application.server.v7.0:com.ibm.mqjms:jar:7.0.0: Could not find artifact com.ibm.websphere.application.server.v7.0:com.ibm.ws.wccm:jar:7.0.0 at specified path C:\..\com.ibm.ws.wccm.jar -> [Help 1]
</code>```

答:
System scope dependecies are not downloaded from nexus repositories. They supposed to exist in the system where it is specified in pom file. I have realized there are some system path in the pom file and releted jar should exists in this folder. In order to solve the problem, I have created a folder in the exact same location and copied all related jars to this folder. Afterwards, I was able to compile the Project.

Sample pom file content for system scope dependency, For this sample missing jars should be copied to c:\SharedSystemLib. That's all.

```<code><dependency>
    <groupId>${groupId}</groupId>
    <artifactId>com.ibm.ws.wccm</artifactId>
    <version>${version}</version>
    <scope>system</scope>
    <systemPath>c:\SharedSystemLib</systemPath>
</dependency>
</code>```

Body:
I have an application which run on IBM Was. It is a maven Project and On its dependency tree There are some was runtime dependencies but their scopes are system.

These system scope jars do not exists in .m2/repository or our local nexus. But I can compile Project (mvn clean install) in my local environment. Some how, maven could find these jars.

[INFO] |  |  +- com.ibm.was:was-server-runtime-lib:pom:7.0.0:provided
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:com.ibm.ws.wccm:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:com.ibm.ws.emf:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:j2ee:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:mail-impl:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:com.ibm.ws.runtime:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:com.ibm.ws.ejbportable:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:com.ibm.ws.admin.core:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:com.ibm.ws.admin.services:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:com.ibm.ws.portletcontainer:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:bootstrap:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:com.ibm.ws.sib.server:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:com.ibm.ws.sip.container:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:com.ibm.ws.sip.interface:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:com.ibm.ws.webcontainer:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:marshall:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:ffdcSupport:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:wsatlib:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:com.ibm.ws.runtime.dist:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:com.ibm.mq:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:com.ibm.mq.headers:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:com.ibm.mq.pcf:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:com.ibm.mq.jmqi:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:com.ibm.mq.connector:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:com.ibm.mq.commonservices:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:dhbcore:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:org.eclipse.emf.common:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:org.eclipse.emf.commonj.sdo:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:org.eclipse.emf.ecore.change:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:org.eclipse.emf.ecore.sdo:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:org.eclipse.emf.ecore.xmi:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:org.eclipse.emf.ecore:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:com.ibm.ws.prereq.wsdl4j:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:com.ibm.jaxb.tools:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:com.ibm.jaxws.tools:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:com.ibm.wsfp.main:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:com.ibm.ws.prereq.vajava:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:rsadbutils:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:com.ibm.ws.jpa:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:com.ibm.ws.prereq.commonj-twm:jar:7.0.0:system
[INFO] |  |  |  +- com.ibm.websphere.application.server.v7.0:com.ibm.ws.prereq.soap:jar:7.0.0:system
[INFO] |  |  |  \- com.ibm.websphere.application.server.v7.0:com.ibm.mqjms:jar:7.0.0:system

But, On build server these jar could not be found and following error occurs.

The following artifacts could not be resolved: com.ibm.websphere.application.server.v7.0:com.ibm.ws.wccm:jar:7.0.0, com.ibm.websphere.application.server.v7.0:com.ibm.ws.emf:jar:7.0.0, com.ibm.websphere.application.server.v7.0:j2ee:jar:7.0.0, com.ibm.websphere.application.server.v7.0:mail-impl:jar:7.0.0, com.ibm.websphere.application.server.v7.0:com.ibm.ws.runtime:jar:7.0.0, com.ibm.websphere.application.server.v7.0:com.ibm.ws.ejbportable:jar:7.0.0, com.ibm.websphere.application.server.v7.0:com.ibm.ws.admin.core:jar:7.0.0, com.ibm.websphere.application.server.v7.0:com.ibm.ws.admin.services:jar:7.0.0, com.ibm.websphere.application.server.v7.0:com.ibm.ws.portletcontainer:jar:7.0.0, com.ibm.websphere.application.server.v7.0:bootstrap:jar:7.0.0, com.ibm.websphere.application.server.v7.0:com.ibm.ws.sib.server:jar:7.0.0, com.ibm.websphere.application.server.v7.0:com.ibm.ws.sip.container:jar:7.0.0, com.ibm.websphere.application.server.v7.0:com.ibm.ws.sip.interface:jar:7.0.0, com.ibm.websphere.application.server.v7.0:com.ibm.ws.webcontainer:jar:7.0.0, com.ibm.websphere.application.server.v7.0:marshall:jar:7.0.0, com.ibm.websphere.application.server.v7.0:ffdcSupport:jar:7.0.0, com.ibm.websphere.application.server.v7.0:wsatlib:jar:7.0.0, com.ibm.websphere.application.server.v7.0:com.ibm.ws.runtime.dist:jar:7.0.0, com.ibm.websphere.application.server.v7.0:com.ibm.mq:jar:7.0.0, com.ibm.websphere.application.server.v7.0:com.ibm.mq.headers:jar:7.0.0, com.ibm.websphere.application.server.v7.0:com.ibm.mq.pcf:jar:7.0.0, com.ibm.websphere.application.server.v7.0:com.ibm.mq.jmqi:jar:7.0.0, com.ibm.websphere.application.server.v7.0:com.ibm.mq.connector:jar:7.0.0, com.ibm.websphere.application.server.v7.0:com.ibm.mq.commonservices:jar:7.0.0, com.ibm.websphere.application.server.v7.0:dhbcore:jar:7.0.0, com.ibm.websphere.application.server.v7.0:org.eclipse.emf.common:jar:7.0.0, com.ibm.websphere.application.server.v7.0:org.eclipse.emf.commonj.sdo:jar:7.0.0, com.ibm.websphere.application.server.v7.0:org.eclipse.emf.ecore.change:jar:7.0.0, com.ibm.websphere.application.server.v7.0:org.eclipse.emf.ecore.sdo:jar:7.0.0, com.ibm.websphere.application.server.v7.0:org.eclipse.emf.ecore.xmi:jar:7.0.0, com.ibm.websphere.application.server.v7.0:org.eclipse.emf.ecore:jar:7.0.0, com.ibm.websphere.application.server.v7.0:com.ibm.ws.prereq.wsdl4j:jar:7.0.0, com.ibm.websphere.application.server.v7.0:com.ibm.jaxb.tools:jar:7.0.0, com.ibm.websphere.application.server.v7.0:com.ibm.jaxws.tools:jar:7.0.0, com.ibm.websphere.application.server.v7.0:com.ibm.wsfp.main:jar:7.0.0, com.ibm.websphere.application.server.v7.0:com.ibm.ws.prereq.vajava:jar:7.0.0, com.ibm.websphere.application.server.v7.0:rsadbutils:jar:7.0.0, com.ibm.websphere.application.server.v7.0:com.ibm.ws.jpa:jar:7.0.0, com.ibm.websphere.application.server.v7.0:com.ibm.ws.prereq.commonj-twm:jar:7.0.0, com.ibm.websphere.application.server.v7.0:com.ibm.ws.prereq.soap:jar:7.0.0, com.ibm.websphere.application.server.v7.0:com.ibm.mqjms:jar:7.0.0: Could not find artifact com.ibm.websphere.application.server.v7.0:com.ibm.ws.wccm:jar:7.0.0 at specified path C:\..\com.ibm.ws.wccm.jar -> [Help 1]

Body:
System scope dependecies are not downloaded from nexus repositories. They supposed to exist in the system where it is specified in pom file. I have realized there are some system path in the pom file and releted jar should exists in this folder. In order to solve the problem, I have created a folder in the exact same location and copied all related jars to this folder. Afterwards, I was able to compile the Project.

Sample pom file content for system scope dependency, For this sample missing jars should be copied to c:\SharedSystemLib. That's all.

<dependency>
    <groupId>${groupId}</groupId>
    <artifactId>com.ibm.ws.wccm</artifactId>
    <version>${version}</version>
    <scope>system</scope>
    <systemPath>c:\SharedSystemLib</systemPath>
</dependency>