问:
How to restrict particles from falling forever at the bottom of screen?
I want to stop those particles at the bottom of screen or prevent them to fall forever below the screen. Code requires to settle all the particles collected at the bottom of screen. Please run the demo below and 'click the particle' text. when the particles are generated they are required to be collected at the bottom.

//-------------------------------- For Squares-------------

var d = document, $d = $(d),
    w = window, $w = $(w),
    wWidth = $w.width(), wHeight = $w.height(),
    credit = $('.credit > a'),
    particles = $('.particles'),
    particleCount = 0,
    maxTime = 10,
    sizes = [
        75
    ],
    colors = [
      '#f44336', '#e91e63', '#9c27b0', '#673ab7', '#3f51b5',
      '#2196f3', '#03a9f4', '#00bcd4', '#009688', '#4CAF50',
      '#8BC34A', '#CDDC39', '#FFEB3B', '#FFC107', '#FF9800',
      '#FF5722', '#795548', '#9E9E9E', '#607D8B', '#777777'
    ],

    mouseX = $w.width() / 2, mouseY = $w.height() / 2;

function updateParticleCount () {
  $('.particle-count > .number').text(particleCount);
};

$w
.on( 'resize' , function () {
  wWidth = $w.width();
  wHeight = $w.height();
});

$("p")
.on( 'mousemove touchmove' , function ( event ) {
  event.preventDefault();
  event.stopPropagation();
  mouseX = event.clientX;
  mouseY = event.clientY;
  if( !!event.originalEvent.touches ) {
    mouseX = event.originalEvent.touches[0].clientX;
    mouseY = event.originalEvent.touches[0].clientY;
  }
})
.on( 'mousedown touchstart' , function( event ) {
  if( event.target === credit.get(0) ){
    return;
  }
  mouseX = event.clientX;
  mouseY = event.clientY;
  if( !!event.originalEvent.touches ) {
    mouseX = event.originalEvent.touches[0].clientX;
    mouseY = event.originalEvent.touches[0].clientY;
  }

 var counter = 0;

   var timer = setInterval(function () {
    if (counter < maxTime) {
      createParticle( event );
    } else {
      clearInterval( timer );
      counter = 0;
    }
    counter++;

  }, 1000 / 20);

  $("p").
  on('mouseup mouseleave touchend touchcancel touchleave', function () {
    clearInterval( timer );
  });
});

function createParticle ( event ) {
  var particle = $('
' + getSymbol() + '
'),
      size = sizes[Math.floor(Math.random() * sizes.length)],
      color = colors[Math.floor(Math.random() * colors.length)],
      negative = size/2,
      speedHorz = Math.random() * 10,
      speedUp = Math.random() * 25,
      spinVal = 360 * Math.random(),
      spinSpeed = ((12 * Math.random())) * (Math.random() <=.5 ? -1 : 1),
      otime,
      time = otime = (1 + (.5 * Math.random())) * 1000,
      top = (mouseY - negative),
      left = (mouseX - negative),
      direction = Math.random() <=.5 ? -1 : 1 ,
      life = 10;

  particle
  .css({
    height: size + 'px',
    width: size + 'px',
    top: top + 'px',
    left: left + 'px',
    background: color,
    transform: 'rotate(' + spinVal + 'deg)',
    webkitTransform: 'rotate(' + spinVal + 'deg)'
  })
  .appendTo( particles );
  particleCount++;
  updateParticleCount();

  var particleTimer = setInterval(function () {
    time = time - life;
    left = left - (speedHorz * direction);
    top = top - speedUp;
    speedUp = Math.min(size, speedUp - 1);
    spinVal = spinVal + spinSpeed;

    particle
    .css({
      height: size + 'px',
      width: size + 'px',
      top: top + 'px',
      left: left + 'px',
      opacity: ((time / otime)/2) + 1.0,
      transform: 'rotate(' + spinVal + 'deg)',
      webkitTransform: 'rotate(' + spinVal + 'deg)'
    });

    if( time <= 0 || left <= -size || left >= wWidth + size || top >= wHeight + size ) {
      particle.remove();
      particleCount--;
      updateParticleCount();
      clearInterval(particleTimer);
    }
  }, 1000 / 50);
}

//-------------------------------- For Circles-------------

var d = document, $d = $(d),
    w = window, $w = $(w),
    wWidth = $w.width(), wHeight = $w.height(),
    credit = $('.credit > a'),
    particles2 = $('.particles2'),
    particle2Count = 0,
    maxTime = 10,
    sizes = [
        75
    ],
    colors = [
      '#f44336', '#e91e63', '#9c27b0', '#673ab7', '#3f51b5',
      '#2196f3', '#03a9f4', '#00bcd4', '#009688', '#4CAF50',
      '#8BC34A', '#CDDC39', '#FFEB3B', '#FFC107', '#FF9800',
      '#FF5722', '#795548', '#9E9E9E', '#607D8B', '#777777'
    ],

    mouseX = $w.width() / 2, mouseY = $w.height() / 2;

function updateParticle2Count () {
  $('.particle2-count > .number').text(particle2Count);
};

$w
.on( 'resize' , function () {
  wWidth = $w.width();
  wHeight = $w.height();
});

$("p")
.on( 'mousemove touchmove' , function ( event ) {
  event.preventDefault();
  event.stopPropagation();
  mouseX = event.clientX;
  mouseY = event.clientY;
  if( !!event.originalEvent.touches ) {
    mouseX = event.originalEvent.touches[0].clientX;
    mouseY = event.originalEvent.touches[0].clientY;
  }
})
.on( 'mousedown touchstart' , function( event ) {
  if( event.target === credit.get(0) ){
    return;
  }
  mouseX = event.clientX;
  mouseY = event.clientY;
  if( !!event.originalEvent.touches ) {
    mouseX = event.originalEvent.touches[0].clientX;
    mouseY = event.originalEvent.touches[0].clientY;
  }

  var counter = 0;

   var timer = setInterval(function () {
    if (counter < maxTime) {
      createParticle2( event );
    } else {
      clearInterval( timer );
      counter = 0;
    }
    counter++;

  }, 1000 / 20);

  $("p").
  on('mouseup mouseleave touchend touchcancel touchleave', function () {
    clearInterval( timer );
  });
});

function createParticle2 ( event ) {
  var particle2 = $('
' + getSymbol() + '
'),
      size = sizes[Math.floor(Math.random() * sizes.length)],
      color = colors[Math.floor(Math.random() * colors.length)],
      negative = size/2,
      speedHorz = Math.random() * 10,
      speedUp = Math.random() * 25,
      spinVal = 360 * Math.random(),
      spinSpeed = ((12 * Math.random())) * (Math.random() <=.5 ? -1 : 1),
      otime,
      time = otime = (1 + (.5 * Math.random())) * 1000,
      top = (mouseY - negative),
      left = (mouseX - negative),
      direction = Math.random() <=.5 ? -1 : 1 ,
      life = 10;

  particle2
  .css({
    height: size + 'px',
    width: size + 'px',
    top: top + 'px',
    left: left + 'px',
    background: color,
    transform: 'rotate(' + spinVal + 'deg)',
    webkitTransform: 'rotate(' + spinVal + 'deg)'
  })
  .appendTo( particles2 );
  particle2Count++;
  updateParticle2Count();

  var particle2Timer = setInterval(function () {
    time = time - life;
    left = left - (speedHorz * direction);
    top = top - speedUp;
    speedUp = Math.min(size, speedUp - 1);
    spinVal = spinVal + spinSpeed;

    particle2
    .css({
      height: size + 'px',
      width: size + 'px',
      top: top + 'px',
      left: left + 'px',
      opacity: ((time / otime)/2) + 1.0,
      transform: 'rotate(' + spinVal + 'deg)',
      webkitTransform: 'rotate(' + spinVal + 'deg)'
    });

    if( time <= 0 || left <= -size || left >= wWidth + size || top >= wHeight + size ) {
      particle2.remove();
      particle2Count--;
      updateParticle2Count();
      clearInterval(particle2Timer);
    }
  }, 1000 / 50);
}
function getSymbol() {
  var symbols = "12X34Y5Z+x=-%";
  return symbols.charAt(Math.floor(Math.random() * symbols.length));
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@import url('https://fonts.googleapis.com/css?family=Roboto+Slab:300');
.particle-count {
  display: block;
  text-align: center;
  margin: 25px 0;
}

.particles > .particle {
  background: #000;
  border-radius: 20%;
  position: absolute;
  background-repeat: no-repeat;
  color: white;
}

.particles > .particle.small {
  width: 10px;
  height: 10px;
}
.particles > .particle.normal {
  width: 15px;
  height: 15px;
}
.particles > .particle.big {
  width: 20px;
  height: 20px;
}
.particles > .particle.bigger {
  width: 25px;
  height: 25px;
}

.particles {
  background: #000;
  border-radius: 100%;
  position: absolute;
  background-repeat: no-repeat;
  font-family: 'Roboto Slab', serif;
  font-size: 48px;
  text-align: center;
}

/**-----------------------------------------------------------------**/
.particle2-count {
  display: block;
  text-align: center;
  margin: 25px 0;
}

.particles2 > .particle2 {
  background: #000;
  border-radius: 100%;
  position: absolute;
  background-repeat: no-repeat;
  color: white;
}

.particles2 > .particle2.small {
  width: 10px;
  height: 10px;
}
.particles2 > .particle2.normal {
  width: 15px;
  height: 15px;
}
.particles2 > .particle2.big {
  width: 20px;
  height: 20px;
}
.particles2 > .particle2.bigger {
  width: 25px;
  height: 25px;
}

.particles2 {
  background: #000;
  border-radius: 100%;
  position: absolute;
  background-repeat: no-repeat;
  font-family: 'Roboto Slab', serif;
  font-size: 48px;
  text-align: center;
}</code>```

Click for particles

```

I hope you guys can easily fix this
Thanks!

答:
To make something "bounce" when it reaches the bottom of the frame you should check if it is below the bottom of the screen if so reverse the velocity of the particle, dampen its rebound velocity by multiplying it by a number less than one and set its height to be the bottom of the screen- this helps with stutter. For instance:

```<code>if (top + size > wHeight) {
  speedUp = -0.7 * speedUp; // rebounds with 0.7 times the velocity
  top = wHeight - size;
}
</code>```

JSFiddle example.

Hope this helps!

Body:
I want to stop those particles at the bottom of screen or prevent them to fall forever below the screen. Code requires to settle all the particles collected at the bottom of screen. Please run the demo below and 'click the particle' text. when the particles are generated they are required to be collected at the bottom.

//-------------------------------- For Squares-------------

var d = document, $d = $(d),
    w = window, $w = $(w),
    wWidth = $w.width(), wHeight = $w.height(),
    credit = $('.credit > a'),
    particles = $('.particles'),
    particleCount = 0,
    maxTime = 10,
    sizes = [
        75
    ],
    colors = [
      '#f44336', '#e91e63', '#9c27b0', '#673ab7', '#3f51b5',
      '#2196f3', '#03a9f4', '#00bcd4', '#009688', '#4CAF50',
      '#8BC34A', '#CDDC39', '#FFEB3B', '#FFC107', '#FF9800',
      '#FF5722', '#795548', '#9E9E9E', '#607D8B', '#777777'
    ],

    mouseX = $w.width() / 2, mouseY = $w.height() / 2;

function updateParticleCount () {
  $('.particle-count > .number').text(particleCount);
};

$w
.on( 'resize' , function () {
  wWidth = $w.width();
  wHeight = $w.height();
});

$("p")
.on( 'mousemove touchmove' , function ( event ) {
  event.preventDefault();
  event.stopPropagation();
  mouseX = event.clientX;
  mouseY = event.clientY;
  if( !!event.originalEvent.touches ) {
    mouseX = event.originalEvent.touches[0].clientX;
    mouseY = event.originalEvent.touches[0].clientY;
  }
})
.on( 'mousedown touchstart' , function( event ) {
  if( event.target === credit.get(0) ){
    return;
  }
  mouseX = event.clientX;
  mouseY = event.clientY;
  if( !!event.originalEvent.touches ) {
    mouseX = event.originalEvent.touches[0].clientX;
    mouseY = event.originalEvent.touches[0].clientY;
  }

 var counter = 0;

   var timer = setInterval(function () {
    if (counter < maxTime) {
      createParticle( event );
    } else {
      clearInterval( timer );
      counter = 0;
    }
    counter++;

  }, 1000 / 20);

  $("p").
  on('mouseup mouseleave touchend touchcancel touchleave', function () {
    clearInterval( timer );
  });
});

function createParticle ( event ) {
  var particle = $('
' + getSymbol() + '
'),
      size = sizes[Math.floor(Math.random() * sizes.length)],
      color = colors[Math.floor(Math.random() * colors.length)],
      negative = size/2,
      speedHorz = Math.random() * 10,
      speedUp = Math.random() * 25,
      spinVal = 360 * Math.random(),
      spinSpeed = ((12 * Math.random())) * (Math.random() <=.5 ? -1 : 1),
      otime,
      time = otime = (1 + (.5 * Math.random())) * 1000,
      top = (mouseY - negative),
      left = (mouseX - negative),
      direction = Math.random() <=.5 ? -1 : 1 ,
      life = 10;

  particle
  .css({
    height: size + 'px',
    width: size + 'px',
    top: top + 'px',
    left: left + 'px',
    background: color,
    transform: 'rotate(' + spinVal + 'deg)',
    webkitTransform: 'rotate(' + spinVal + 'deg)'
  })
  .appendTo( particles );
  particleCount++;
  updateParticleCount();

  var particleTimer = setInterval(function () {
    time = time - life;
    left = left - (speedHorz * direction);
    top = top - speedUp;
    speedUp = Math.min(size, speedUp - 1);
    spinVal = spinVal + spinSpeed;

    particle
    .css({
      height: size + 'px',
      width: size + 'px',
      top: top + 'px',
      left: left + 'px',
      opacity: ((time / otime)/2) + 1.0,
      transform: 'rotate(' + spinVal + 'deg)',
      webkitTransform: 'rotate(' + spinVal + 'deg)'
    });

    if( time <= 0 || left <= -size || left >= wWidth + size || top >= wHeight + size ) {
      particle.remove();
      particleCount--;
      updateParticleCount();
      clearInterval(particleTimer);
    }
  }, 1000 / 50);
}

//-------------------------------- For Circles-------------

var d = document, $d = $(d),
    w = window, $w = $(w),
    wWidth = $w.width(), wHeight = $w.height(),
    credit = $('.credit > a'),
    particles2 = $('.particles2'),
    particle2Count = 0,
    maxTime = 10,
    sizes = [
        75
    ],
    colors = [
      '#f44336', '#e91e63', '#9c27b0', '#673ab7', '#3f51b5',
      '#2196f3', '#03a9f4', '#00bcd4', '#009688', '#4CAF50',
      '#8BC34A', '#CDDC39', '#FFEB3B', '#FFC107', '#FF9800',
      '#FF5722', '#795548', '#9E9E9E', '#607D8B', '#777777'
    ],

    mouseX = $w.width() / 2, mouseY = $w.height() / 2;

function updateParticle2Count () {
  $('.particle2-count > .number').text(particle2Count);
};

$w
.on( 'resize' , function () {
  wWidth = $w.width();
  wHeight = $w.height();
});

$("p")
.on( 'mousemove touchmove' , function ( event ) {
  event.preventDefault();
  event.stopPropagation();
  mouseX = event.clientX;
  mouseY = event.clientY;
  if( !!event.originalEvent.touches ) {
    mouseX = event.originalEvent.touches[0].clientX;
    mouseY = event.originalEvent.touches[0].clientY;
  }
})
.on( 'mousedown touchstart' , function( event ) {
  if( event.target === credit.get(0) ){
    return;
  }
  mouseX = event.clientX;
  mouseY = event.clientY;
  if( !!event.originalEvent.touches ) {
    mouseX = event.originalEvent.touches[0].clientX;
    mouseY = event.originalEvent.touches[0].clientY;
  }

  var counter = 0;

   var timer = setInterval(function () {
    if (counter < maxTime) {
      createParticle2( event );
    } else {
      clearInterval( timer );
      counter = 0;
    }
    counter++;

  }, 1000 / 20);

  $("p").
  on('mouseup mouseleave touchend touchcancel touchleave', function () {
    clearInterval( timer );
  });
});

function createParticle2 ( event ) {
  var particle2 = $('
' + getSymbol() + '
'),
      size = sizes[Math.floor(Math.random() * sizes.length)],
      color = colors[Math.floor(Math.random() * colors.length)],
      negative = size/2,
      speedHorz = Math.random() * 10,
      speedUp = Math.random() * 25,
      spinVal = 360 * Math.random(),
      spinSpeed = ((12 * Math.random())) * (Math.random() <=.5 ? -1 : 1),
      otime,
      time = otime = (1 + (.5 * Math.random())) * 1000,
      top = (mouseY - negative),
      left = (mouseX - negative),
      direction = Math.random() <=.5 ? -1 : 1 ,
      life = 10;

  particle2
  .css({
    height: size + 'px',
    width: size + 'px',
    top: top + 'px',
    left: left + 'px',
    background: color,
    transform: 'rotate(' + spinVal + 'deg)',
    webkitTransform: 'rotate(' + spinVal + 'deg)'
  })
  .appendTo( particles2 );
  particle2Count++;
  updateParticle2Count();

  var particle2Timer = setInterval(function () {
    time = time - life;
    left = left - (speedHorz * direction);
    top = top - speedUp;
    speedUp = Math.min(size, speedUp - 1);
    spinVal = spinVal + spinSpeed;

    particle2
    .css({
      height: size + 'px',
      width: size + 'px',
      top: top + 'px',
      left: left + 'px',
      opacity: ((time / otime)/2) + 1.0,
      transform: 'rotate(' + spinVal + 'deg)',
      webkitTransform: 'rotate(' + spinVal + 'deg)'
    });

    if( time <= 0 || left <= -size || left >= wWidth + size || top >= wHeight + size ) {
      particle2.remove();
      particle2Count--;
      updateParticle2Count();
      clearInterval(particle2Timer);
    }
  }, 1000 / 50);
}
function getSymbol() {
  var symbols = "12X34Y5Z+x=-%";
  return symbols.charAt(Math.floor(Math.random() * symbols.length));
}

@import url('https://fonts.googleapis.com/css?family=Roboto+Slab:300');
.particle-count {
  display: block;
  text-align: center;
  margin: 25px 0;
}

.particles > .particle {
  background: #000;
  border-radius: 20%;
  position: absolute;
  background-repeat: no-repeat;
  color: white;
}

.particles > .particle.small {
  width: 10px;
  height: 10px;
}
.particles > .particle.normal {
  width: 15px;
  height: 15px;
}
.particles > .particle.big {
  width: 20px;
  height: 20px;
}
.particles > .particle.bigger {
  width: 25px;
  height: 25px;
}

.particles {
  background: #000;
  border-radius: 100%;
  position: absolute;
  background-repeat: no-repeat;
  font-family: 'Roboto Slab', serif;
  font-size: 48px;
  text-align: center;
}

/**-----------------------------------------------------------------**/
.particle2-count {
  display: block;
  text-align: center;
  margin: 25px 0;
}

.particles2 > .particle2 {
  background: #000;
  border-radius: 100%;
  position: absolute;
  background-repeat: no-repeat;
  color: white;
}

.particles2 > .particle2.small {
  width: 10px;
  height: 10px;
}
.particles2 > .particle2.normal {
  width: 15px;
  height: 15px;
}
.particles2 > .particle2.big {
  width: 20px;
  height: 20px;
}
.particles2 > .particle2.bigger {
  width: 25px;
  height: 25px;
}

.particles2 {
  background: #000;
  border-radius: 100%;
  position: absolute;
  background-repeat: no-repeat;
  font-family: 'Roboto Slab', serif;
  font-size: 48px;
  text-align: center;
}

Click for particles

I hope you guys can easily fix this
Thanks!

Body:
To make something "bounce" when it reaches the bottom of the frame you should check if it is below the bottom of the screen if so reverse the velocity of the particle, dampen its rebound velocity by multiplying it by a number less than one and set its height to be the bottom of the screen- this helps with stutter. For instance:

if (top + size > wHeight) {
  speedUp = -0.7 * speedUp; // rebounds with 0.7 times the velocity
  top = wHeight - size;
}

JSFiddle example.

Hope this helps!


来源: stackexchange

问:
Creating vector managed JNI threads [C++]
In short I've been trying to accomplish the following: I want to be able to effectively manage a lot(in the billions/they don't take long to finish, but I am creating arrays to process at a high pace, and if i don't pass stuff to the thread right away, the array gets so large it causes segfaults) of threads which pass data to JNI if necessary and need to be stored in a vector.

I've been facing two problems:

The first one is, that if I try to spawn more than around 45 threads all running JNI simultaneously, Java crashes. If they aren't running all at the same time, it works fine, but I get lots of complaints from the GC that it wasn't getting enough memory which doesn't seem to affect anything though.

The second is, that if I spawn the threads at the speed I am at the moment, the vector which I use to manage and later join them, gets too large.

So in conclusion I need a fast way to keep track of the threads I am creating without sacrificing any time pretty much.

```<code>//g++ -std=c++11 -I/usr/lib/jvm/java-8-openjdk/include -I/usr/lib/jvm/java-8-openjdk/include/linux cpptest/Test.cpp -L/usr/lib/jvm/java-8-openjdk/jre/lib/amd64/server -ljvm -lpthread
#include <jni.h>
#include <iostream>
#include <thread>
#include <string.h>
#include <vector>
#include <chrono>
#include <mutex>
#include <fstream>
#include <algorithm>

jclass cls;
jmethodID mid;
JNIEnv* env;
JavaVM* jvm;
std::mutex m;

typedef struct {
    long seed;
    int chunkX;
    int chunkZ;
    int eyes;
} Stronghold;

void ThreadFunc(Stronghold strhld, std::ofstream *outfile) {
  jvm->AttachCurrentThread((void**)&env, NULL);
  jlongArray rt = (jlongArray)env->CallStaticLongMethod(cls, mid, (jlong)strhld.seed, (jint)strhld.chunkX, (jint)strhld.chunkZ, (jint)strhld.eyes);
  jsize size = env->GetArrayLength(rt);
  std::vector<long> rtVec(size);
  env->GetLongArrayRegion(rt, 0, size, &rtVec[0]);
    jvm->DetachCurrentThread();
    std::string write;
    m.lock();
  for(long &element : rtVec) {
        write = std::to_string(element) + "; ";
    *outfile << write;
  }
    *outfile << std::endl;
    m.unlock();
}

int main(int argc, char* argv[]) {
  std::ofstream outfile("./new.txt",std::ofstream::binary);
    std::vector<std::thread> threads;

  const int kNumOptions = 3;
  JavaVMOption options[kNumOptions] = {
    { const_cast<char*>("-Xmx512m"), NULL },
    { const_cast<char*>("-verbose:gc"), NULL },
    { const_cast<char*>("-Djava.class.path=/home/jewe37/Desktop/"), NULL }
  };

  JavaVMInitArgs vm_args;
  vm_args.version = JNI_VERSION_1_8;
  vm_args.options = options;
  vm_args.nOptions = sizeof(options) / sizeof(JavaVMOption);

  env = NULL;
  jvm = NULL;
  JNI_CreateJavaVM(&jvm, reinterpret_cast<void**>(&env), &vm_args);

  const char* kClassName = "Processor";
  cls = env->FindClass(kClassName);
  if (cls == NULL) {
    std::cerr << "FINDCLASS" << std::endl;
        return 1;
    }

  const char* kMethodName = "ProcessSeed";
  mid = env->GetStaticMethodID(cls, kMethodName, "(JIII)[J");
  if (mid == NULL) {
    std::cerr << "FINDMETHOD" << std::endl;
        return 1;
    }

  Stronghold strhld;

    for(int i = 0; i < std::stoi(argv[1]); i++) {
        strhld = {i, i*2, i*3, i*4};
        threads.emplace_back(ThreadFunc, strhld, &outfile);
        std::this_thread::sleep_for(std::chrono::microseconds(50));
    }

    std::cout << threads.size() << std::endl;

    for (std::thread &thread : threads) if (thread.joinable()) thread.join();

  jvm->DestroyJavaVM();

  outfile.close();
  return 0;
}
</code>```

答:
You can always use mutex and this way make sure to access JVM by single thread only:

http://jnicookbook.owsiak.org/recipe-no-027/

ContentLicense: CC BY-SA 3.0

Body:
In short I've been trying to accomplish the following: I want to be able to effectively manage a lot(in the billions/they don't take long to finish, but I am creating arrays to process at a high pace, and if i don't pass stuff to the thread right away, the array gets so large it causes segfaults) of threads which pass data to JNI if necessary and need to be stored in a vector.

I've been facing two problems:

The first one is, that if I try to spawn more than around 45 threads all running JNI simultaneously, Java crashes. If they aren't running all at the same time, it works fine, but I get lots of complaints from the GC that it wasn't getting enough memory which doesn't seem to affect anything though.

The second is, that if I spawn the threads at the speed I am at the moment, the vector which I use to manage and later join them, gets too large.

So in conclusion I need a fast way to keep track of the threads I am creating without sacrificing any time pretty much.

//g++ -std=c++11 -I/usr/lib/jvm/java-8-openjdk/include -I/usr/lib/jvm/java-8-openjdk/include/linux cpptest/Test.cpp -L/usr/lib/jvm/java-8-openjdk/jre/lib/amd64/server -ljvm -lpthread
#include <jni.h>
#include <iostream>
#include <thread>
#include <string.h>
#include <vector>
#include <chrono>
#include <mutex>
#include <fstream>
#include <algorithm>

jclass cls;
jmethodID mid;
JNIEnv* env;
JavaVM* jvm;
std::mutex m;

typedef struct {
    long seed;
    int chunkX;
    int chunkZ;
    int eyes;
} Stronghold;

void ThreadFunc(Stronghold strhld, std::ofstream *outfile) {
  jvm->AttachCurrentThread((void**)&env, NULL);
  jlongArray rt = (jlongArray)env->CallStaticLongMethod(cls, mid, (jlong)strhld.seed, (jint)strhld.chunkX, (jint)strhld.chunkZ, (jint)strhld.eyes);
  jsize size = env->GetArrayLength(rt);
  std::vector<long> rtVec(size);
  env->GetLongArrayRegion(rt, 0, size, &rtVec[0]);
    jvm->DetachCurrentThread();
    std::string write;
    m.lock();
  for(long &element : rtVec) {
        write = std::to_string(element) + "; ";
    *outfile << write;
  }
    *outfile << std::endl;
    m.unlock();
}

int main(int argc, char* argv[]) {
  std::ofstream outfile("./new.txt",std::ofstream::binary);
    std::vector<std::thread> threads;

  const int kNumOptions = 3;
  JavaVMOption options[kNumOptions] = {
    { const_cast<char*>("-Xmx512m"), NULL },
    { const_cast<char*>("-verbose:gc"), NULL },
    { const_cast<char*>("-Djava.class.path=/home/jewe37/Desktop/"), NULL }
  };

  JavaVMInitArgs vm_args;
  vm_args.version = JNI_VERSION_1_8;
  vm_args.options = options;
  vm_args.nOptions = sizeof(options) / sizeof(JavaVMOption);

  env = NULL;
  jvm = NULL;
  JNI_CreateJavaVM(&jvm, reinterpret_cast<void**>(&env), &vm_args);

  const char* kClassName = "Processor";
  cls = env->FindClass(kClassName);
  if (cls == NULL) {
    std::cerr << "FINDCLASS" << std::endl;
        return 1;
    }

  const char* kMethodName = "ProcessSeed";
  mid = env->GetStaticMethodID(cls, kMethodName, "(JIII)[J");
  if (mid == NULL) {
    std::cerr << "FINDMETHOD" << std::endl;
        return 1;
    }

  Stronghold strhld;

    for(int i = 0; i < std::stoi(argv[1]); i++) {
        strhld = {i, i*2, i*3, i*4};
        threads.emplace_back(ThreadFunc, strhld, &outfile);
        std::this_thread::sleep_for(std::chrono::microseconds(50));
    }

    std::cout << threads.size() << std::endl;

    for (std::thread &thread : threads) if (thread.joinable()) thread.join();

  jvm->DestroyJavaVM();

  outfile.close();
  return 0;
}


问:
Calling Node.Js Rest API(POST) from Java Spring MVC
How to integrate node.js and java micro services. I'm able to call node rest api from java spring mvc but not able to post data to node api. Getting empty body in request object at node project.

FYI: Node.js(express) -REST api(POST method)
     Spring MVC -REST -api(POST method)

Java:

```<code>String url = "localhost:3010/upload";
JSONObject jsonob1=new JSONObject(); jsonob1.put("upfile", file);
jsonob1.put("ty", "ACT");
HashMap<String, String> header = getHeaderValues(uploadreq.getAuthToken(), "action");
status = getHttpClient.executePostRequest(url,jsonob1,header);
LOGGER.debug("result {}", status);
</code>```

NodeJs:

```<code>var express = require("express");
var router = express.Router();
router.post('/upload', function (req, res) { console.log(req); });
</code>```

答:
Please ignore it, its resolved by myself, Access req.body at nodejs side as following </p>

```<code>var qs = require('querystring');if(req.method=='POST') {
     var body='';
     req.on('data', function (data) {
         body +=data;
     });
     req.on('end',function(){
         var POST =  qs.parse(body);
         console.log(POST);``
     });}
</code>```

Body:
How to integrate node.js and java micro services. I'm able to call node rest api from java spring mvc but not able to post data to node api. Getting empty body in request object at node project.

FYI: Node.js(express) -REST api(POST method)
     Spring MVC -REST -api(POST method)

Java:

String url = "localhost:3010/upload";
JSONObject jsonob1=new JSONObject(); jsonob1.put("upfile", file);
jsonob1.put("ty", "ACT");
HashMap<String, String> header = getHeaderValues(uploadreq.getAuthToken(), "action");
status = getHttpClient.executePostRequest(url,jsonob1,header);
LOGGER.debug("result {}", status);

NodeJs:

var express = require("express");
var router = express.Router();
router.post('/upload', function (req, res) { console.log(req); });

Body:
Please ignore it, its resolved by myself, Access req.body at nodejs side as following

var qs = require('querystring');if(req.method=='POST') {
     var body='';
     req.on('data', function (data) {
         body +=data;
     });
     req.on('end',function(){
         var POST =  qs.parse(body);
         console.log(POST);``
     });}


问:
Key Value Pair in C Language
I am new to C programming and I am trying to create a key value structure as in Perl Programming. I saw one solution like :-

```<code>struct key_value
{
   int key;
   char* value;
};

struct key_value kv;

kv.key = 1;
kv.value = "foo";
</code>```

But I don't know how to access these values from this structure. Can someone enlight on this ?

答:
The functionality you are looking for needs your own implementation in C; e.g. an array of your struct-type.

Here is an example of how to read the value for a key, without knowing anything about at which array-index the key will be found.

I have the keys numbered backward in order to illustrate that.

Note that more sophisticated API definitions are needed for special cases such as non-existing key; I just blindly return the last entry to keep things easy here.

```<code>#include <stdio.h>

#define MAPSIZE 30

struct key_value
{
   int key;
   char* value;
};

struct key_value kvmap[MAPSIZE];

void initmap(void)
{
    int i;
    for(i=0; i<MAPSIZE; i++)
    {
         kvmap[i].key=MAPSIZE-i-1;
         kvmap[i].value="unset";
    }

    kvmap[0].value="zero";
    kvmap[1].value="one";
    kvmap[2].value="two";
    kvmap[3].value="three";
    kvmap[4].value="four";
    kvmap[5].value="five";
    kvmap[6].value="six";
    kvmap[7].value="seven";
    kvmap[8].value="eight";
    kvmap[24].value="find this"; // it has the key "5"

}

char* readmap(int key)
{
    int i=0;
    while ((i<MAPSIZE-1) && (kvmap[i].key!=key))
    {   printf("Not in %d\n", i);
        ++i;}

    // will return last entry if key is not present
    return kvmap[i].value;
}

int main(void)
{
    initmap();

    printf("%s\n", readmap(5));
    return 0;
}
</code>```

Title: Key Value Pair in C Language

Body:
I am new to C programming and I am trying to create a key value structure as in Perl Programming. I saw one solution like :-

struct key_value
{
   int key;
   char* value;
};

struct key_value kv;

kv.key = 1;
kv.value = "foo";

But I don't know how to access these values from this structure. Can someone enlight on this ?

Body:
The functionality you are looking for needs your own implementation in C; e.g. an array of your struct-type.

Here is an example of how to read the value for a key, without knowing anything about at which array-index the key will be found.

I have the keys numbered backward in order to illustrate that.

Note that more sophisticated API definitions are needed for special cases such as non-existing key; I just blindly return the last entry to keep things easy here.

#include <stdio.h>

#define MAPSIZE 30

struct key_value
{
   int key;
   char* value;
};

struct key_value kvmap[MAPSIZE];

void initmap(void)
{
    int i;
    for(i=0; i<MAPSIZE; i++)
    {
         kvmap[i].key=MAPSIZE-i-1;
         kvmap[i].value="unset";
    }

    kvmap[0].value="zero";
    kvmap[1].value="one";
    kvmap[2].value="two";
    kvmap[3].value="three";
    kvmap[4].value="four";
    kvmap[5].value="five";
    kvmap[6].value="six";
    kvmap[7].value="seven";
    kvmap[8].value="eight";
    kvmap[24].value="find this"; // it has the key "5"

}

char* readmap(int key)
{
    int i=0;
    while ((i<MAPSIZE-1) && (kvmap[i].key!=key))
    {   printf("Not in %d\n", i);
        ++i;}

    // will return last entry if key is not present
    return kvmap[i].value;
}

int main(void)
{
    initmap();

    printf("%s\n", readmap(5));
    return 0;
}


问:
PHP range() function in .NET?
I need to generate a list of sequential numbers.  I know Ruby you can do 1..10 or PHP you can do range(1, 10).  Anything like that in .Net already, or do I have to write it?   Thanks.</p>

答:
In C# (with .NET 3.0 or higher) this should do the job:</p>

```<code>IEnumerable<int> myRange = Enumerable.Range(1, 10);
</code>```

OwnerDisplayName: Kevin

ContentLicense: CC BY-SA 2.5

Title: PHP range() function in .NET?

Body:
In C# (with .NET 3.0 or higher) this should do the job:

IEnumerable<int> myRange = Enumerable.Range(1, 10);


问:
converting date format
I got date as '14-Dec-2010' i want to get the month in number format for the given date.
that is., i want to convert the date to '14-12-2010'.

答:
I think this SQL convert should work

SELECT CONVERT(datetime,'14-Dec-2010',105)

Title: converting date format


问:
how to get data of contact us form in our email
I have created one contact us activity in my android application. It contain 4 edit text such as name, phone number, email and message along with the submit button. What i have to do is when i will click on submit button then the data from all four edit text should be E-mailed to me on my mail id. Can anyone suggest how can i do so? If any further details are required then please let me know.
Thanks
Here is some code sample.

```<code>                String Name = name.getText().toString();
                String Phone = phone.getText().toString();
                String Email = email.getText().toString();
                String Message = message.getText().toString();

                //check whether the msg empty or not
                if (Name.length() != 0 && Phone.length() != 0 && Email.length() != 0) {
                    HttpClient httpclient = new DefaultHttpClient();
                    HttpPost httppost = new HttpPost("http://www.abcd.com/Server1.php");

                    try {
                        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                        nameValuePairs.add(new BasicNameValuePair("id", "01"));
                        nameValuePairs.add(new BasicNameValuePair("message", Name));

                        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                        httpclient.execute(httppost);
                        name.setText(""); //reset the message text field
                        phone.setText(""); //reset the message text field
                        email.setText(""); //reset the message text field
                        message.setText(""); //reset the message text field
                        Toast.makeText(getBaseContext(), "Sent", Toast.LENGTH_SHORT).show();
                    } catch (ClientProtocolException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else {
                    //display message if text field is empty
                    Toast.makeText(getBaseContext(), "All fields are required", Toast.LENGTH_SHORT).show();
                }
            }
</code>```

I have written this code. It is not giving any error. App is also not crashing but the data is not getting on email. Any Help?

```<code>public class ContactUs extends AppCompatActivity {
private EditText name, phone, email, msg;
private Button submitButton;
private TextInputLayout inputLayoutName, inputLayoutPhone, inputLayoutEmail, inputLayoutMessage;

EditText editText;

//New Code
Session session = null;
ProgressDialog pdialog = null;
Context context = null;
//private EditText name, phone, email, message;
String Name, Phone, Email, Msg;
String receiver = "xyz@gmail.com";
String sender = "abc@gmail.com";
String subject = "Test Mail";
String textMessage = "Hello To All";
String Data;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_contact_us);

    initializeWidgets();

    submitButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            boolean isValid = true;
            if (name.getText().toString().isEmpty()) {
                inputLayoutName.setError("Name is mandatory");
                isValid = false;
            } else {
                inputLayoutName.setErrorEnabled(false);
            }

            if (phone.getText().toString().isEmpty()) {
                inputLayoutPhone.setError("Phone number is mandatory");
                isValid = false;
            } else {
                inputLayoutPhone.setErrorEnabled(false);
            }

            if (email.getText().toString().isEmpty()) {
                inputLayoutEmail.setError("Email is required");
                isValid = false;
            } else {
                inputLayoutEmail.setErrorEnabled(false);
            }

            if (isValid) {
                                String Name = name.getText().toString();
                String Phone = phone.getText().toString();
                String Email = email.getText().toString();
                String Message = msg.getText().toString();

                Data = Name + Phone + Email + Message;

                Properties prop = new Properties();
                prop.put("mail.smtp.host", "smtp.gmail.com");
                prop.put("mail.smtp.socketFactory.port", "587");
                prop.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
                prop.put("mail.smtp.auth", "true");
                prop.put("mail.smtp.port", "587");

                session = Session.getDefaultInstance(prop, new Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        PasswordAuthentication passwordAuthentication = new PasswordAuthentication(sender, "abc");
                        return passwordAuthentication;
                    } });

                try {
                    MimeMessage message = new MimeMessage(session);
                    message.setFrom(new InternetAddress(sender));
                    message.setRecipients(MimeMessage.RecipientType.TO, InternetAddress.parse(receiver));
                    message.setText(Data);
                    Transport.send(message);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
            name.setText("");
            phone.setText("");
            email.setText("");
            msg.setText("");
            Toast.makeText(getApplicationContext(), "Data Submitted Successfully", Toast.LENGTH_LONG).show();
        }

    });
}

private void initializeWidgets() {

    name = (EditText) findViewById(R.id.name);
    phone = (EditText) findViewById(R.id.phone);
    email = (EditText) findViewById(R.id.email);
    msg = (EditText) findViewById(R.id.message);
    submitButton = (Button) findViewById(R.id.btnSubmit);
    inputLayoutName = (TextInputLayout) findViewById(R.id.inputLayoutName);
    inputLayoutPhone = (TextInputLayout) findViewById(R.id.inputLayoutPhone);
    inputLayoutEmail = (TextInputLayout) findViewById(R.id.inputLayoutEmail);
    inputLayoutMessage = (TextInputLayout) findViewById(R.id.inputLayoutMessage);

}

public boolean onSupportNavigateUp() {
    onBackPressed();`enter code here`
    return true;
}
</code>```

答:
Here you can find a solution for sending email with intent (user action required).

You have to create a String with email body containing all data you want to send, then the Email client is opened and the user can manually send the message.

Otherwise you can use your smtp configuration sending an email in background, without user action as explained here.
This way the email is sent without user knowledge, but you have to know configuration of your Email account.

Following for Gmail (copied from here):

```<code>import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.Security;
import java.util.Properties;

public class GMailSender extends javax.mail.Authenticator {
    private String mailhost = "smtp.gmail.com";
    private String user;
    private String password;
    private Session session;

    static {
        Security.addProvider(new com.provider.JSSEProvider());
    }

    public GMailSender(String user, String password) {
        this.user = user;
        this.password = password;

        Properties props = new Properties();
        props.setProperty("mail.transport.protocol", "smtp");
        props.setProperty("mail.host", mailhost);
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", "465");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactory.class",
                "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.fallback", "false");
        props.setProperty("mail.smtp.quitwait", "false");

        session = Session.getDefaultInstance(props, this);
    }

    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(user, password);
    }

    public synchronized void sendMail(String subject, String body, String sender, String recipients) throws Exception {
        try{
        MimeMessage message = new MimeMessage(session);
        DataHandler handler = new DataHandler(new ByteArrayDataSource(body.getBytes(), "text/plain"));
        message.setSender(new InternetAddress(sender));
        message.setSubject(subject);
        message.setDataHandler(handler);
        if (recipients.indexOf(',') > 0)
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
        else
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
        Transport.send(message);
        }catch(Exception e){

        }
    }

    public class ByteArrayDataSource implements DataSource {
        private byte[] data;
        private String type;

        public ByteArrayDataSource(byte[] data, String type) {
            super();
            this.data = data;
            this.type = type;
        }

        public ByteArrayDataSource(byte[] data) {
            super();
            this.data = data;
        }

        public void setType(String type) {
            this.type = type;
        }

        public String getContentType() {
            if (type == null)
                return "application/octet-stream";
            else
                return type;
        }

        public InputStream getInputStream() throws IOException {
            return new ByteArrayInputStream(data);
        }

        public String getName() {
            return "ByteArrayDataSource";
        }

        public OutputStream getOutputStream() throws IOException {
            throw new IOException("Not Supported");
        }
    }
}
</code>```

Body:
I have created one contact us activity in my android application. It contain 4 edit text such as name, phone number, email and message along with the submit button. What i have to do is when i will click on submit button then the data from all four edit text should be E-mailed to me on my mail id. Can anyone suggest how can i do so? If any further details are required then please let me know.
Thanks
Here is some code sample.

                String Name = name.getText().toString();
                String Phone = phone.getText().toString();
                String Email = email.getText().toString();
                String Message = message.getText().toString();

                //check whether the msg empty or not
                if (Name.length() != 0 && Phone.length() != 0 && Email.length() != 0) {
                    HttpClient httpclient = new DefaultHttpClient();
                    HttpPost httppost = new HttpPost("http://www.abcd.com/Server1.php");

                    try {
                        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                        nameValuePairs.add(new BasicNameValuePair("id", "01"));
                        nameValuePairs.add(new BasicNameValuePair("message", Name));

                        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                        httpclient.execute(httppost);
                        name.setText(""); //reset the message text field
                        phone.setText(""); //reset the message text field
                        email.setText(""); //reset the message text field
                        message.setText(""); //reset the message text field
                        Toast.makeText(getBaseContext(), "Sent", Toast.LENGTH_SHORT).show();
                    } catch (ClientProtocolException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else {
                    //display message if text field is empty
                    Toast.makeText(getBaseContext(), "All fields are required", Toast.LENGTH_SHORT).show();
                }
            }

I have written this code. It is not giving any error. App is also not crashing but the data is not getting on email. Any Help?

public class ContactUs extends AppCompatActivity {
private EditText name, phone, email, msg;
private Button submitButton;
private TextInputLayout inputLayoutName, inputLayoutPhone, inputLayoutEmail, inputLayoutMessage;

EditText editText;

//New Code
Session session = null;
ProgressDialog pdialog = null;
Context context = null;
//private EditText name, phone, email, message;
String Name, Phone, Email, Msg;
String receiver = "xyz@gmail.com";
String sender = "abc@gmail.com";
String subject = "Test Mail";
String textMessage = "Hello To All";
String Data;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_contact_us);

    initializeWidgets();

    submitButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            boolean isValid = true;
            if (name.getText().toString().isEmpty()) {
                inputLayoutName.setError("Name is mandatory");
                isValid = false;
            } else {
                inputLayoutName.setErrorEnabled(false);
            }

            if (phone.getText().toString().isEmpty()) {
                inputLayoutPhone.setError("Phone number is mandatory");
                isValid = false;
            } else {
                inputLayoutPhone.setErrorEnabled(false);
            }

            if (email.getText().toString().isEmpty()) {
                inputLayoutEmail.setError("Email is required");
                isValid = false;
            } else {
                inputLayoutEmail.setErrorEnabled(false);
            }

            if (isValid) {
                                String Name = name.getText().toString();
                String Phone = phone.getText().toString();
                String Email = email.getText().toString();
                String Message = msg.getText().toString();

                Data = Name + Phone + Email + Message;

                Properties prop = new Properties();
                prop.put("mail.smtp.host", "smtp.gmail.com");
                prop.put("mail.smtp.socketFactory.port", "587");
                prop.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
                prop.put("mail.smtp.auth", "true");
                prop.put("mail.smtp.port", "587");

                session = Session.getDefaultInstance(prop, new Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        PasswordAuthentication passwordAuthentication = new PasswordAuthentication(sender, "abc");
                        return passwordAuthentication;
                    } });

                try {
                    MimeMessage message = new MimeMessage(session);
                    message.setFrom(new InternetAddress(sender));
                    message.setRecipients(MimeMessage.RecipientType.TO, InternetAddress.parse(receiver));
                    message.setText(Data);
                    Transport.send(message);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
            name.setText("");
            phone.setText("");
            email.setText("");
            msg.setText("");
            Toast.makeText(getApplicationContext(), "Data Submitted Successfully", Toast.LENGTH_LONG).show();
        }

    });
}

private void initializeWidgets() {

    name = (EditText) findViewById(R.id.name);
    phone = (EditText) findViewById(R.id.phone);
    email = (EditText) findViewById(R.id.email);
    msg = (EditText) findViewById(R.id.message);
    submitButton = (Button) findViewById(R.id.btnSubmit);
    inputLayoutName = (TextInputLayout) findViewById(R.id.inputLayoutName);
    inputLayoutPhone = (TextInputLayout) findViewById(R.id.inputLayoutPhone);
    inputLayoutEmail = (TextInputLayout) findViewById(R.id.inputLayoutEmail);
    inputLayoutMessage = (TextInputLayout) findViewById(R.id.inputLayoutMessage);

}

public boolean onSupportNavigateUp() {
    onBackPressed();`enter code here`
    return true;
}

Body:
Here you can find a solution for sending email with intent (user action required).

You have to create a String with email body containing all data you want to send, then the Email client is opened and the user can manually send the message.

Otherwise you can use your smtp configuration sending an email in background, without user action as explained here.
This way the email is sent without user knowledge, but you have to know configuration of your Email account.

Following for Gmail (copied from here):

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.Security;
import java.util.Properties;

public class GMailSender extends javax.mail.Authenticator {
    private String mailhost = "smtp.gmail.com";
    private String user;
    private String password;
    private Session session;

    static {
        Security.addProvider(new com.provider.JSSEProvider());
    }

    public GMailSender(String user, String password) {
        this.user = user;
        this.password = password;

        Properties props = new Properties();
        props.setProperty("mail.transport.protocol", "smtp");
        props.setProperty("mail.host", mailhost);
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", "465");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactory.class",
                "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.fallback", "false");
        props.setProperty("mail.smtp.quitwait", "false");

        session = Session.getDefaultInstance(props, this);
    }

    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(user, password);
    }

    public synchronized void sendMail(String subject, String body, String sender, String recipients) throws Exception {
        try{
        MimeMessage message = new MimeMessage(session);
        DataHandler handler = new DataHandler(new ByteArrayDataSource(body.getBytes(), "text/plain"));
        message.setSender(new InternetAddress(sender));
        message.setSubject(subject);
        message.setDataHandler(handler);
        if (recipients.indexOf(',') > 0)
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
        else
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
        Transport.send(message);
        }catch(Exception e){

        }
    }

    public class ByteArrayDataSource implements DataSource {
        private byte[] data;
        private String type;

        public ByteArrayDataSource(byte[] data, String type) {
            super();
            this.data = data;
            this.type = type;
        }

        public ByteArrayDataSource(byte[] data) {
            super();
            this.data = data;
        }

        public void setType(String type) {
            this.type = type;
        }

        public String getContentType() {
            if (type == null)
                return "application/octet-stream";
            else
                return type;
        }

        public InputStream getInputStream() throws IOException {
            return new ByteArrayInputStream(data);
        }

        public String getName() {
            return "ByteArrayDataSource";
        }

        public OutputStream getOutputStream() throws IOException {
            throw new IOException("Not Supported");
        }
    }
}


问:
SSH to Vagrant box in Windows?
I'm using Vagrant to start a VirtualBox VM in windows.
In other platforms, I can just

```<code>$ vagrant ssh
</code>```

to connect to the VM.

How do i connect to this Vagrant box in windows?

The way suggested in Vagrant documentation to use PuTTy also did not work:

http://docs-v1.vagrantup.com/v1/docs/getting-started/ssh.html

答:
Another solution here but only for the virtual box of windows 10 to test explorer.
ssh user: IEUser
ssh pass:Passw0rd!</p>

Title: SSH to Vagrant box in Windows?

Body:
I'm using Vagrant to start a VirtualBox VM in windows.
In other platforms, I can just

$ vagrant ssh

to connect to the VM.

How do i connect to this Vagrant box in windows?

The way suggested in Vagrant documentation to use PuTTy also did not work:

http://docs-v1.vagrantup.com/v1/docs/getting-started/ssh.html


问:
ngIf in angular 2 not working
```<code><div *ngFor="let message of messages">
  <div *ngIf="message.user===user">

  </div>

 <input [(ngModel)]="message"  />
<button (click)="sendMessage()">Send</button>
</code>```

Here user is the variable that I have assigned in the component. That is a string value 'user1'. If message.user === user1 then I need to show something but its not working.

答:
I have provided some demo ..since u failed to add your .ts file just go through this:
https://angular.io/docs/ts/latest/api/common/index/NgIf-directive.html</p>

Title: ngIf in angular 2 not working

Body:
 <input [(ngModel)]="message"  />
<button (click)="sendMessage()">Send</button>

Here user is the variable that I have assigned in the component. That is a string value 'user1'. If message.user === user1 then I need to show something but its not working.


问:
How to retrieve the currently logged in user role name in textbox using vb.net?
How to retrieve the currently logged in user role name in textbox using vb.net ?

iam currently using

```<code>TextBox1.Text = Roles.GetRolesForUser(User.Identity.Name)
</code>```

om page load event but it is highlighted by a blue line in visual studio 2008

答:
Use System.Web.Security.Roles class:

C#:

```<code>String[] roles = System.Web.Security.Roles.GetRolesForUser();
</code>```

VB:

```<code>Dim roles As String() = System.Web.Security.Roles.GetRolesForUser()
</code>```

Body:
How to retrieve the currently logged in user role name in textbox using vb.net ?

iam currently using

TextBox1.Text = Roles.GetRolesForUser(User.Identity.Name)

om page load event but it is highlighted by a blue line in visual studio 2008

Body:
Use System.Web.Security.Roles class:

C#:

String[] roles = System.Web.Security.Roles.GetRolesForUser();

VB:

Dim roles As String() = System.Web.Security.Roles.GetRolesForUser()


问:
Dynamic initialization of 2d array in c++ in a specific way
if we initialize a 2d array in c++ like:

```<code>    int n;
    cin>>n;
    int a[n][1000]= {0};
</code>```

why does it compile but not work properly? I tried to access   a[4][2] which gave me 2 while it should give me 0  while in case of:

```<code>    int n;
    cin>>n; int a[n]= {0};
</code>```

it works absolutely fine. Used a gcc c++14 compiler

答:
why does it compile

The program is ill-formed. However, some compiler support variable length arrays as a language extension and so would allow both of the example programs that you show.

why ... but not work properly?

I suspect that you expected that the program would behave differently than it did behave. Why it would behave differently depends on what you expected. Or perhaps you tried to create a larger array than fits on the stack.

Body:
if we initialize a 2d array in c++ like:

    int n;
    cin>>n;
    int a[n][1000]= {0};

why does it compile but not work properly? I tried to access   a[4][2] which gave me 2 while it should give me 0  while in case of:

    int n;
    cin>>n; int a[n]= {0};

it works absolutely fine. Used a gcc c++14 compiler


问:
How am I able to move my
 to where I want it?
How can I move my menu
 to the bottom left in this div?

Codepen: https://codepen.io/audn/pen/QgwvNq

I've tried margin-left:auto, but didn't seem to work.
Is it because of my padding?

HTML:

.verified{
  font-size:5px;
}
ul.media {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  margin-left: auto;
  background-color: #111019;
}
li.media {
  float: left;
}
li.media a {
  display: block;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}
li.media a:hover {
  background-color: #111019;
}
.content-selfmade{
  width: 250px;
  background-color: #111019;
  padding: 15px 15px;
  float:left;
  color: white;
  margin-left: auto;
  margin-right: auto;
  border-radius: .2em;
  margin-bottom: 10px;
  margin-left: 10px;
  height: 120px;
}
.tooltip {
  position: relative;
  display: inline-block;
  border-bottom: 1px dotted black;
}
.staff-verified{
  color: #e58900;
}
.lightPill{
  color:white;
  background-color:#e58900;
  padding:.1em .35em;
  border-radius:1px;
  font-size:.75em;
}
.tooltip .tooltiptext {
  visibility: hidden;
  width: 120px;
  background-color: black;
  color: #fff;
  text-align: center;
  border-radius: 6px;
  padding: 5px 0;
  /* Position the tooltip */
  position: absolute;
  z-index: 1;
}
.btn-team {
  border: 1px solid #e58900;
  border-radius: 5px;
  font-family: Arial;
  float:left;
  margin-top: 10px;
  color: #ffffff;
  font-size: 12px;
  padding: 5px 15px 5px 15px;
  text-decoration: none;
}

.btn-team:hover {
  cursor: pointer;
  border: 1px solid #7c4b01;
  text-decoration: none;
  float:left;
}

.tooltip:hover .tooltiptext {
  visibility: visible;
}
.h2{
  font-size: 11px;
}
#steam-photo{
  background-image: url('http://i.imgur.com/fkue1Ww.png');
  border-radius: 50%;
  width: 75px;
  height: 75px;
}
#team-members{
  width: 25px;
  height:25px;
  border-radius: 50%;
  float:left;
  margin-left: 5px;
  margin-top: 5px;
}
.content-selfmade-name{
  top: 0;
  display: block;
  font-size:  1rem;
  float: right;
  width: 140px;
  margin-top: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <div class="content-selfmade">
    <img id="steam-photo" src="http://i.imgur.com/fkue1Ww.png"></span>
    <span class="content-selfmade-name">Audn
      <font style="color:#0288D1;";>

          <div class="tooltip">
            <i class="fa fa-check-circle" aria-hidden="true"></i>
              <span class="tooltiptext">Verified Staff member.</span>
          </div>

      </font>
      <div class="h2">
        <span class="staff-verified">PUBG.team developer.</span>
      </div>
    <img id="team-members" src="https://cdn.discordapp.com/attachments/301429296390602752/321126144193593345/yggdrasil128.png">
    <img id="team-members" src="http://i.imgur.com/9Ix1SKa.jpg">
    <img id="team-members" src="http://i.imgur.com/RsOTLvl.png">
    <p>
  </span>
  <ul class="media">
    <li class="media">Stats</li>
    <li class="media">Steam</li>
  </ul>
</div></code>```

答:
Remove the meaningless
 tag and your menu will pop into place.

Updated codepen: https://codepen.io/audn/pen/QgwvNq

Title: How am I able to move my <ul> to where I want it?

Body:
How can I move my menu
 to the bottom left in this div?

Codepen: https://codepen.io/audn/pen/QgwvNq

I've tried margin-left:auto, but didn't seem to work.
Is it because of my padding?

HTML:

.verified{
  font-size:5px;
}
ul.media {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  margin-left: auto;
  background-color: #111019;
}
li.media {
  float: left;
}
li.media a {
  display: block;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}
li.media a:hover {
  background-color: #111019;
}
.content-selfmade{
  width: 250px;
  background-color: #111019;
  padding: 15px 15px;
  float:left;
  color: white;
  margin-left: auto;
  margin-right: auto;
  border-radius: .2em;
  margin-bottom: 10px;
  margin-left: 10px;
  height: 120px;
}
.tooltip {
  position: relative;
  display: inline-block;
  border-bottom: 1px dotted black;
}
.staff-verified{
  color: #e58900;
}
.lightPill{
  color:white;
  background-color:#e58900;
  padding:.1em .35em;
  border-radius:1px;
  font-size:.75em;
}
.tooltip .tooltiptext {
  visibility: hidden;
  width: 120px;
  background-color: black;
  color: #fff;
  text-align: center;
  border-radius: 6px;
  padding: 5px 0;
  /* Position the tooltip */
  position: absolute;
  z-index: 1;
}
.btn-team {
  border: 1px solid #e58900;
  border-radius: 5px;
  font-family: Arial;
  float:left;
  margin-top: 10px;
  color: #ffffff;
  font-size: 12px;
  padding: 5px 15px 5px 15px;
  text-decoration: none;
}

.btn-team:hover {
  cursor: pointer;
  border: 1px solid #7c4b01;
  text-decoration: none;
  float:left;
}

.tooltip:hover .tooltiptext {
  visibility: visible;
}
.h2{
  font-size: 11px;
}
#steam-photo{
  background-image: url('http://i.imgur.com/fkue1Ww.png');
  border-radius: 50%;
  width: 75px;
  height: 75px;
}
#team-members{
  width: 25px;
  height:25px;
  border-radius: 50%;
  float:left;
  margin-left: 5px;
  margin-top: 5px;
}
.content-selfmade-name{
  top: 0;
  display: block;
  font-size:  1rem;
  float: right;
  width: 140px;
  margin-top: 10px;
}

    Audn

              Verified Staff member.

        PUBG.team developer.

Stats

Steam

Body:
Remove the meaningless <p> tag and your menu will pop into place.

Updated codepen: https://codepen.io/audn/pen/QgwvNq


问:
Replace a char in the string with HTML element
I'm getting system logs from the server and feeding them to my widget which appends new logs to the log-container element. Logs look like this:

```<code>2017-06-0512:11:53.066|error[61f4cdd07abb]sequential(sequential)|interval(0)Error:...
</code>```

I'm appending with jquery like this:

```<code> returnElement.append('<span class="message">' + log.message + '  </span><br>');
</code>```

However, I would like to style these pipe symbols which act like delimiters in the logs |

Whats the best way to do this? Will probably have to wrap them with another span but I would like to avoid substringing each log.

答:
You can do it with a RegExp, e.g.: msg.replace(/(\|)/g, '$1')

var msg = '2017-06-0512:11:53.066|error[61f4cdd07abb]sequential(sequential)|interval(0)Error:...';

document.write('' + msg.replace(/(\|)/g, '$1') + '');```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.delimiter {
  font-weight: bold;
  color: green;
  font-size: 16pt;
  margin: 10px;
}</code>```

Body:
I'm getting system logs from the server and feeding them to my widget which appends new logs to the log-container element. Logs look like this:

2017-06-0512:11:53.066|error[61f4cdd07abb]sequential(sequential)|interval(0)Error:...

I'm appending with jquery like this:

 returnElement.append('' + log.message + '
');

However, I would like to style these pipe symbols which act like delimiters in the logs |

Whats the best way to do this? Will probably have to wrap them with another span but I would like to avoid substringing each log.

Body:
You can do it with a RegExp, e.g.: msg.replace(/(\|)/g, '<span class="delimiter">$1</span>')

var msg = '2017-06-0512:11:53.066|error[61f4cdd07abb]sequential(sequential)|interval(0)Error:...';

document.write('<span>' + msg.replace(/(\|)/g, '<span class="delimiter">$1</span>') + '</span>');

.delimiter {
  font-weight: bold;
  color: green;
  font-size: 16pt;
  margin: 10px;
}


问:
Error in SPD 2013
Anybody use SharePoint Designer 2013 with SharePoint 2016?
When  open site SP 2016 in SPD 2013 and try to see list and libraries
I see that error:

There are not items to show in this view

答:
Problem is solved.
In site was library with reports, that was created in SSRS 2014.
SPD display all list\libraries after deleted thih item from site content.</p>

Title: Error in SPD 2013


问:
How to pass image, from uiimagepickercontroller, into another scene's uiimageview
How do I save a UIImagePickerController camera image so I can send to CreateViewController scene's UIImageView?

HomeViewController(scene 1) has a button that loads UIImagePickerController and returns with an image from the camera. CreateViewController(scene 2) has an empty UIImageView.

HomeViewController.h

```<code>#import "CreateViewController.h"

@interface HomeViewController : UIViewController
<UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@property (strong, nonatomic) UIImagePickerController *imagePicker;
@property(nonatomic, retain) UIImage *myImage;

- (IBAction)cameraImage:(id)sender;
</code>```

HomeViewController.m

```<code>@implementation HomeViewController
@synthesize imagePicker, myImage;

-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

if ( [segue.identifier isEqualToString:@"create"]) {
    CreateViewController *cvc = [segue destinationViewController];
    UIImage *image = myImage;
    cvc.myImage = image;

}
}

//Camera button action
- (IBAction)cameraImage:(id)sender{
//UIImagePickerController space in memory
imagePicker = [[UIImagePickerController alloc]init];
//Set the delegate
imagePicker.delegate = self;
//Set the sourceType
imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
//Show Image Picker UI
[self presentViewController:imagePicker animated:YES completion:^{}];
}

-(void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:    (NSDictionary *)info {

self.myImage = [info objectForKey:UIImagePickerControllerOriginalImage];

[self dismissViewControllerAnimated:YES completion:^{}];

[self performSegueWithIdentifier:@"create" sender:self];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
[self dismissViewControllerAnimated:YES completion:^{}];
}
</code>```

CreateViewController.h

```<code>@property (strong, nonatomic) IBOutlet UIImageView *bgImage;
@property(nonatomic, retain) UIImage *myImage;
</code>```

CreateViewController.m

```<code>@implementation CreateViewController
@synthesize bgImage, myImage;

- (void)viewDidLoad
{
[super viewDidLoad];
UIImage *image = myImage;
[bgImage setImage:image];
}
</code>```

Download sample code here; http://code-blind.com/ios6-camera-picture-to-another-scenes-uiimageview/

答:
in this code:</p>

```<code>    - (void)imagePickerController:(UIImagePickerController *)picker

      didFinishPickingMediaWithInfo:(NSDictionary *)info
     {
UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];

 if( i ==1)
 {

     [self dismissViewControllerAnimated:YES completion:^
      {
          Second_ViewController*secondview=[[UIStoryboard storyboardWithName:@"Main" bundle:nil]instantiateViewControllerWithIdentifier:@"Second_ViewController"];
          secondview.bb_image=image;
          [[NSUserDefaults standardUserDefaults ]setInteger:0 forKey:@"123"];

          [[self navigationController] pushViewController:secondview animated:YES];

      }];
 }
</code>```

Body:
How do I save a UIImagePickerController camera image so I can send to CreateViewController scene's UIImageView?

HomeViewController(scene 1) has a button that loads UIImagePickerController and returns with an image from the camera. CreateViewController(scene 2) has an empty UIImageView.

HomeViewController.h

#import "CreateViewController.h"

@interface HomeViewController : UIViewController
<UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@property (strong, nonatomic) UIImagePickerController *imagePicker;
@property(nonatomic, retain) UIImage *myImage;

- (IBAction)cameraImage:(id)sender;

HomeViewController.m

@implementation HomeViewController
@synthesize imagePicker, myImage;

-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

if ( [segue.identifier isEqualToString:@"create"]) {
    CreateViewController *cvc = [segue destinationViewController];
    UIImage *image = myImage;
    cvc.myImage = image;

}
}

//Camera button action
- (IBAction)cameraImage:(id)sender{
//UIImagePickerController space in memory
imagePicker = [[UIImagePickerController alloc]init];
//Set the delegate
imagePicker.delegate = self;
//Set the sourceType
imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
//Show Image Picker UI
[self presentViewController:imagePicker animated:YES completion:^{}];
}

-(void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:    (NSDictionary *)info {

self.myImage = [info objectForKey:UIImagePickerControllerOriginalImage];

[self dismissViewControllerAnimated:YES completion:^{}];

[self performSegueWithIdentifier:@"create" sender:self];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
[self dismissViewControllerAnimated:YES completion:^{}];
}

CreateViewController.h

@property (strong, nonatomic) IBOutlet UIImageView *bgImage;
@property(nonatomic, retain) UIImage *myImage;

CreateViewController.m

@implementation CreateViewController
@synthesize bgImage, myImage;

- (void)viewDidLoad
{
[super viewDidLoad];
UIImage *image = myImage;
[bgImage setImage:image];
}

Download sample code here; http://code-blind.com/ios6-camera-picture-to-another-scenes-uiimageview/

Body:
in this code:

    - (void)imagePickerController:(UIImagePickerController *)picker

      didFinishPickingMediaWithInfo:(NSDictionary *)info
     {
UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];

 if( i ==1)
 {

     [self dismissViewControllerAnimated:YES completion:^
      {
          Second_ViewController*secondview=[[UIStoryboard storyboardWithName:@"Main" bundle:nil]instantiateViewControllerWithIdentifier:@"Second_ViewController"];
          secondview.bb_image=image;
          [[NSUserDefaults standardUserDefaults ]setInteger:0 forKey:@"123"];

          [[self navigationController] pushViewController:secondview animated:YES];

      }];
 }


问:
First and last value of window function in one row in PostgreSQL
I'd like to have first value of one column and last value of second column in one row for a specified partition. For that I created this query:

```<code>SELECT DISTINCT
b.machine_id,
batch,
timestamp_sta,
timestamp_stp,
FIRST_VALUE(timestamp_sta) OVER w AS batch_start,
LAST_VALUE(timestamp_stp) OVER w AS batch_end
FROM db_data.sta_stp AS a
JOIN db_data.ll_lu AS b
ON a.ll_lu_id=b.id
WINDOW w AS (PARTITION BY batch, machine_id ORDER BY timestamp_sta)
ORDER BY timestamp_sta, batch, machine_id;
</code>```

But as you can see in the image, returned data in batch_end column are not correct.

batch_start column has correct first value of timestamp_sta column. However batch_end should be "2012-09-17 10:49:45" and it equals timestamp_stp from same row.

Why is it so?

答:
From syntax documentation:

The frame_clause specifies the set of rows constituting the window frame, which is a subset of the current partition, for those window functions that act on the frame instead of the whole partition. The frame can be specified in either RANGE or ROWS mode; in either case, it runs from the frame_start to the frame_end. If frame_end is omitted, it defaults to CURRENT ROW.

A frame_start of UNBOUNDED PRECEDING means that the frame starts with the first row of the partition, and similarly a frame_end of UNBOUNDED FOLLOWING means that the frame ends with the last row of the partition.

and function list

last_value(value any)     returns value evaluated at the row that is the last row of the window frame

So correct SQL should be:

```<code>SELECT DISTINCT
b.machine_id,
batch,
timestamp_sta,
timestamp_stp,
FIRST_VALUE(timestamp_sta) OVER w AS batch_start,
LAST_VALUE(timestamp_stp) OVER w AS batch_end
FROM db_data.sta_stp AS a
JOIN db_data.ll_lu AS b
ON a.ll_lu_id=b.id
WINDOW w AS (PARTITION BY batch, machine_id ORDER BY timestamp_sta range between unbounded preceding and unbounded following)
ORDER BY timestamp_sta, batch, machine_id;
</code>```

Body:
I'd like to have first value of one column and last value of second column in one row for a specified partition. For that I created this query:

SELECT DISTINCT
b.machine_id,
batch,
timestamp_sta,
timestamp_stp,
FIRST_VALUE(timestamp_sta) OVER w AS batch_start,
LAST_VALUE(timestamp_stp) OVER w AS batch_end
FROM db_data.sta_stp AS a
JOIN db_data.ll_lu AS b
ON a.ll_lu_id=b.id
WINDOW w AS (PARTITION BY batch, machine_id ORDER BY timestamp_sta)
ORDER BY timestamp_sta, batch, machine_id;

But as you can see in the image, returned data in batch_end column are not correct.

batch_start column has correct first value of timestamp_sta column. However batch_end should be "2012-09-17 10:49:45" and it equals timestamp_stp from same row.

Why is it so?

Body:
From syntax documentation:

The frame_clause specifies the set of rows constituting the window frame, which is a subset of the current partition, for those window functions that act on the frame instead of the whole partition. The frame can be specified in either RANGE or ROWS mode; in either case, it runs from the frame_start to the frame_end. If frame_end is omitted, it defaults to CURRENT ROW.

A frame_start of UNBOUNDED PRECEDING means that the frame starts with the first row of the partition, and similarly a frame_end of UNBOUNDED FOLLOWING means that the frame ends with the last row of the partition.

and function list

last_value(value any)     returns value evaluated at the row that is the last row of the window frame

So correct SQL should be:

SELECT DISTINCT
b.machine_id,
batch,
timestamp_sta,
timestamp_stp,
FIRST_VALUE(timestamp_sta) OVER w AS batch_start,
LAST_VALUE(timestamp_stp) OVER w AS batch_end
FROM db_data.sta_stp AS a
JOIN db_data.ll_lu AS b
ON a.ll_lu_id=b.id
WINDOW w AS (PARTITION BY batch, machine_id ORDER BY timestamp_sta range between unbounded preceding and unbounded following)
ORDER BY timestamp_sta, batch, machine_id;


问:
Use GNU parallel to parallelise a bash for loop
I have a for loop which runs a Python script ~100 times on 100 different input folders. The python script is most efficient on 2 cores, and I have 50 cores available. So I'd like to use GNU parallel to run the script on 25 folders at a time.

Here's my for loop (works fine, but is sequential of course), the python script takes a bunch of input variables including the -p 2 which runs it on two cores:

```<code>for folder in $(find /home/rob/PartitionFinder/ -maxdepth 2 -type d); do
        python script.py --raxml --quick --no-ml-tree $folder --force -p 2
done
</code>```

and here's my attempt to parallelise it, which does not work:

```<code>folders=$(find /home/rob/PartitionFinder/ -maxdepth 2 -type d)

echo $folders | parallel -P 25 python script.py --raxml --quick --no-ml-tree {} --force -p 2
</code>```

The issue I'm hitting (perhaps it's just the first of many though) is that my folders variable is not a list, so it's really just passing a long string of 100 folders as the {} to the script.

All hints gratefully received.

答:
You can create a Makefile like this:

```<code>#!/usr/bin/make -f

FOLDERS=$(shell find /home/rob/PartitionFinder/ -maxdepth 2 -type d)

all: ${FOLDERS}

# To execute the find before the all
find_folders:
    @ echo $(FOLDERS) > /dev/null

${FOLDERS}: find_folders
    @ python script.py --raxml --quick --no-ml-tree $@ --force -p 2
</code>```

and then run make -j 25

Be careful: use tabs to indent in your file

Also, files with spaces in the name won't work.

Body:
I have a for loop which runs a Python script ~100 times on 100 different input folders. The python script is most efficient on 2 cores, and I have 50 cores available. So I'd like to use GNU parallel to run the script on 25 folders at a time.

Here's my for loop (works fine, but is sequential of course), the python script takes a bunch of input variables including the -p 2 which runs it on two cores:

for folder in $(find /home/rob/PartitionFinder/ -maxdepth 2 -type d); do
        python script.py --raxml --quick --no-ml-tree $folder --force -p 2
done

and here's my attempt to parallelise it, which does not work:

folders=$(find /home/rob/PartitionFinder/ -maxdepth 2 -type d)

echo $folders | parallel -P 25 python script.py --raxml --quick --no-ml-tree {} --force -p 2

The issue I'm hitting (perhaps it's just the first of many though) is that my folders variable is not a list, so it's really just passing a long string of 100 folders as the {} to the script.

All hints gratefully received.

Body:
You can create a Makefile like this:

#!/usr/bin/make -f

FOLDERS=$(shell find /home/rob/PartitionFinder/ -maxdepth 2 -type d)

all: ${FOLDERS}

# To execute the find before the all
find_folders:
    @ echo $(FOLDERS) > /dev/null

${FOLDERS}: find_folders
    @ python script.py --raxml --quick --no-ml-tree $@ --force -p 2

and then run make -j 25

Be careful: use tabs to indent in your file

Also, files with spaces in the name won't work.


问:
How to create dynamic cell in tableview (without custom cell)?
I have created UITableView with default cell.imagview, cell.textLabel and cell.detailTextLabel.text.

I want to set cell dynamic according to content. I am able to set it dynamic only for either TextLabel or detailTextLabel. But to for both at same time.

Is there any way to do that?

答: @sss You need to return height of every cell in datasource method heightForCell at index path. so You need to calculate the height of the cell in that datasource method for every index path.</p>


问:
C# Call function from another form (radform)
First of all, I would like to point out that I have searched for a solution to this problem without luck.

So basicly I have a Mysql function in Radform1 witch I want to call from CustomAppointmentEditForm

Radform1

```<code>  public RadForm1()
    {
        InitializeComponent();

    }
</code>```

CustomAppointmentEditForm

```<code>        public CustomAppointmentEditForm()
    {
        InitializeComponent();

    }
</code>```

The function I want to call from Radform1

```<code>private void Update_LeadInfo()
    {
        try
        {
            using (MySqlConnection cn = new MySqlConnection(ConString))
            {
                string UniqueID = textBoxDescription.Text;

                string CVR = txtCVR.Text;
                string Firma = txtFirma.Text;
                string Nummer = txtNummer.Text;
                string Addresse = txtAddresse.Text;
                string Postnr = txtPostnr.Text;
                string By = txtBy.Text;
                string Noter = txtNoter.Text;
                string Email = txtEmail.Text;
                string StartDato = dateStart.Text + " " + timeStart.Text;
                string SlutDato = dateEnd.Text + " " + timeEnd.Text;
                string Afholdt = radCheckBox1.CheckState.ToString();
                if(Afholdt == "Checked")
                {
                    Afholdt = "1";
                }
                else
                {
                    Afholdt = "0";
                }
                if(chkAllDay.CheckState == CheckState.Checked)
                {
                    StartDato = dateStart.Text + " " + "00:00";
                    SlutDato = dateEnd.Text + " " + "00:00";
                }
                cn.Open();

                Console.WriteLine(UniqueID);
                MySqlCommand cmd = new MySqlCommand();
                cmd.Connection = cn;
                cmd.CommandText = "UPDATE Leads SET CVR = ('" + CVR + "'), Firma = ('" + Firma + "'), Nummer = ('" + Nummer + "'), Addresse = ('" + Addresse + "'), Postnr = ('" + Postnr + "'), Bynavn = ('" + By + "'), Noter = ('" + Noter + "'), Afholdt = ('" + Afholdt + "'), Email = ('" + Email + "'), Slut_Dato = ('" + SlutDato + "')  WHERE UniqueID = ('" + UniqueID + "');";
                cmd.ExecuteNonQuery();

                cmd.Dispose();
                cn.Close();
            }
        }
        catch (Exception Fejl)
        {
            Console.WriteLine(Fejl);
        }
    }
</code>```

I know there is a simple solution to this, thanks in advance

答:
EDIT:
I wouldn't use this method there.

Update_LeadInfo doesn't seem to use any methods from RadForm1 besides those TextBox.Text objects.

Create another class with paremeters for accessing the Database, e.g.

```<code>public static class DatabaseAccess{

    private static string ConString = "<SOMECONSTRING>";
    public static void Update_LeadInfo(LeadInfo infoObj){ //Don't mix CamelCase and _ Case Notation
        using (MySqlConnection cn = new MySqlConnection(ConString))
        {
           MySqlCommand cmd = new MySqlCommand();
           cmd.Connection = cn;
           cmd.CommandText = "UPDATE Leads SET CVR = ('" + infoObj.CVR + "'), Firma = ('" + infoObj.Firma + "'), Nummer = ('" + infoObj.Nummer + "'), Addresse = ('" + infoObjAddresse + "'), Postnr = ('" + infoObj.Postnr + "'), Bynavn = ('" + infoObj.By + "'), Noter = ('" + infoObj.Noter + "'), Afholdt = ('" + infoObj.Afholdt + "'), Email = ('" + infoObj.Email + "'), Slut_Dato = ('" + infoObj.SlutDato + "')  WHERE UniqueID = ('" + infoObj.UniqueID + "');";
           cmd.ExecuteNonQuery();

           cmd.Dispose();
           cn.Close();
        }
    }
}
</code>```

You LeadInfo class:

```<code> public class LeadInfo{
     public string CVR {get;set}
     ...
     public string Afholdt {get;set;}
 }
</code>```

And use Parameterized Queries!

Instead of cmd.CommandText = "UPDATE Leads SET CVR = ('" + infoObj.CVR + "'), Firma = ('" + infoObj.Firma + "'), Nummer = ('" + infoObj.Nummer + "'), Addresse = ('" + infoObjAddresse + "'), Postnr = ('" + infoObj.Postnr + "'), Bynavn = ('" + infoObj.By + "'), Noter = ('" + infoObj.Noter + "'), Afholdt = ('" + infoObj.Afholdt + "'), Email = ('" + infoObj.Email + "'), Slut_Dato = ('" + infoObj.SlutDato + "')  WHERE UniqueID = ('" + infoObj.UniqueID + "');";

Use:

```<code>string updateCommand = "UPDATE Leads SET CVR = @paramCVR, ..., WHERE UniqueID = @paramUniqueID;"
MySqlCommand m = new MySqlCommand(updateCommand);
m.Parameters.AddWithValue("@paramCVR", infoObj.CVR);
...
m.Parameters.AddWithValue("@paramUniqueID", infoObj.UniqueID);
</code>```

To get access to another public non-static method, you have to reference it in the class you want to use it.

So when you initialize your CustomAppointmentEditForm now, you have to pass the RadForm1 as a parameter.

Build as second constructor without the parameter, if you want to call CustomAppointmentEditForm like before.

Take this as an example:

```<code>RadForm1 radObj;

public CustomAppointmentEditForm(RadForm1 radObj)
{
    InitializeComponent();
    this.radObj = radObj;
}

private void SomeMethod()
{
    radObj.Update_LeadInfo();
}
</code>```

And this is your call from RadForm1:

```<code>CustomAppointmentEditForm custForm = new CustomAppointmentEditForm(this);
</code>```

Body:
First of all, I would like to point out that I have searched for a solution to this problem without luck.

So basicly I have a Mysql function in Radform1 witch I want to call from CustomAppointmentEditForm

Radform1

  public RadForm1()
    {
        InitializeComponent();

    }

CustomAppointmentEditForm

        public CustomAppointmentEditForm()
    {
        InitializeComponent();

    }

The function I want to call from Radform1

private void Update_LeadInfo()
    {
        try
        {
            using (MySqlConnection cn = new MySqlConnection(ConString))
            {
                string UniqueID = textBoxDescription.Text;

                string CVR = txtCVR.Text;
                string Firma = txtFirma.Text;
                string Nummer = txtNummer.Text;
                string Addresse = txtAddresse.Text;
                string Postnr = txtPostnr.Text;
                string By = txtBy.Text;
                string Noter = txtNoter.Text;
                string Email = txtEmail.Text;
                string StartDato = dateStart.Text + " " + timeStart.Text;
                string SlutDato = dateEnd.Text + " " + timeEnd.Text;
                string Afholdt = radCheckBox1.CheckState.ToString();
                if(Afholdt == "Checked")
                {
                    Afholdt = "1";
                }
                else
                {
                    Afholdt = "0";
                }
                if(chkAllDay.CheckState == CheckState.Checked)
                {
                    StartDato = dateStart.Text + " " + "00:00";
                    SlutDato = dateEnd.Text + " " + "00:00";
                }
                cn.Open();

                Console.WriteLine(UniqueID);
                MySqlCommand cmd = new MySqlCommand();
                cmd.Connection = cn;
                cmd.CommandText = "UPDATE Leads SET CVR = ('" + CVR + "'), Firma = ('" + Firma + "'), Nummer = ('" + Nummer + "'), Addresse = ('" + Addresse + "'), Postnr = ('" + Postnr + "'), Bynavn = ('" + By + "'), Noter = ('" + Noter + "'), Afholdt = ('" + Afholdt + "'), Email = ('" + Email + "'), Slut_Dato = ('" + SlutDato + "')  WHERE UniqueID = ('" + UniqueID + "');";
                cmd.ExecuteNonQuery();

                cmd.Dispose();
                cn.Close();
            }
        }
        catch (Exception Fejl)
        {
            Console.WriteLine(Fejl);
        }
    }

I know there is a simple solution to this, thanks in advance

Body:
EDIT:
I wouldn't use this method there.

Update_LeadInfo doesn't seem to use any methods from RadForm1 besides those TextBox.Text objects.

Create another class with paremeters for accessing the Database, e.g.

public static class DatabaseAccess{

    private static string ConString = "<SOMECONSTRING>";
    public static void Update_LeadInfo(LeadInfo infoObj){ //Don't mix CamelCase and _ Case Notation
        using (MySqlConnection cn = new MySqlConnection(ConString))
        {
           MySqlCommand cmd = new MySqlCommand();
           cmd.Connection = cn;
           cmd.CommandText = "UPDATE Leads SET CVR = ('" + infoObj.CVR + "'), Firma = ('" + infoObj.Firma + "'), Nummer = ('" + infoObj.Nummer + "'), Addresse = ('" + infoObjAddresse + "'), Postnr = ('" + infoObj.Postnr + "'), Bynavn = ('" + infoObj.By + "'), Noter = ('" + infoObj.Noter + "'), Afholdt = ('" + infoObj.Afholdt + "'), Email = ('" + infoObj.Email + "'), Slut_Dato = ('" + infoObj.SlutDato + "')  WHERE UniqueID = ('" + infoObj.UniqueID + "');";
           cmd.ExecuteNonQuery();

           cmd.Dispose();
           cn.Close();
        }
    }
}

You LeadInfo class:

 public class LeadInfo{
     public string CVR {get;set}
     ...
     public string Afholdt {get;set;}
 }

And use Parameterized Queries!

Instead of cmd.CommandText = "UPDATE Leads SET CVR = ('" + infoObj.CVR + "'), Firma = ('" + infoObj.Firma + "'), Nummer = ('" + infoObj.Nummer + "'), Addresse = ('" + infoObjAddresse + "'), Postnr = ('" + infoObj.Postnr + "'), Bynavn = ('" + infoObj.By + "'), Noter = ('" + infoObj.Noter + "'), Afholdt = ('" + infoObj.Afholdt + "'), Email = ('" + infoObj.Email + "'), Slut_Dato = ('" + infoObj.SlutDato + "')  WHERE UniqueID = ('" + infoObj.UniqueID + "');";

Use:

string updateCommand = "UPDATE Leads SET CVR = @paramCVR, ..., WHERE UniqueID = @paramUniqueID;"
MySqlCommand m = new MySqlCommand(updateCommand);
m.Parameters.AddWithValue("@paramCVR", infoObj.CVR);
...
m.Parameters.AddWithValue("@paramUniqueID", infoObj.UniqueID);

To get access to another public non-static method, you have to reference it in the class you want to use it.

So when you initialize your CustomAppointmentEditForm now, you have to pass the RadForm1 as a parameter.

Build as second constructor without the parameter, if you want to call CustomAppointmentEditForm like before.

Take this as an example:

RadForm1 radObj;

public CustomAppointmentEditForm(RadForm1 radObj)
{
    InitializeComponent();
    this.radObj = radObj;
}

private void SomeMethod()
{
    radObj.Update_LeadInfo();
}

And this is your call from RadForm1:

CustomAppointmentEditForm custForm = new CustomAppointmentEditForm(this);


问:
Remove filter on image
I'm using AForge.net for my channel filtering, I have 3 button, red, blue and green.
When I click on button red it will apply the filter of red channel. However, when I go on to click on the blue button, it will overlap the red and image goes dark.

Does anyone know how can I "dispose" red channel when blue is click, vice versa, so as the filter will not overlap each other? Below is a snippet of my code.

```<code> private void redchannel_Click_1(object sender, EventArgs e)
    {
        try
        {

            pictureBox1.Image = pic;
            pictureBox2.Image = pic2;

            // create filter
            ChannelFiltering filter = new ChannelFiltering();
            // set channels' ranges to keep
            filter.Red = new IntRange(0, 255);
            filter.Green = new IntRange(255, 255);
            filter.Blue = new IntRange(255, 255);
            // apply the filter
            filter.ApplyInPlace(pic2);

        }

        catch (Exception)
        {
            throw new ApplicationException("Failed loading image");
        }
    }

    private void bluechannel_Click_1(object sender, EventArgs e)
    {
        try
        {
            pictureBox1.Image = pic;
            pictureBox2.Image = pic2;

            // create filter
            ChannelFiltering filter = new ChannelFiltering();
            // set channels' ranges to keep
            filter.Red = new IntRange(255, 255);
            filter.Green = new IntRange(255, 255);
            filter.Blue = new IntRange(0, 255);
            // apply the filter
            filter.ApplyInPlace(pic2);

        }

        catch (Exception)
        {
            throw new ApplicationException("Failed loading image");
        }
    }

    private void greenchannel_Click_1(object sender, EventArgs e)
    {
        try
        {
            pictureBox1.Image = pic;
            pictureBox2.Image = pic2;

            // create filter
            ChannelFiltering filter = new ChannelFiltering();
            // set channels' ranges to keep

            filter.Red = new IntRange(255, 255);
            filter.Green = new IntRange(0, 255);
            filter.Blue = new IntRange(255, 255);
            // apply the filter
            filter.ApplyInPlace(pic2);
        }
        catch (Exception)
        {
            throw new ApplicationException("Failed loading image");

        }
    }
</code>```

答: You need to store the original image as well as a potentially modified display image.  Perform your calculations on the original and show them with the display image.  Never alter the original, only the display image.</p>

Title: Remove filter on image

Body:
I'm using AForge.net for my channel filtering, I have 3 button, red, blue and green.
When I click on button red it will apply the filter of red channel. However, when I go on to click on the blue button, it will overlap the red and image goes dark.

Does anyone know how can I "dispose" red channel when blue is click, vice versa, so as the filter will not overlap each other? Below is a snippet of my code.

 private void redchannel_Click_1(object sender, EventArgs e)
    {
        try
        {

            pictureBox1.Image = pic;
            pictureBox2.Image = pic2;

            // create filter
            ChannelFiltering filter = new ChannelFiltering();
            // set channels' ranges to keep
            filter.Red = new IntRange(0, 255);
            filter.Green = new IntRange(255, 255);
            filter.Blue = new IntRange(255, 255);
            // apply the filter
            filter.ApplyInPlace(pic2);

        }

        catch (Exception)
        {
            throw new ApplicationException("Failed loading image");
        }
    }

    private void bluechannel_Click_1(object sender, EventArgs e)
    {
        try
        {
            pictureBox1.Image = pic;
            pictureBox2.Image = pic2;

            // create filter
            ChannelFiltering filter = new ChannelFiltering();
            // set channels' ranges to keep
            filter.Red = new IntRange(255, 255);
            filter.Green = new IntRange(255, 255);
            filter.Blue = new IntRange(0, 255);
            // apply the filter
            filter.ApplyInPlace(pic2);

        }

        catch (Exception)
        {
            throw new ApplicationException("Failed loading image");
        }
    }

    private void greenchannel_Click_1(object sender, EventArgs e)
    {
        try
        {
            pictureBox1.Image = pic;
            pictureBox2.Image = pic2;

            // create filter
            ChannelFiltering filter = new ChannelFiltering();
            // set channels' ranges to keep

            filter.Red = new IntRange(255, 255);
            filter.Green = new IntRange(0, 255);
            filter.Blue = new IntRange(255, 255);
            // apply the filter
            filter.ApplyInPlace(pic2);
        }
        catch (Exception)
        {
            throw new ApplicationException("Failed loading image");

        }
    }


问:
How to Set RelayState in SAMLEntryPoint
I have my EntryPoint class as follows, but what is the exact value to be set in the relaystate, any example. I want to fetch the URL parameter values requested before authenticating.</p>

```<code>import org.opensaml.saml2.metadata.provider.MetadataProviderException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.saml.SAMLEntryPoint;
import org.springframework.security.saml.context.SAMLMessageContext;
import org.springframework.security.saml.websso.WebSSOProfileOptions;

public class SamlLoginEntryPoint extends SAMLEntryPoint{

    protected WebSSOProfileOptions getProfileOptions(SAMLMessageContext context, AuthenticationException exception) throws MetadataProviderException {

        System.out.println("inside entrypoint");
        WebSSOProfileOptions ssoProfileOptions;
        if (defaultOptions != null) {
            System.out.println("in if");
            ssoProfileOptions = defaultOptions.clone();
            ssoProfileOptions.setRelayState("");
            System.out.println("relaystate:"+ssoProfileOptions.getRelayState());
        } else {
            System.out.println("in else");
            ssoProfileOptions = new WebSSOProfileOptions();
            ssoProfileOptions.setRelayState("");
        }

        return ssoProfileOptions;

    }
</code>```

答:
Override the commence() method of SAMLEntryPoint class and get the request parameter from the request object . </p>

<p>So my implementation looks like this : </p>

```<code>public class CustomMFASamlEntryPoint extends SAMLEntryPoint {
   private String relayState;

   @Override
   public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authenticationException) throws IOException, ServletException {
       //read your request parameter
       setRelayState(request.getParameter("request-param-for-relaystate"));
       super.commence(request, response, authenticationException);
   }

   @Override
   protected WebSSOProfileOptions getProfileOptions(SAMLMessageContext samlMessageContext, AuthenticationException authenticationException) throws MetadataProviderException {
       //set the relayState to your SAML message context
       samlMessageContext.setRelayState(getRelayState());
       return super.getProfileOptions(samlMessageContext, authenticationException);
   }

   private void setRelayState(String relayState) {
       this.relayState = relayState;
   }

   private String getRelayState() {
       return relayState;
   }
}
</code>```

Title: How to Set RelayState in SAMLEntryPoint

Body:
I have my EntryPoint class as follows, but what is the exact value to be set in the relaystate, any example. I want to fetch the URL parameter values requested before authenticating.

import org.opensaml.saml2.metadata.provider.MetadataProviderException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.saml.SAMLEntryPoint;
import org.springframework.security.saml.context.SAMLMessageContext;
import org.springframework.security.saml.websso.WebSSOProfileOptions;

public class SamlLoginEntryPoint extends SAMLEntryPoint{

    protected WebSSOProfileOptions getProfileOptions(SAMLMessageContext context, AuthenticationException exception) throws MetadataProviderException {

        System.out.println("inside entrypoint");
        WebSSOProfileOptions ssoProfileOptions;
        if (defaultOptions != null) {
            System.out.println("in if");
            ssoProfileOptions = defaultOptions.clone();
            ssoProfileOptions.setRelayState("");
            System.out.println("relaystate:"+ssoProfileOptions.getRelayState());
        } else {
            System.out.println("in else");
            ssoProfileOptions = new WebSSOProfileOptions();
            ssoProfileOptions.setRelayState("");
        }

        return ssoProfileOptions;

    }

Body:
Override the commence() method of SAMLEntryPoint class and get the request parameter from the request object .

So my implementation looks like this :

public class CustomMFASamlEntryPoint extends SAMLEntryPoint {
   private String relayState;

   @Override
   public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authenticationException) throws IOException, ServletException {
       //read your request parameter
       setRelayState(request.getParameter("request-param-for-relaystate"));
       super.commence(request, response, authenticationException);
   }

   @Override
   protected WebSSOProfileOptions getProfileOptions(SAMLMessageContext samlMessageContext, AuthenticationException authenticationException) throws MetadataProviderException {
       //set the relayState to your SAML message context
       samlMessageContext.setRelayState(getRelayState());
       return super.getProfileOptions(samlMessageContext, authenticationException);
   }

   private void setRelayState(String relayState) {
       this.relayState = relayState;
   }

   private String getRelayState() {
       return relayState;
   }
}