text:
Q: AnimationRepetitions in Manipulate Is there any way to stop an animation in Manipulate once it gets to the end? I assumed AnimationRepetitions would work like in ListAnimate, but it still loops for me. For Comparison:
ListAnimate[Table[i, {i, 0, 1, 0.1}], AnimationRepetitions -> 1](*Stops after one animation*)

Manipulate[i, {i, 0, 1, 0.1, Appearance -> "Open", AnimationRate -> 0.2, AnimationRunning -> True,   AnimationRepetitions -> 1}](*Loops Continuously*)

A: Ok, I figured out a hack—hopefully someone comes along with something nicer. The trick is to put an invisible flip-flop variable into our Manipulate, and have it become False at the end of the range of the actual variable.
Manipulate[x = x && (i < 1); (*start body*) i,
    {i, 0, 1, 0.1, Appearance -> "Open", AnimationRate -> 0.2, AnimationRunning -> x},
    {x, {True, False}, ControlType -> None}]

A: Update: Use DefaultOptions -> {Animator -> AnimationRepetitions -> 1} instead of AnimationRepetitions -> 1:
Manipulate[i, {i, 0, 1, 0.1, Appearance -> "Open",
  AnimationRunning -> True,
  DefaultOptions -> {Animator -> AnimationRepetitions -> 1}}]

Use  AnimationRepetitions -> 2 to get

Original answer:
Manipulate[i, {i, 0, 1, 0.1,
  Manipulator[##,
    Appearance -> "Open",
    AnimationRate -> 0.2,
    AnimationRunning -> (i < 1)] &}]

A: ListAnimate evidently constructs a Manipulate, and so we should be able to replicate its behavior. One way to figure out how ListAnimate works is to inspect its InputForm (click image to inspect output).
ListAnimate[Table[i, {i, 0, 1, 0.1}],
  AnimationRepetitions -> 1] // InputForm

Unsurprisingly, ListAnimate uses a control of type Animator. The default Manipulate slider is a Manipulator (and Slider is distinct from both).
If we specify an Animator in Manipulate,
then we can use the AnimationRepetitions option.  Here's a slimmed down version:
Manipulate[i, {i, 0, 1, 0.1,
  ControlType -> Animator, AnimationRepetitions -> 1}]

Add options to achieve the appearance desired.


text:
Q: @RefreshScope with @ConditionalOnProperty does not work Problem
Exploring an option of enabling/disabling a @RequestMapping endpoint on demand without restarting JVM. Implement a kill switch on a endpoint at runtime.
Attempt
I've tried the following but @RefreshScope does not seem to work with @ConditionOnProperty
@RestController
@RefreshScope
@ConditionalOnProperty(name = "stackoverflow.endpoints", havingValue = "enabled")
public class MyController {

    @Value("${stackoverflow.endpoints}")
    String value;

    @RequestMapping(path = "/sample", method = RequestMethod.GET)
    public ResponseEntity<String> process() {
        return ResponseEntity.ok(value);
    }

}

Updated property using
POST /env?stackoverflow.endpoints=anyvalue

And reloaded context using
POST /refresh

At this point the controller returns the updated value.
Question
Are there any other ways to achieve the desired functionality?

A: Conditions in Boot are only applied at the Configuration class level or at the bean definition level.
This might help you.
public class MyWebConfiguration extends WebMvcConfigurationSupport {
 @Bean
 @ConditionalOnProperty(prefix="stackoverflow.endpoints",name = "enabled")
 public MyController myController() {
    return new MyController ();
 }
}

A: As Spenser Gibb said here, this behavior is not supported.

redpajama_set_name: RedPajamaStackExchange


text:
Q: FREETEXTTABLE always returns same ranks for all records Below query always returns the same RANK for all records. I've tried not to use quotes and result is the same. Also I've tried to delete\create new index without luck.
select * from FREETEXTTABLE(tProductCharItem, pci_name, '"Размер"') t
            join tProductCharItem pci on t.[KEY] = pci.pci_id
            order by [rank] desc

KEY
RANK
pci_name

53
80
Размер

89
80
Размер люльки (ШxД), см

90
80
Размер прогулочного блока (ШxД), см

91
80
Размер спального места, см

154
80
Размер матраса

209
80
Размер пеленального столика (ШхД), см

Sample data:
create table tProductCharItem(pci_id int identity(1,1) primary key, pci_name nvarchar(100))
insert into tProductCharItem(pci_name) select 'Размер'
insert into tProductCharItem(pci_name) select 'Размер люльки (ШxД), см'
insert into tProductCharItem(pci_name) select 'Размер прогулочного блока (ШxД), см'
insert into tProductCharItem(pci_name) select 'Размер спального места, см'
insert into tProductCharItem(pci_name) select 'Размер матраса'
insert into tProductCharItem(pci_name) select 'Размер пеленального столика (ШхД), см'
insert into tProductCharItem(pci_name) select 'Размер спального места подростковой кровати'
insert into tProductCharItem(pci_name) select 'Размер подножки, см'


text:
Q: Какая функция будет производительнее? Функция traversalTreeDOM, у нее есть один +, она будет работать в более древних браузерах.
Какая функция производительнее, traversalTreeDOM или traversalTree
Конкретнее интересует:
что будет быстрее и производительнее, много раз сделать document.createElement(''); и .appendChild(); или один раз сделать .innerHTML?

var tree = [
 {
  title: 'Razdel 1',
  url: 'razdel_1',
  children: [
   {
    title: 'Razdel 1 1',
    url: 'razdel_1_1'
   },
   {
    title: 'Razdel 1 2',
    url: 'razdel_1_2'
   },
   {
    title: 'Razdel 1 3',
    url: 'razdel_1_3',
    children: [
     {
      title: 'Razdel 1 3 1',
      url: 'razdel_1_3_1',
     },
     {
      title: 'Razdel 1 3 2',
      url: 'razdel_1_3_2',
     },
     {
      title: 'Razdel 1 3 3',
      url: 'razdel_1_3_3',
     }
    ]
   }
  ]
 },
 {
  title: 'Razdel 2',
  url: 'razdel_2',
  children: [
   {
    title: 'Razdel 2 1',
    url: 'razdel_2_1'
   },
   {
    title: 'Razdel 2 2',
    url: 'razdel_2_2'
   },
   {
    title: 'Razdel 2 3',
    url: 'razdel_2_3'
   }
  ]
 },
 {
  title: 'Razdel 3',
  url: 'razdel_3',
  children: [
   {
    title: 'Razdel 3 1',
    url: 'razdel_3_1'
   },
   {
    title: 'Razdel 3 2',
    url: 'razdel_3_2'
   },
   {
    title: 'Razdel 3 3',
    url: 'razdel_3_3'
   }
  ]
 },
 {
  title: 'Razdel 4',
  url: 'razdel_4',
  children: [
   {
    title: 'Razdel 4 1',
    url: 'razdel_4_1',
    children: [
     {
      title: 'Razdel 4 1 1',
      url: 'razdel_4_1_1'
     },
     {
      title: 'Razdel 4 1 2',
      url: 'razdel_4_1_2',
      children: [
       {
        title: 'Razdel 4 1 2 1',
        url: 'razdel_4_1_2_1',
       },
       {
        title: 'Razdel 4 1 2 2',
        url: 'razdel_4_1_2_2',
       }
      ]
     },
     {
      title: 'Razdel 4 1 3',
      url: 'razdel_4_1_3'
     }
    ]
   },
   {
    title: 'Razdel 4 2',
    url: 'razdel_4_2'
   },
   {
    title: 'Razdel 4 3',
    url: 'razdel_4_3'
   }
  ]
 },
 {
  title: 'Razdel 5',
  url: 'razdel_5',
  children: [
   {
    title: 'Razdel 5 1',
    url: 'razdel_5_1'
   },
   {
    title: 'Razdel 5 2',
    url: 'razdel_5_2'
   },
   {
    title: 'Razdel 5 3',
    url: 'razdel_5_3'
   }
  ]
 },
 {
  title: 'Razdel 6',
  url: 'razdel_6'
 },
 {
  title: 'Razdel 7',
  url: 'razdel_7',
  children: [
   {
    title: 'Razdel 7 1',
    url: 'razdel_7_1',
   },
   {
    title: 'Razdel 7 2',
    url: 'razdel_7_2',
   },
   {
    title: 'Razdel 7 3',
    url: 'razdel_7_3',
   }
  ]
 }
];

function traversalTree(tree) {
 var rootPath = [{
  node: tree,
  counter: 0
 }];

 var html = '
';

 while(rootPath.length) {
  var index = rootPath[rootPath.length - 1];
  var item = index.node[index.counter];
  if(index.counter === index.node.length) {
   rootPath.pop();
   html += '
';
   if(rootPath.length) {
    html += '
';
   }
   continue;
  }

  html += '
' + item['title'] + '';

  if(item.children) {
   rootPath.push({
    node: item.children,
    counter: 0
   });

   html += '
'
  } else {
   html += '
';
  }
  index.counter++;
 }
 return html;
}

var endOk = traversalTree(tree);
var out1 = document.getElementById('out1');
out1.innerHTML = endOk;
console.log(endOk);

function traversalTreeDOM(tree) {
 var html = document.createElement('ul');
 var rootPath = [{
  node: tree,
  nodeDOM: html,
  counter: 0
 }];

 while(rootPath.length) {
  var index = rootPath[rootPath.length - 1];
  var item = index.node[index.counter];
  var itemDOM = index.nodeDOM;
  if(index.counter === index.node.length) {
   rootPath.pop();
   continue;
  }

  var li = document.createElement('li');
  var a = document.createElement('a');
  a.href = '#' + item['url'];
  var text = document.createTextNode(item['title']);
  a.appendChild(text);
  li.appendChild(a);
  itemDOM.appendChild(li);

  if(item.children) {
   var newLVL = document.createElement('ul');
   rootPath.push({
    node: item.children,
    nodeDOM: newLVL,
    counter: 0
   });

   li.appendChild(newLVL);
  }
  index.counter++;
 }
 return html;
}
var DOMok = traversalTreeDOM(tree);
var out2 = document.getElementById('out2');
out2.appendChild(DOMok);
console.log(DOMok.outerHTML);
#out1 {
 float: left;
}

#out2 {
 float: right;
}
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Document</title>
  <link rel="stylesheet" href="styles/style.css">

-------------------------Обновление-------------------------
Выяснил, следующее:
Конкретно в данном случае appendChild гораздо быстрее innerHTML.
Но, в целом результат +- оба варианта одинаковы...

function randomInteger(min, max) {
 var rand = min + Math.random() * (max + 1 - min);
 rand = Math.floor(rand);
 return rand;
}

var tree = [
 {
  title: 'Razdel 1',
  url: 'razdel_1',
  children: [
   {
    title: 'Razdel 1 1',
    url: 'razdel_1_1'
   },
   {
    title: 'Razdel 1 2',
    url: 'razdel_1_2'
   },
   {
    title: 'Razdel 1 3',
    url: 'razdel_1_3',
    children: [
     {
      title: 'Razdel 1 3 1',
      url: 'razdel_1_3_1',
     },
     {
      title: 'Razdel 1 3 2',
      url: 'razdel_1_3_2',
     },
     {
      title: 'Razdel 1 3 3',
      url: 'razdel_1_3_3',
     }
    ]
   }
  ]
 },
 {
  title: 'Razdel 2',
  url: 'razdel_2',
  children: [
   {
    title: 'Razdel 2 1',
    url: 'razdel_2_1'
   },
   {
    title: 'Razdel 2 2',
    url: 'razdel_2_2'
   },
   {
    title: 'Razdel 2 3',
    url: 'razdel_2_3'
   }
  ]
 },
 {
  title: 'Razdel 3',
  url: 'razdel_3',
  children: [
   {
    title: 'Razdel 3 1',
    url: 'razdel_3_1'
   },
   {
    title: 'Razdel 3 2',
    url: 'razdel_3_2'
   },
   {
    title: 'Razdel 3 3',
    url: 'razdel_3_3'
   }
  ]
 },
 {
  title: 'Razdel 4',
  url: 'razdel_4',
  children: [
   {
    title: 'Razdel 4 1',
    url: 'razdel_4_1',
    children: [
     {
      title: 'Razdel 4 1 1',
      url: 'razdel_4_1_1'
     },
     {
      title: 'Razdel 4 1 2',
      url: 'razdel_4_1_2',
      children: [
       {
        title: 'Razdel 4 1 2 1',
        url: 'razdel_4_1_2_1',
       },
       {
        title: 'Razdel 4 1 2 2',
        url: 'razdel_4_1_2_2',
       }
      ]
     },
     {
      title: 'Razdel 4 1 3',
      url: 'razdel_4_1_3'
     }
    ]
   },
   {
    title: 'Razdel 4 2',
    url: 'razdel_4_2'
   },
   {
    title: 'Razdel 4 3',
    url: 'razdel_4_3'
   }
  ]
 },
 {
  title: 'Razdel 5',
  url: 'razdel_5',
  children: [
   {
    title: 'Razdel 5 1',
    url: 'razdel_5_1'
   },
   {
    title: 'Razdel 5 2',
    url: 'razdel_5_2'
   },
   {
    title: 'Razdel 5 3',
    url: 'razdel_5_3'
   }
  ]
 },
 {
  title: 'Razdel 6',
  url: 'razdel_6'
 },
 {
  title: 'Razdel 7',
  url: 'razdel_7',
  children: [
   {
    title: 'Razdel 7 1',
    url: 'razdel_7_1',
   },
   {
    title: 'Razdel 7 2',
    url: 'razdel_7_2',
   },
   {
    title: 'Razdel 7 3',
    url: 'razdel_7_3',
   }
  ]
 }
];

console.time('GEN');
function genTree(title, url, lvl) {
 if(lvl > 10) {
  return;
 }
 var tree = [];
 var int = randomInteger(3, 5);
 for (var i = 0; i < int; i++) {
  tree[i] = {
   title: title + ' ' + (i + 1),
   url: url + '_' + (i +1)
  };
  if(Math.random() > 0.5) {
   tree[i].children = genTree(title + ' ' + (i + 1), url + '_' + (i +1), lvl + 1);
  }
 }

 return tree;
}

var newTree = genTree('Razdel', 'razdel', 0);
console.timeEnd('GEN');

function traversalTree(tree) {
 var rootPath = [{
  node: tree,
  counter: 0
 }];

 var html = '
';

 while(rootPath.length) {
  var index = rootPath[rootPath.length - 1];
  var item = index.node[index.counter];
  if(index.counter === index.node.length) {
   rootPath.pop();
   html += '
';
   if(rootPath.length) {
    html += '
';
   }
   continue;
  }

  html += '
' + item['title'] + '';

  if(item.children) {
   rootPath.push({
    node: item.children,
    counter: 0
   });

   html += '
'
  } else {
   html += '
';
  }
  index.counter++;
 }
 return html;
}

var out1 = document.getElementById('out1');

console.time('ALL1');
console.time('Function #1');
var endOk = traversalTree(newTree);
console.timeEnd('Function #1');
console.time('innerHTML');
out1.innerHTML = endOk;
console.timeEnd('innerHTML');
console.timeEnd('ALL1');

function traversalTreeDOM(tree) {
 var html = document.createElement('ul');
 var rootPath = [{
  node: tree,
  counter: 0
 }];

 while(rootPath.length) {
  var index = rootPath[rootPath.length - 1];
  var item = index.node[index.counter];
  if(index.counter === index.node.length) {
   rootPath.pop();
   if(rootPath.length) {
    html = html.parentElement.parentElement;
   }
   continue;
  }

  var li = document.createElement('li');
  var a = document.createElement('a');
  a.href = '#' + item['url'];
  var text = document.createTextNode(item['title']);
  a.appendChild(text);
  li.appendChild(a);
  html.appendChild(li);

  if(item.children) {
   var html = document.createElement('ul');
   rootPath.push({
    node: item.children,
    counter: 0
   });

   li.appendChild(html);
  }
  index.counter++;
 }
 return html;
}

var out2 = document.getElementById('out2');

console.time('ALL2');
console.time('Function #2');
var DOMok = traversalTreeDOM(newTree);
console.timeEnd('Function #2');
console.time('appendChild');
out2.appendChild(DOMok);
console.timeEnd('appendChild');
console.timeEnd('ALL2');

console.log(endOk === DOMok.outerHTML);
#out1 {
 float: left;
}

#out2 {
 float: right;
}
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Document</title>
  <link rel="stylesheet" href="styles/style.css">

A: innerHTML медленнее из-за того, что заново рендерит весь родительский элемент.


text:
Q: Can you help me with a bibliography? I have done this, but the webpages don't appear.
\begin{thebibliography}{99}\\

\bibitem{work1}...\\
\bibitem{work9}J O'Connor i E F Robertson: Squaring the circle [en línia] <\underline{http:www-gap.dcs.st-and.ac.uk/~history/HistTopics/Squaring_the_circle.html}>.\\

\end{thebibliography}

A: how about the hyperref package? i.e.
\usepackage{hyperref}

and then in your example
\bibitem{work1}...\
\bibitem{work9} J O'Connor i E F Robertson:
Squaring the circle [en línia]
\href{http:www-gap.dcs.st-and.ac.uk/~history/HistTopics/Squaring_the_circle.html}\

for more details, have a look at e.g.
How can I have colored and underlined links with hyperref?
https://en.wikibooks.org/wiki/LaTeX/Hyperlinks#.5Chyperref


text:
Q: Why does the server say "connection lost, timed out" after joining a minigame? Okay, I have already got this problem a few times, and it disappeared after a few days but I want to play Minecraft when my friends are online.
The problem is: I start Minecraft and I go to multiplayer to join some servers. But everytime I want to join it takes quite a while before the server loads. Okay, that's no problem. But if you're in the server you want to play minigames or go to survival or creative or something like that. If I then for example want to join my survival, it loads a while (again) and then says 'connection lost;timed out' and it keeps doing that.
I tried restarting my computer, and tried several times to join the server but it just doesn't work. How can I fix this?

A: I have to second Ethan's answer. Try going to http://www.speedtest.net and comparing your speed to other people's. Then go to http://www.pingtest.net/ and do the same thing.
This will give you an idea of the condition of your network.
The least likely possibility would be that your router or operating system is actively blocking the game. Though people will disagree, I'd suggest turning your firewall off if you are behind a router, as a router provides EXACTLY the same functionality as a firewall network wide.
If you are NOT connected to a router and are instead connected directly to a modem of some sort I would NOT disable your firewall.
If you continue to have issues, try looking up port forwarding for the game.
Hope I have been helpful, and good luck!


text:
Q: Macbook Pro Late 2011 ran once but will not run again after reinstalling El Capitan OS Over the weekend, I wiped my drive and reinstalled my Mac's OS using the MacOS Utilities.
Everything went fine with the reinstall, I was able to run the new OS (El Capitan) and even download Chrome.
I closed the lid on my mac (while machine still on) and went to sleep.  The next morning, I was not able to turn the machine on again.
At first, I thought it was the battery, so I charged the battery for 2 hours and tried again.  Nothing. No sound, no chime, no indications of any kind that the machine is running or trying to run.
I did notice the breath light was solid, however, after I reset NVRAM and PRAM, the breath light went off.  More importantly, the mac still wouldn't turn on.
Not sure what's going on, one day it was good and next day no life.
Please help!

A: Try holding down the power button for a long period of time until you hear a loud long beep come from the machine. This will force machine to 'hard' boot up and perform hardware checks as it does so.


text:
Q: How to set up groups of checkboxes which affect each other Sorry for the ambiguous title, but it's quite hard to condense what I'm trying to do into a few words. Here's exactly what I'm trying to do:
I want to have a series of groups of checkboxes. One would be gender, with checkboxes for Male and Female, one would be Region, with checkboxes for North, East, South and West and so on.
The aim is to allow the user to select say, Male or Female, but as soon as they put a check in a checkbox of another group e.g. any of the Region checkboxes, all of their previous 'checks' from all other groups are removed.
The point is to only allow the user to select from one group of checkboxes at a time.
I can only think of checking which checkboxes have been marked on click using javascript, but was wondering if there was a simpler way which I may be missing.
I've also thought that maybe a hidden radio button for each group could work.
If anyone has a more elegant solution I'm eager to hear it.

A: Its been a long time since I've done any pure Javascript, libraries like jQuery make this kind of thing so easy. Anyway, something a bit like the following might work, you'd need to test it in a few browsers and tweak to what you need.
<form name="theForm">
    <input type="checkbox" id="male" name="theGroup" onClick="clearGroup(this);">male
    <input type="checkbox" id="female" name="theGroup" onClick="clearGroup(this);">female

    <input type="checkbox" id="north" name="theGroup" onClick="clearGroup(this);">north
    <input type="checkbox" id="south" name="theGroup" onClick="clearGroup(this);">south
    <input type="checkbox" id="east" name="theGroup" onClick="clearGroup(this);">east
    <input type="checkbox" id="west" name="theGroup" onClick="clearGroup(this);">west
</form>

Here is a working example to play around with.
You could do the equivalent thing in jQuery as simply as
$('input:checkbox').click(function() {
    $(this).siblings(':checked').attr('checked', false);
});

and you have no browser compatibility issues to worry about.

A: Managed to figure it out with a little help from fearofawhack planet. Seems really simple now.
Heres a link to the JSFiddle http://jsfiddle.net/aeeN4/

A: if you have different groups you can use this code below.

<form name="theForm">
    <input type="checkbox" id="male" name="theGroup2" onClick="clearGroup(this);">male
    <input type="checkbox" id="female" name="theGroup2" onClick="clearGroup(this);">female

    <input type="checkbox" id="north" name="theGroup" onClick="clearGroup(this);">north
    <input type="checkbox" id="south" name="theGroup" onClick="clearGroup(this);">south
    <input type="checkbox" id="east" name="theGroup" onClick="clearGroup(this);">east
    <input type="checkbox" id="west" name="theGroup" onClick="clearGroup(this);">west
</form>


text:
Q: ESP32/ESP8266 external programmer two way design question When I design a PCB that has a ESP32/ESP8266, I usually integrate a USB-UART bridge in the design as well. However, I am now working on a board that will likely have more than just a few copies.
The USB-UART bridge isn't necessary in this particular application as we are unlikely to edit the code once it is uploaded. It adds up to part cost and my time soldering the boards together.
I want to use one of those cheap USB TTL boards to program the boards.
There is a slight inconvenience.
The standard ESP32 auto program circuit uses the "Request to Send" (RTS) line, and the FTDI programmer that I want to use doesn't have that as a standard output as seen below.

It has an RTS pin on the side, so I could butcher the board and make an adapter on a breadboard but I am very sure my superiors won't accept such a put together solution.
Is there a possible hardware solution I could implement on the main board that would allow me to use one of these FTDI boards to program the ESP32 automatically? Pressing a button isn't an acceptable solution either. It has to be a plug in solution.
If there isn't any then I will have to design a separate programmer board that fits the requirements.

A: You could use ESP-Prog which is built specifically for this job. Comes with both UART and JTAG as well, so it give's you more options.
Comes with IDC cables so all you need is to add a small IDC connector to your board (similar to the ones on the ESP-PROG PCB)
It is not as cheap as those eBay FTDI clones but it still very cheap (~12$) and reliable.

A: To upload code to a ESP8266 chip, you will need the circuit to have it in normal operation and expose RX,TX, IO0 and RST to any interface.
With that, you can use a programmer that will have the bridge circuit and make the proper connections.
As example, you can use a ESP-01(https://www.ebay.ca/itm/203337954357) or ESP-8285-01(https://www.ebay.ca/itm/203337940168)
Those modules do not have the programming circuitry and can be programmed by such devices like this

https://www.ebay.ca/itm/203304682591.
I like this one because it has all the circuitry to auto upload the code without having to press any button.
https://youtu.be/dMmxNos7V0o?t=49
But, if you are working with the bare ESP-12E/F families in your design, you should consider something like this

https://www.aliexpress.com/item/32991118728.html?spm=a2g0s.9042311.0.0.27424c4dfHrdsD
This one is good because you can just snap the module and it does have the circuitry for the upload of your code. I have one and it is a game changing


text:
Q: Connection timed out exception in java HttpClient library but not through chrome browser? I have blocked a port 8070 by the following command:
sudo iptables -A INPUT -p tcp --destination-port 8070 -j DROP

Now, when I deploy my web application in embedded Tomcat 7 on port 8070, and If I access through the URL http://localhost:8070/app or http://192.168.1.3:8070/app, I always get the exception Connection timed out. That is usual because I have blocked that port.
But when I access the URL http://192.168.1.3:8070/app through the chrome browser, I get the Connection Timed out error message. That is also as expected. But When I try to access http://localhost:8070/app through chrome browser, It gives me successful response. This is unusual.
Why I am able to access through browser on localhost, but not through Apache HttpClient library?

A: Note, that this should be on serverfault.com.
But you should try indicating your network interface for iptables like this:
iptables -A INPUT -p tcp -s 192.168.1.3 --destination-port 8070 -j DROP
iptables -A INPUT -p tcp -s localhost --destination-port 8070 -j DROP

A: Chrome uses IPv6 so it can resolve localhost using that, the other examples are using IPv4. So check your hosts file if it contains an ::1 entry for localhost?
You can try with no IPv6 for chrome as well with this command line flag:
--disable-ipv6


text:
Q: Ignore unresolved symbols with Clojure reader I have an app that logs Clojure maps to a log file via prn.  A contrived entry from the log might be:
{:foo "bar"
 :baz [:quux]
 :body #<HttpInput org.eclipse.jetty.server.HttpInput@2a4bd173>}

I'd like to be able to paste this into a repl to inspect the "simple" keys and values, but the reader chokes on #< values.
CompilerException java.lang.RuntimeException:
  Unable to resolve symbol: HttpInput in this context

I don't care about the #< values. Is there a way to get the reader to ignore them, or give me a chance to deal with them directly (sort of like *data-readers*)?

A: To the best of my knowledge, there's no way to make this input work with the reader without manually editing the log output. The default behavior for prn for unrecognized datatypes is to output something of the form:
#<(.getSimpleName (class o)) (str o)>
The # character indicates a reader macro, which dispatches on the following character, and the < character indicates an unreadable form; the reader will always throw an exception when it encounters this.
Your best bet might be to alter the logging for your application, to print something more readable. One way of doing this is providing an implementation of the print-method multimethod for your target class, e.g.:
(defmethod print-method org.eclipse.jetty.server.HttpInput [o w]
  (print-method {:type "HttpInput"
                 :request-uri (-> o ._connection .getRequest .getUri str)}
                w))

(This might not work for the protected field _connection, but hopefully you get the picture.)


text:
Q: Requesting images from Google Cloud makes page extremely slow I am making a PHP Google App Engine site and I've found that requesting images from the Google Cloud service makes the page load extremely slow.
Without loading in the images it takes around 0.5s for the page to load and with the images it takes 10-15s. I assume I am doing something wrong so any help would be much appreciated.
See this example.
My Code
require_once "google/appengine/api/cloud_storage/CloudStorageTools.php";
use google\appengine\api\cloud_storage\CloudStorageTools;

...

function cloudStorageUrl($url, $size, $crop) {
    if (file_exists($url)) {
        $object_image_url = CloudStorageTools::getImageServingUrl($object_image_file, ['size' => $size, 'crop' => $crop]);
        return $object_image_url;
    }
    else {
        return false;
    }
}

A: As suggested by Paul & Stuart I solved this issue by creating a table in Google Cloud SQL where I could store the url returned from Google Cloud Storage so that I didn't have to repeatedly request the url.
Code Example
// Cloud Storage URL function
function cloudStorageUrl($url, $size, $crop) {
    if (file_exists($url)) {
        $object_image_url = CloudStorageTools::getImageServingUrl($object_image_file, ['size' => $size, 'crop' => $crop]);
        return $object_image_url;
    } else {
        return 'none';
    }
}

// Connect to database
$db = new pdo('mysql:unix_socket=/cloudsql/<your-project-id>:<your-instance-name>;dbname=guestbook', 'root', '');

foreach($db->query('SELECT * FROM `images` WHERE `id`="'.$id.'"') as $row) {
    // Check if Cloud Storage URL already exists
    if ($row['url'] && $row['url'] !== 'none') {
        $url = $row['url'];
    } else {
        // Get the Cloud Storage URL and save it
        $url = cloudStorageUrl($row['cloud_storage_location'], 400, false);
        $stmt = $db->prepare('INSERT INTO `images` (id, url) VALUES (:id, :url ON DUPLICATE KEY UPDATE url=VALUES(url))');
        $stmt->execute(array(':id' => intval($id), ':url' => htmlspecialchars($url)));
    }
}


text:
Q: disabled input for autocomplete using Select2 I am using SELECT2 to perform an autocomplete
<select  class="js-example-basic-single" id="existeField">
    <option value="" disabled selected>Selectionnée le
                                    champs</option>
    <option th:each="fields: ${listFields}" th:value="${fields.id}"
        th:data-jira="${fields.idJira}" th:data-type="${fields.type}"
        th:data-defaut="${fields.value}" th:text="${fields.nom}">
   </option>
</select>

and it disabled the input also the design is not very good

A: The problem was not in the SELECT2 but it was in the modal (it is a standard bootstrap modal)
The Modal

  ....

The solution is to simplly remove tabindex="-1" and every thing will be OK.
Hope that weill help some one.


text:
Q: Replace specific values in a matrix using Python I have a m x n matrix where each row is a sample and each column is a class. Each row contains the soft-max probabilities of each class. I want to replace the maximum value in each row with 1 and others with 0. How can I do it efficiently in Python?

A: Some made up data:
>>> a = np.random.rand(5, 5)
>>> a
array([[ 0.06922196,  0.66444783,  0.2582146 ,  0.03886282,  0.75403153],
       [ 0.74530361,  0.36357237,  0.3689877 ,  0.71927017,  0.55944165],
       [ 0.84674582,  0.2834574 ,  0.11472191,  0.29572721,  0.03846353],
       [ 0.10322931,  0.90932896,  0.03913152,  0.50660894,  0.45083403],
       [ 0.55196367,  0.92418942,  0.38171512,  0.01016748,  0.04845774]])

In one line:
>>> (a == a.max(axis=1)[:, None]).astype(int)
array([[0, 0, 0, 0, 1],
       [1, 0, 0, 0, 0],
       [1, 0, 0, 0, 0],
       [0, 1, 0, 0, 0],
       [0, 1, 0, 0, 0]])

A more efficient (and verbose) approach:
>>> b = np.zeros_like(a, dtype=int)
>>> b[np.arange(a.shape[0]), np.argmax(a, axis=1)] = 1
>>> b
array([[0, 0, 0, 0, 1],
       [1, 0, 0, 0, 0],
       [1, 0, 0, 0, 0],
       [0, 1, 0, 0, 0],
       [0, 1, 0, 0, 0]])

A: I think the best answer to your particular question is to use a matrix type object.
A sparse matrix should be the most performant in terms of storing large numbers of these matrices of large sizes in a memory friendly way, given that most of the matrix is populated with zeroes. This should be superior to using numpy arrays directly especially for very large matrices in both dimensions, if not in terms of speed of computation, in terms of memory.
import numpy as np
import scipy       #older versions may require `import scipy.sparse`

matrix = np.matrix(np.random.randn(10, 5))
maxes = matrix.argmax(axis=1).A1
                      # was .A[:,0], slightly faster, but .A1 seems more readable
n_rows = len(matrix)  # could do matrix.shape[0], but that's slower
data = np.ones(n_rows)
row = np.arange(n_rows)
sparse_matrix = scipy.sparse.coo_matrix((data, (row, maxes)),
                                        shape=matrix.shape,
                                        dtype=np.int8)

This sparse_matrix object should be very lightweight relative to a regular matrix object, which would needlessly track each and every zero in it. To materialize it as a normal matrix:
sparse_matrix.todense()

returns:
matrix([[0, 0, 0, 0, 1],
        [0, 0, 1, 0, 0],
        [0, 0, 1, 0, 0],
        [0, 0, 0, 0, 1],
        [1, 0, 0, 0, 0],
        [0, 0, 1, 0, 0],
        [0, 0, 0, 1, 0],
        [0, 1, 0, 0, 0],
        [1, 0, 0, 0, 0],
        [0, 0, 0, 1, 0]], dtype=int8)

Which we can compare to matrix:
matrix([[ 1.41049496,  0.24737968, -0.70849012,  0.24794031,  1.9231408 ],
        [-0.08323096, -0.32134873,  2.14154425, -1.30430663,  0.64934781],
        [ 0.56249379,  0.07851507,  0.63024234, -0.38683508, -1.75887624],
        [-0.41063182,  0.15657594,  0.11175805,  0.37646245,  1.58261556],
        [ 1.10421356, -0.26151637,  0.64442885, -1.23544526, -0.91119517],
        [ 0.51384883,  1.5901419 ,  1.92496778, -1.23541699,  1.00231508],
        [-2.42759787, -0.23592018, -0.33534536,  0.17577329, -1.14793293],
        [-0.06051458,  1.24004714,  1.23588228, -0.11727146, -0.02627196],
        [ 1.66071534, -0.07734444,  1.40305686, -1.02098911, -1.10752638],
        [ 0.12466003, -1.60874191,  1.81127175,  2.26257234, -1.26008476]])

A: This approach using basic numpy and list comprehensions works, but is the least performant. I'm leaving this answer here as it may be somewhat instructive. First we create a numpy matrix:
matrix = np.matrix(np.random.randn(2,2))

matrix is, e.g.:
matrix([[-0.84558168,  0.08836042],
        [-0.01963479,  0.35331933]])

Now map 1 to a new matrix if the element is max, else 0:
newmatrix = np.matrix([[1 if i == row.max() else 0 for i in row]
                                                   for row in np.array(matrix)])

newmatrix is now:
matrix([[0, 1],
        [0, 1]])

A: Y = np.random.rand(10,10)
X=np.zeros ((5,5))
y_insert=2
x_insert=3
offset = (1,2)
for index_x, row in enumerate(X):
  for index_y, e in enumerate(row):
    Y[index_x + offset[0]][index_y + offset[1]] = e


text:
Q: JavaScript Messed up OnChange File Input I do not understand why web technology is so messed up.
I am trying to accomplish something really easy. But found out that it has bugs.
So what I am trying to do is load in a div the image selected by user. It works first time. But once I select browse and select another image it doesn't work. What is wrong here?
<input type="file" id="imgUploadButton" class="default" name="picture" onchange="imageUploaded(event);" />

And this is the Javascript code
var selectedFile = event.target.files[0];
var reader = new FileReader();
var imgtag = document.getElementById("imageTool");

imgtag.title = selectedFile.name;
reader.onload = function(event) {
    imgtag.src = event.target.result;
 };
 reader.readAsDataURL(selectedFile);

A: I would define the onchange event a bit differently if I were you, for example by doing the following:
<input type="file" id="imgUploadButton" />

Best is to do this on the end of the body tag, of course. See my jsfiddle here.


text:
Q: Can't resolve 'fs' , 'os','path','querystring' in in 'C:\Users\..\node_modules\ibm-cloud-sdk-core\lib' in React Js application I want to make a React Application which uses IBM's Watson AI like Text to speech conversion. For that I have generated TTS service on IBM Cloud . added Credentials and keys in the code. but when I run the application via npm start or yarn start , it gives me errors like below :
Module not found: Error: Can't resolve 'fs' in 'C:..\node_modules\ibm-cloud-sdk-core\lib'
Module not found: Error: Can't resolve 'os' in 'C:..\node_modules\ibm-cloud-sdk-core\auth\utils'
Module not found: Error: Can't resolve 'http' in 'C:..\node_modules\ibm-cloud-sdk-core\auth\utils'
Can anyone help me with above errors. It seems error from node_modules.
Is it with some version related issues?
Any SDKs,Packages need to installed to run the application ?
Request you to help me with solutions and suggestion to resolved the above errors.
Thanks.

A: This error indeed seems to deal with missing node modules that you try to import. Try to run this command in order to install all dependencies that you miss:
npm install -g npm-install-missing
npm-install-missing

Alternatively, you may try to install all dependencies listed in your package.json this way:
npm install

If you need to install some specific dependency and you know its name, this solution will install it and add to your package.json:
npm install {package-name} --save


text: Q: how to load XML data into data set using Delphi,without using third party components? i want to load XML data(around 25000+ records) into data set (TQuery, TStored Proc) without using third party components. i am using Delphi 5, so i do not have TClientDataSet.


text:
Q: Is there a prime of height $i$ in support of $H^i_I(R)$? $I$ is an ideal of a local Noetherian ring $R$ and $i>0$ .
Clearly the height of primes in support of $H^i_I(R)$ is at least $i$
The question is if it
contains a prime of height $i$, specially when $R$ is complete and unmixed?
PS What about the case $i$ equals the cohomological dimension of $I$, ie
$$i=\sup\lbrace j: H^j_I(R)\neq 0\rbrace $$

A: Let $(R, \mathfrak{m}) = k[[a, b, c, d]]$ where $k$ a field. Set $I_1 = (a, b),I_2 = (c, d)$ and $I  = I_1 \cap I_2$. Consider $H^3_I(R)$ (use Mayer-Vietoris exact sequence, Hartshorne-Lichtenbaum vanising theorem) we can prove that $\text{supp}H^3_I(R) = \{\mathfrak{m}\}$. Notice that, by Lyubeznik (D-modules, F-modules) we have $H^3_I(R) \cong E(k)$ the injective hull of $k$.


text:
Q: XSLT to map elements copied file I would like to copy an entire file, manipulate some of its elements by mapping it to corresponding elements in the original xml xsl file. Assume I have a table that tells me which elements from file2 ought to be mapped to corresponding elements in file2. As an example, element writer from file2 ought to be mapped to element author in file1.
For the sake of brevity, let say file1 looks like this:
<?xml version="1.0" encoding="UTF-8"?>
    <Books>
      <book1>
        <title>Things fall apart</title>
        <author name = "Chinua Achebe" nationality = "Nigerian" />
      </book1>
    </Books>

And file2 looks like this:
<?xml version="1.0" encoding="UTF-8"?>
    <Books>
      <book2>
        <title> 1984</title>
        <writer>George Orwel</writer>
      </book2>
    </Books>

And I have the following XSLT:
<xsl:template match="@*|node()">
      <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
      </xsl:copy>
    </xsl:template>

    <xsl:template match="Books">
      <Bundle>
        <id value="test"/>
        <resource>
          <!-- I am copying into here the entire File2 -->
          <xsl:copy-of select="document('file2.xml')/*"/>
        </resource>
      </Bundle>
      <xsl:apply-templates/>
    </xsl:template>

Now, I know that element writer in file2 which I copied in its entirety needs to be mapped to its corresponding element in file1, namely author, so that in the end whenever element writer occurs in file2, it is changed to thus:
<author name = "Chinua Achebe" nationality = "Nigerian" />

And this should be the final output.
<Bundle>
    <id value="test"/>
    <resource>
      <?xml version="1.0" encoding="UTF-8"?>
  <!-- Here, the copied and modified file2-->
        <Books>
            <book2>
                    <title> 1984</title>
                    <author name = "Chinua Achebe" nationality = "Nigerian" />
            </book2>
        </Books>

</resource>
  </Bundle>

A: Why not put the content of file2.xml into a variable?
Example (not related to the particular files you posted):
<xsl:variable name="params">
    <xsl:copy-of select="doc('xslt_params.xml')"/>
</xsl:variable>

Then you can access anything from the entire document. Example:
<xsl:variable name="lang">
    <xsl:value-of select="$params/descendant::param[1]/@lang1"/>
</xsl:variable>

A: I am not sure why you can't use file2.xml as the source XML for the transformation - or why you even need the file1.xml here.
In any case, you can easily apply templates to nodes in another document  (or use xsl:for-each on them). Here's an example:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<!-- identity transform -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="/">
    <Bundle>
        <id value="test"/>
        <resource>
            <xsl:apply-templates select="document('file2.xml')/*"/>
        </resource>
    </Bundle>
</xsl:template>

<xsl:template match="writer">
    <author>
        <xsl:apply-templates select="@*|node()"/>
    </author>
</xsl:template>

</xsl:stylesheet>

When this transformation is applied to any well-formed XML source (note that your file1.xml is not well-formed), the result will be:
<?xml version="1.0" encoding="UTF-8"?>
<Bundle>
   <id value="test"/>
   <resource>
      <Books>
         <book2>
            <title> 1984</title>
            <author>George Orwel</author>
         </book2>
      </Books>
   </resource>
</Bundle>

Note that this is not the result shown in your question. As I already mentioned in comments to your question, If you want to use the entire author node from file1.xml as a replacement for the writer node in file2.xml, you will need to provide the logic by which the stylesheet can identify which property of which book to use as the replacement.
For example, if both files have only one Book, you could use:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:variable name="input" select="/" />

<!-- identity transform -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="/">
    <Bundle>
        <id value="test"/>
        <resource>
            <xsl:apply-templates select="document('file2.xml')/*"/>
        </resource>
    </Bundle>
</xsl:template>

<xsl:template match="writer">
    <xsl:copy-of select="$input/Books/book1/author"/>
</xsl:template>

</xsl:stylesheet>

Given a well-formed input such as:
XML
<Books>
    <book1>
        <title>Things fall apart</title>
        <author name = "Chinua Achebe" nationality = "Nigerian"></author>
    </book1>
</Books>

this would return:
<?xml version="1.0" encoding="UTF-8"?>
<Bundle>
   <id value="test"/>
   <resource>
      <Books>
         <book2>
            <title> 1984</title>
            <author name="Chinua Achebe" nationality="Nigerian"/>
         </book2>
      </Books>
   </resource>
</Bundle>


text:
Q: Garbage collector for young generation Have sort question - is it true that all GC in JDK 7 (other than G1) always use stop-the-world for young generation collection?
thanks

A: All (almost) Java garbage collectors has some sort of a Stop-the-world phase where all the Java threads  (not native threads) are suspended waiting for exclusive system operations to complete. This state is sometimes referred to as a safepoint.
The modern garbage collectors are concurrently running together with the applications threads, which means that the garbage collector perform its work at the same time as the application threads are running. During the garbage collector process there are phases where exclusive access memory is needed, in that phase the application Java threads goes into the safepoint state.
One alternative to get rid of the stop-the-world garbage collections is to go for the Zing JVM with the C4 collector from Azul systems. The implementation has a low pause approach with no stop-the-world collections at all. Instead it is using a concurrent compacting approach with no stop-the-world phase.

A: No it is not true.  Java 7 also supports the older Concurrent Mark Sweep (CMS) collector.  CMS is a low pause collector, just like G1.
UPDATE
Apparently CMS is only for the tenured generation ... according to the blog posting that you found at http://blogs.oracle.com/jonthecollector/entry/our_collectors
So that means that your proposition is in fact true.

One could argue that all of the low-pause collectors:
  - need to stop the mutator threads to do some phases of their work, and
  - may fall back to a Full GC using the mark/sweep collector when they can't keep up.
However, there is a qualitive difference between "mostly concurrent" collectors like G1 and CMS, and other collectors that suspend non-GC threads for the entire duration of the collection process.  That is what is normally meant by a "stop the world" strategy.

A: For OpenJDK, JRockit, IBM JVM, and Sun/Oracle JDK, the young collection is always stop the world for every available collector.
The only JVM I know of which does not have a stop the world collector is  Azul's Zing. (Not free)
While OpenJDK/Hotspot has CMS this is mostly concurrent.  There is still stop the world portions and in some cases CMS will fall back to a Full GC which is stop-the-world.
AFAIK, It is hard to find real world examples where G1 is faster in terms of pause time than CMS, however it is improving all the time.
Do your GC logs speak to you


text:
Q: How do I use square brackets in ATTLIST enumeration? I have the following DTD and XML file. When I try to validate the file, I get the following error. The error is occurring on the square bracket in 'byte[]'. How can I include this 'byte[]' in my enumeration? I have tried escaping them with [$#93;, but I get the same error. I tried using quotes around the '"byte[]"' like so, but that didn't work either.
org.xml.sax.SAXParseExceptionpublicId: -//Genera//DTD XML EJB 1.0//EN; systemId: file:///C:/tdc-to-xml/ejb.v2.dtd; lineNumber: 11; columnNumber: 52; The enumerated type list must end with ')' in the "java-type" attribute declaration.
DTD
<!ELEMENT kds-ejb (entities, methods)>
<!ELEMENT entities (entity+)>
<!ELEMENT entity (field+)>
<!ATTLIST entity name CDATA #REQUIRED>
<!ATTLIST entity db-name CDATA #REQUIRED>
<!ATTLIST entity sequence-name CDATA #IMPLIED>
<!ATTLIST entity is-audited (TRUE|FALSE) "FALSE">
<!ELEMENT field (EMPTY)>
<!ATTLIST field name CDATA #REQUIRED>
<!ATTLIST field db-name CDATA #REQUIRED>
<!-- the following line is line 11 -->
<!ATTLIST field java-type (BigDecimal|Boolean|byte[]|Character|Date|Integer|Long|String|Timestamp) #REQUIRED>
<!ATTLIST field is-auto-generated (TRUE|FALSE) "FALSE">
<!ATTLIST field is-audited (TRUE|FALSE) "FALSE">
<!ATTLIST field is-primary-key (TRUE|FALSE) "FALSE">
<!ATTLIST field primary-key-sequence CDATA #IMPLIED>
<!ELEMENT methods (method+)>
<!ELEMENT method (sql, parameters, code?)>
<!ATTLIST method name CDATA #REQUIRED>
<!ATTLIST method entity-name CDATA #IMPLIED>
<!ATTLIST method returns-collection (TRUE|FALSE) "FALSE">
<!ATTLIST method special-return-type CDATA #IMPLIED>
<!ELEMENT sql (#PCDATA)>
<!ELEMENT parameters (parameter)>
<!ELEMENT parameter (EMPTY)>
<!ATTLIST parameter name CDATA #REQUIRED>
<!ATTLIST parameter java-type CDATA #REQUIRED>
<!ATTLIST parameter special-return-type CDATA #IMPLIED>
<!ELEMENT code (line+)>
<!ELEMENT line (text+)>
<!ATTLIST line sequence CDATA #REQUIRED>
<!ELEMENT text (#PCDATA)>

XML
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE kds-ejb PUBLIC "-//Genera//DTD XML EJB 1.0//EN" "ejb.v1.dtd">
<kds-ejb>
    <entities>
        <entity db-name="tblValidate" name="Validate">
            <field db-name="VALIDATE_ID" is-auto-generated="TRUE" is-primary-key="TRUE" java-type="Integer" name="id" primary-key-sequence="0"/>
            <field db-name="VALIDATE_TYPE" java-type="String" name="type"/>
            <field db-name="VALIDATE_DESCRIPTION" java-type="String" name="description"/>
            <field db-name="VALIDATE_ACTIVEYN" java-type="Boolean" name="activeYN"/>
            <field db-name="VALIDATE_OLDCODE" java-type="String" name="oldCode"/>
            <field db-name="VALIDATE_KEYCODE" java-type="String" name="keyCode"/>
        </entity>
    </entities>
    <methods>
        <method entity-name="Validate" name="getValidateByType" returns-collection="TRUE">
            <sql>SELECT * FROM TBLVALIDATE WHERE VALIDATE_TYPE = :type ORDER BY VALIDATE_DESCRIPTION</sql>
            <parameters>
                <parameter java-type="String" name="oldCode" sequence="0"/>
            </parameters>
        </method>
        <method entity-name="Validate" name="getValidateByOldCode" returns-collection="FALSE">
            <sql>SELECT * FROM TBLVALIDATE WHERE VALIDATE_OLDCODE = :oldCode</sql>
            <parameters>
                <parameter java-type="String" name="type" sequence="0"/>
            </parameters>
        </method>
    </methods>
</kds-ejb>

Code to create xml and validate.
public class TdcToXml {
private String fileName = null;

public TdcToXml(String fileName) {
    this.fileName = fileName;
}

private void process() {
    try {

        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

        Document doc = docBuilder.newDocument();
        Element rootElement = doc.createElement("kds-ejb");
        doc.appendChild(rootElement);

        Element entities = doc.createElement("entities");
        rootElement.appendChild(entities);

        Element entity = doc.createElement("entity");
        entity.setAttribute("name", "Validate");
        entity.setAttribute("db-name", "tblValidate");
        entities.appendChild(entity);

        String[][] fields = { { "id", "VALIDATE_ID", "Integer", "TRUE", null, "TRUE", "0" },
                { "type", "VALIDATE_TYPE", "String", null, null, null, null },
                { "description", "VALIDATE_DESCRIPTION", "String", null, null, null, null },
                { "activeYN", "VALIDATE_ACTIVEYN", "Boolean", null, null, null, null },
                { "oldCode", "VALIDATE_OLDCODE", "String", null, null, null, null },
                { "keyCode", "VALIDATE_KEYCODE", "String", null, null, null, null } };
        for (String[] singleField : fields) {
            Element field = doc.createElement("field");
            field.setAttribute("name", singleField[0]);
            field.setAttribute("db-name", singleField[1]);
            field.setAttribute("java-type", singleField[2]);
            if (singleField[3] != null)
                field.setAttribute("is-auto-generated", singleField[3]);
            if (singleField[4] != null)
                field.setAttribute("is-audited", singleField[4]);
            if (singleField[5] != null)
                field.setAttribute("is-primary-key", singleField[5]);
            if (singleField[6] != null)
                field.setAttribute("primary-key-sequence", singleField[6]);
            entity.appendChild(field);
        }

        Element methods = doc.createElement("methods");
        rootElement.appendChild(methods);

        Element method = doc.createElement("method");
        methods.appendChild(method);
        method.setAttribute("name", "getValidateByType");
        method.setAttribute("entity-name", "Validate");
        method.setAttribute("returns-collection", "TRUE");
        methods.appendChild(method);

        Element sql = doc.createElement("sql");
        sql.appendChild(doc.createTextNode(
                "SELECT * FROM TBLVALIDATE WHERE VALIDATE_TYPE = :type ORDER BY VALIDATE_DESCRIPTION"));
        method.appendChild(sql);

        Element parameters = doc.createElement("parameters");
        method.appendChild(parameters);

        Element parameter = doc.createElement("parameter");
        parameter.setAttribute("name", "oldCode");
        parameter.setAttribute("java-type", "String");
        parameter.setAttribute("sequence", "0");
        parameters.appendChild(parameter);

        method = doc.createElement("method");
        methods.appendChild(method);
        method.setAttribute("name", "getValidateByOldCode");
        method.setAttribute("entity-name", "Validate");
        method.setAttribute("returns-collection", "FALSE");
        methods.appendChild(method);

        sql = doc.createElement("sql");
        sql.appendChild(doc.createTextNode("SELECT * FROM TBLVALIDATE WHERE VALIDATE_OLDCODE = :oldCode"));
        method.appendChild(sql);

        parameters = doc.createElement("parameters");
        method.appendChild(parameters);

        parameter = doc.createElement("parameter");
        parameter.setAttribute("name", "type");
        parameter.setAttribute("java-type", "String");
        parameter.setAttribute("sequence", "0");
        parameters.appendChild(parameter);

        // write the content into xml file
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(new File(fileName));

        DOMImplementation domImpl = doc.getImplementation();
        DocumentType doctype = domImpl.createDocumentType("doctype", "-//Genera//DTD XML EJB 1.0//EN",
                "ejb.v1.dtd");
        transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, doctype.getPublicId());
        transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, doctype.getSystemId());
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
        transformer.transform(source, result);

        System.out.println("File saved!");

    } catch (ParserConfigurationException pce) {
        pce.printStackTrace();
    } catch (TransformerException tfe) {
        tfe.printStackTrace();
    }
}

private void validate() {
    try {
        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        domFactory.setValidating(true);
        DocumentBuilder builder = domFactory.newDocumentBuilder();
        builder.setErrorHandler(new ErrorHandler() {
            @Override
            public void error(SAXParseException exception) throws SAXException {
                // do something more useful in each of these handlers
                exception.printStackTrace();
            }

            @Override
            public void fatalError(SAXParseException exception) throws SAXException {
                exception.printStackTrace();
            }

            @Override
            public void warning(SAXParseException exception) throws SAXException {
                exception.printStackTrace();
            }
        });
        builder.parse(fileName);
    } catch (ParserConfigurationException pce) {
        pce.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public static void main(String[] args) {
    TdcToXml tdcToXml = new TdcToXml("ejb.xml");
    tdcToXml.process();
    tdcToXml.validate();
}

}

A: You can't use square brackets in an enumeration; you can only use nmtokens (name tokens) which are comprised of name characters. See here: https://www.w3.org/TR/REC-xml/#d0e3200


text:
Q: Kendo mobile list view template and open new screen I have kendo mobile list view and when list item is tapped I want to open a new window. How do I get div with touch handler to open new window
view.html

in view-model.js
$('#newWindow').open(); //does not work
What is the best way to do this?

A: in Kendo UI Mobile - if you have to go to any screen you will need to make use of the navigate() method on kendo.mobile.Application object.
Take a look at the following demo: http://demos.telerik.com/kendo-ui/m/index#mobile-listview/editing
First view shows a list of products. On clicking any item in the list, we navigate to a editing screen.
In the javascript pay attention to navigate() method
hope this helps.


text:
Q: Как автоматически создать переменную? У меня есть функция, которая перебирает массив и создает кнопки. Скажите, как я могу создать автоматически для каждой кнопки новую переменную вида
const [test] = useSound(SoundImport.test);
function createNewButton() {
    return props.newResult.map(() => (
      <button className={styles.buttonPlay} id='button3'>
        {props.newResult}
      </button>
    ));
  }

Проект на реакте. Не знаю в чистом js это делается или есть методы на реакте

A: Было бы лучше уточнить для чего тебе это нужно, чтобы предложить правильный варинт. Пока есть только 2 идеи реализации того, что тебе нужно. (если я правильно тебя понял)

function createNewButton() {
    const buttonCallback = useCallback((item) => {
      // делаешь то, что надо
    }, [])

    return props.newResult.map((item) => (
      <button className={styles.buttonPlay} onClick={buttonCallback } id='button3'>
        {props.newResult}
      </button>
    ));
}

ЛИБО

const callbacks = {}

function createNewButton() {

    return props.newResult.map((it, i) => {
      const func = () => { ///.... }
      callbacks[i] = func;
      return <button className={styles.buttonPlay} onClick={func} id='button3'>
        {props.newResult}
      </button>
    });
}


text:
Q: Passing different arguments in a function with Powershell I'm writing a GUI tool using powershell that will pull message tracking information from an exchange server. Based on what the user selects will determine the type of search. If not all the args are passed when Get-MessageTrackingLog is run, will the command simply remove that parameter or pass a null value?
Example: if nothing gets passed to "-sender $sender" will the value simply be "null" or will the parameter also be removed, like this?
Get-MessageTrackingLog -server $hts -sender $sender # a value is being passed
or
Get-MessageTrackingLog -server $hts                 # no value for sender is passed
In other words, if I don't pass an arg with a parameter, then I don't want that parameter to be included in the command.
I'm trying to avoid having to write get-messagetrackinglog for every different scenario based on the user's selection.
Hopefully this makes sense to everyone, thanks!
If ($sender -and $chk_Mailbox.checked -and $chk_End.checked -and $chk_start.checked){Msg -sender **$sender** -Start **$Start** -End **$End** -max_res_size **$max_res_size**}
If ($sender -and $chk_Mailbox.checked -and (!$chk_End.checked) -and (!$chk_start.checked)){Msg -sender $sender -max_res_size **$max_res_size**}

Function Msg{
[CmdletBinding()]
Param(
[Parameter(Position=0,Mandatory=$false)]
$Sender,
[Parameter(Position=1,Mandatory=$false)]
$Start,
[Parameter(Position=2,Mandatory=$false)]
$End,
[Parameter(Position=3,Mandatory=$true)]
$max_res_size,
[Parameter(Position=4,Mandatory=$false)]
$EventID,
[Parameter(Position=5,Mandatory=$false)]
$MsgID
)
    BEGIN
    {
        If ($max_res_size -match "unlimited"){$maxloop = 100000000} else {$maxloop = $max_res_size}

        $ht = Get-ExchangeServer | ?{$_.admindisplayversion -match '14.3' -and $_.ServerRole -match 'HubTransport'}  |% {$_.name}
        $startstop = $true
    Foreach ($hts in $ht)
        {
            Get-MessageTrackingLog -server $hts -sender **$sender** -Start **$Start** -End **$End** -resultsize **$max_res_size** -EventID **$EventID** -MessageId **$MsgID** -warningaction 0 |
            %{
                if ($rescount -ge $maxloop){$startstop = $false; break}
                $dataGridView1.rows.add($_.TimeStamp,$_.Sender,[string]$_.Recipients,$_.RecipientCount,`
                $_.TotalBytes,$_.ReturnPath,$_.MessageLatency,$_.MessageLatencyType,$_.EventId,$_.Source,$_.ServerHostname,$_.ConnectorId,$_.MessageId)
                $rescount++
                $Res_Count.text = $rescount
            }
        }
    }
}

A: Yes, this is exactly how it works. A parameter that is not bound to a value will have the default value for that type (or a default value that is specified for that parameter, if present). For reference types or parameters that don't have a specific type, this is $null.
So for a function
function x($a, $b){}
x 1

you'd have $b equal to $null, but in the following case
function x($a, [int]$b){}
x 1

it'd be 0 instead. And for this:
function x($a, $b=-1){}
x 1

you'd get -1 because there's a specific default value specified.

A: You are asking for splatting. It is a handy way to conditionally build a set of parameters for cmdlet calls.
Just to show you one as an example
$parameters = @{
    Server = $hts
    Start = $Start
    End = $End
    ResultSize = $max_res_size
    EventID = $EventID
    MessageId = $MsgID
    WarningAction = 0
}

# If sender was specified then add it as a parameter
if($sender){$parameters.Sender = $sender}

# Call the cmdlets passing all the arguments we used.
Get-MessageTrackingLog @parameters

I know that you would want to make other optional as well. Easy to replicate from what I have shown you here. Basically take a hashtable that you define and build as you check your other parameters. Then you splat that to the cmdlet Get-MessageTrackingLog
Also keep in mind that you can just use default values for some of these inside your param so that way you do not have to check if they exist.
This is also a handy way to keep lines short when you have a lot of parameters. Save the backticks use splatting.


text:
Q: If statement inside a function - relationship to the global scope I have been doing one simple DOM game for ages now. And I can't figure out why the scope is the way it is. Explanation is in the code below. I do not understand why one var must be declared inside of a function in an if statement for it to work, instead of the global scope. I was dealing with this for literally several hours now and I know it must be simple but now its driving me crazy.
//this code does not work - if the var currentScore is declared in the global scope

var
    activePlayer = 1;
    btnRoll = document.querySelector(".btn-roll");
    diceImage = document.querySelector(".dice");
    diceImage.style.display="none";

//var currentScore selects a div - either the one from player 1 or 2

    currentScore = document.querySelector("#current-" + activePlayer);

    btnRoll.addEventListener ("click", function(){
        //after clicking roll dice - generate random num
        var diceNum = Math.floor(Math.random() * 6) + 1;
        diceImage.style.display="block";
        //view a correct image that is the generated number
        diceImage.src="dice-" + diceNum + ".png";
        //if the rolled number greater than one - add to the roundScore
        if (diceNum !== 1) {
            roundScore += diceNum;
//this below should change the text of 0 of a div for player 1 to text of the round score -which it does
            currentScore.textContent = roundScore;

        }
        //else its other players round
        else {
            roundScore = 0;
           if(activePlayer === 1) {
               activePlayer = 2;
  //when I console.log the active player it changes to 2

           }
           else {
               activePlayer = 1;

           }
        }

    });
//problem comes when its suppose to start again - it does recognize that its player 2 but the currentScore variable is stil #current-1 instead of #current-2.

For it to work the currentScore var must be declared the same way but not in a global scope but in the first if statement. Why?


text:
Q: Reset Session in Microsoft BotFramework with NodeJS I am working on a simple project where my primary requirement is to use Microsoft BotFramework's WebChat to create a custom inline app. I want to add a button at the  header which will be a reset button, which will restart the session and remove all the messages but will maintain the same conversation ID. I am not finding any useful documentation on how can I send a message to the bot from a button click. Also How can I notify the bot which conversation's session needs to be erased.
This is the sample code I am using,
<!DOCTYPE html>
 <html>
  <head>
    <link href="stylesheets/botchat.css" rel="stylesheet" />
  </head>
  <body>
   <div id="bot"/>
    <script src="javascripts/botchat.js"></script>
    <script>
     BotChat.App({
       directLine: { secret: '' },
       user: { id: 'you' },
       bot: { id: 'agent' },
       sendTyping: true,
       resize: 'detect'
     }, document.getElementById("bot"));
    </script>
   </body>
 </html>

I have also checked that we have something called deleteUserData event, but I am not sure how do I use this in my scenario.

A: You can do this via back channel. In a nutshell, what will happen is the web page that's hosting webchat will connect to the same DirectLine instance your webchat is using, which will allow the page to communicate with the bot. You can then set up a handler for a reset event which will call the appropriate code to handle resetting the state.
You can see how to set up back channel here:
https://github.com/MissionMarsFourthHorizon/operation-max/tree/master/Node/exercise8-BackChannel

A: Try session.clearDialogStack(); or delete session.userData;


text:
Q: Azure Data Factory 'Failed Validation' with Folder does not exist I uploaded whole set of .txt files in my blob storage with folder structure Year/Month/day.
I circled the folder structure.

Then in the pipeline I have following dataset created.
 "type": "AzureBlob",
        "linkedServiceName": "blob-store",
        "typeProperties": {
            "fileName": "{Day}.csv",
            "folderPath": "adf-data/sales/{Year}/{Month}",
            "format": {
                "type": "TextFormat",
                "columnDelimiter": "\t",
                "firstRowAsHeader": true
            },
            "partitionedBy": [
                {
                    "name": "Year",
                    "value": {
                        "type": "DateTime",
                        "date": "SliceStart",
                        "format": "yyyy"
                    }
                },
                {
                    "name": "Month",
                    "value": {
                        "type": "DateTime",
                        "date": "SliceStart",
                        "format": "MM"
                    }
                },
                {
                    "name": "Day",
                    "value": {
                        "type": "DateTime",
                        "date": "SliceStart",
                        "format": "dd"
                    }
                }
            ]
        },
        "availability": {
            "frequency": "Day",
            "interval": 1
        },
        "external": true,
        "policy": {}
    }

When I run the pipeline I am getting an error with folder does not exist.
Question:
What can I do to troubleshoot this further or fix?

A: I had wrong file extension.  Error message was misleading. Instead of cannot find file I thought the error was about missing folder.
I had to change this
 "typeProperties": {
            "fileName": "{Day}.csv",
            "folderPath": "adf-data/sales/{Year}/{Month}",
            "format": {
                "type": "TextFormat",
                "columnDelimiter": "\t",
                "firstRowAsHeader": true
            },

To (change file extension from csv to txt)
"typeProperties": {
            "fileName": "{Day}.txt",
            "folderPath": "adf-data/sales/{Year}/{Month}",
            "format": {
                "type": "TextFormat",
                "columnDelimiter": "\t",
                "firstRowAsHeader": true
            },


text:
Q: Performance Issue after Truncate and Load of a table in Oracle One of our clients has migrated from old to new (Larger size/resources) servers.
A process (X) is taking 4Hours extra whenever we are doing a truncate and full load of a Specific Table. If we do not truncate-load this table X doesnt take long to run, In process X we are inserting, updating and reading data from this table into numerous temp tables and then using these temp tables further.
I would like to know:

*

*Best Practices whenever a truncate and full load is performed

*What steps can we take from our side on this specific table?

*Does the database migration to another server bring such issues?

*What debugging should I do, I am doing gather stats with cascade after the
full load on this table, then running the process X

*is it recommended to update any Oracle parameters on moving from oracle 12c from Oracle 11g or 10?

sorry for being very generic, the exact usage of the table in process X is complex and difficult to mention here.
Please advise.


text:
Q: How to configure Chrome browser: modify download directory and turn off pdf viewer Im using Selenium + C#  to test me web aplication and generate PDF files from it. I have 2 problems:
1) When PDF file is generated, it's displayed in pdf viewer automatically.  I cannot turn it off. It's still enabled after chrome reboot. Im using Chrome v43.0.4. I want it to be automatically downloaded.
2) When I save generated PDF file, it's saved in default "Downloads" directory. I read that I should be able to overwrite downlaod path  with Chrome parameters but how?:)
UPDATE 1: When I turned off PDF viewer & changed download path manually, it works after MANUAL Chrome restart, but these values are not working when chrome is started automatically from Selenium.
UDPATE2: Selenium ver 2.49

A: You can disable pdf viewer typing "about:plugins" into the omnibox at the top, and disabling Chrome PDF Viewer.
To change the download path open chrome settings and change it on advanced options/downloads.
Regards.


text:
Q: How to check for duplicate CSS rules? I messed up my css and somehow i have a lot of the duplicate rules and my 1800 something lines css file is now of 3000+ lines..
Is there any way/tool that would take my css file as input and check for all the duplicate rules? and possibly generate a css removing those redundancies?

A: Have you tried CSS Lint? Click the arrow by the Lint! button and it'll open up some options you can play with. Make sure "Disallow duplicate properties" is checked

A: Install Node JS
https://nodejs.org/en/download/
if you have already node js installed or after installing open node command prompt window by typing node( on windows machine) in start.
Type following command to install css purge tool

npm install css-purge -g

After the tool is installed,
Open the folder where node command prompt window is open and paste messed up css file there and then type following command in node cmd prompt window

css-purge -i style.css -o style_purged.css

where style.css is the name of messed up css file, the above command will create a new css file with name style_purged.css which does not contain duplicate css rules.
But be careful, it will also remove the comments you have.
https://www.npmjs.com/package/css-purge

A: I have tried a couple of tools such as CSSLint and CSSBurner. I have also tried the CSS Validator from W3C, which I do not like.
One thing I like about CSSBurner is that it is color-coded and lets you scroll through all of your errors and repeats really quickly. I found all of my repeats (and other things) super fast.


text:
Q: How to copy a file to host during packer provisioning? I would like to generate a public/private ssh key pair during packer provisioning and copy the files to the host machine. Is there a way to copy files out from the VM to the host using packer?

A: I figured it out. The file provisioner has a "direction" option that allows download instead of upload
{
"type": "file",
"source": "app.tar.gz",
"destination": "/tmp/app.tar.gz",
"direction" : "download"
}


text:
Q: using cells embedded with text in calculations How can I incorporate text within a cell while maintaining the ability to use that cell in other calculations?
For example: To show "Days" within a cell, I've used formala: =B1-A1&" "&"Days", with A1 representing the start date and B1 representing the end date. [6/29/2016-6/29/2015&" "&"Days"=366 Days]
I want to then use this value in other calculations. A simple example would be adding 1 to the cell to get 377 days. Since the cell has text, I'm getting the #VALUE! error. I believe there is a way around this.

A: This is a good question.
Say we have a cell with the formula:
=B1-A1

Format the cell as Custom General  " Days"

This allows the cell to display properly and still be used numerically !

A: You can convert your result with Value and Left like the following:
=VALUE(LEFT(C1,FIND(" ",C1,1)-1))
C1 is where you have your formula =B1-A1&" "&"Days"
Find will give the number of character where you have " " space and left will return the number on the left of " "
Value will convert the result to number so you can make calculation with it


text:
Q: Estou tendo um problema com meu programa em c++ estou tendo um erro executando esse codigo aqui:
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>

int main (void) {
  char ent[7];
  char senha[7];
  printf("digite a senha: ");
  scanf("%s",&ent);
  printf("digite a senha novamente: ");
  scanf("%s",&senha);
  if (ent==senha){
     printf("foi");
  }
  else
  {
     printf("nao foi");
  }
  return 0;
}

por algum motivo naquele if aparece como se a variavel ent fosse diferente da variavel senha
com certeza deve ser algo bobo que eu devo ter esquecido,alguem poderia me ajudar?

A: Você não está comparando duas string e sim dois arrays de caracteres. Para isso você pode usar a função strcomp():
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main (void) {
  char ent[7];
  char senha[7];
  printf("digite a senha: ");
  scanf("%s",&ent);
  printf("digite a senha novamente: ");
  scanf("%s",&senha);
  if (strcmp(ent,senha) == 0){
     printf("foi");
  }
  else
  {
     printf("nao foi");
  }
  return 0;
}


text:
Q: Merging polygons for rendering with Geoserver For my application, I need to merge the polygons of different records into one polygon, but only for the rendering (WMS Map).
If it's not clear, here's the goal: a PostGIS table contains the buffers around linear structures (roads, railways,...). Each element of each the structure has its own buffer and I'd like to show on the map only the union of the buffers grouped by type (one for the rails, one for the roads,...).
I've tried the following:

*

*having only one buffer object per kind in the table (multipolygon): very slow, since it requires to load the entire polygon each time it is accessed, and not very flexible when the source data is modified

*creating a view in the PostGIS table that groups every thing using the following query:
SELECT min(restriction.id) AS gid, st_multi(st_union(restriction.geom)) AS geom, restriction.type
    FROM public.restriction
    GROUP BY restriction.type
Also very slow, since the union is done each time the view is accessed

*

*Using Geoserver SQL View's feature. According to the following post, a where statement is added to the view to limit the request to the queried bounding box, but is even slower than the PostGIS view: https://getsatisfaction.com/opengeo/topics/postgis_parameterized_view_dynamic_bounding_box
It is not possible to it with SLDs.
Is there any way to improve the query or to achieve the desired result, but faster?
I'm using the latest version of OpenGeo (3.1).

A: Depending on how 'real-time' you need to be, what about doing some processing to make a separate table(s) soley for display purposes? Instead of performing those queries 'live', all the heavy lifting would be done ahead of time. Might be able to schedule it if things change frequently.


text:
Q: How to download millions of S3 files and compress them on the fly? I have an S3 bucket with millions of files, and I want to download all of them. Since I don't have enough storage, I would like to download them, compress them on the fly and only then save them. How do I do this?
To illustrate what I mean:
aws s3 cp --recursive s3://bucket | gzip > file

A: If you want to compress them all into a single file, as your question seems to indicate, you can add a - to the end of the CLI command to make it write to StdOut:
aws s3 cp --recursive s3://bucket - | gzip > file

If you want to compress them as individual files, then you'll need to first get a listing of all the files, then iterate through them and download/compress one at a time.
But you'll probably find it faster as well as cheaper to spin up an public EC2 instance in the same region with enough disk space to hold the uncompressed files, download them all at once, and compress them there (data going from S3 to EC2 is free as long as it doesn't go through a NAT or cross regions). You can then download the compressed files from S3 and shut down the instance.


text:
Q: How can I create a new pandas DataFrame out of an existing one applying a function to every column without a for loop? A simplified script I have now working is as follows:
columns = df.columns.tolist()

df1=pd.DataFrame()

for i in columns:
    df1[i]=[random.uniform(-1*(df[i].std()*3),(df[i].std()*3))+df[i].mean()]

How can I get the same result (a one row dataframe) with a simpler, more efficient code?

A: Try with apply:
df1 = df.apply(lambda x: random.uniform(-3*x.std(),3*x.std())+x.mean())


text:
Q: WebGL isn't working The following is code I got from a tutorial:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<canvas id="glcanvas" width="640" height="480">
  Your browser doesn't appear to support the <canvas> element.
</canvas>

A black box should show up, but I just get a plain white screen. The alert does show up. I am using firefox and webgl-force:enabled is set to true in about:config. Why won't the black box show up?

A: You're missing
// Clear the color as well as the depth buffer.
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

at the end of your gl calls
(source)


text:
Q: Frame stacking/observation stacking in reinforcement learning: what happens until I have reached the stack size I am currently working on a reinforcement learning project and I used observation stacking for the first time. I implemented the custom environemnt with OpenAI Gym and implemented my agents (DQN and PPO) in StableBaselines3. I implemented observation stacking with a stack size of 10 and the code is working and the results are great. However I am not completely understanding what my code is doing at the very beginning before sufficient observations have been stacked. In short: what is the agent doing the first 9 steps? Does the agent still get to chose actions and if, how are the incomplete observations (not yet fully stacked) fed into the Neural Network underlying the agents decissions? I am explicetly not using frame skipping as implemented in the original DQN paper from 2015.
Relevant parts of my implementation:
class SomeEnv(gym.Env):
  def __init__(self, arg1, ...):
    ...
  def step(self, action):
    ...
    return obs, rew, done, info
  def reset(self):
    ...
  def render(self, mode='human', close=False):
    ...

train_env = VecFrameStack(make_vec_env(SomeEnv,
                                  vec_env_cls=DummyVecEnv,
                                  env_kwargs={...}),
                                  n_stack=10)
model = DQN(Mlp_policy,
            train_env,
            ...)
model.learn(...)

Glad for any explanations!


text:
Q: How to escape "at sign" (@) in Invoke-Expression -Command? When I run this command in command-line, it works as expected:
C:\>p4 changes @2019/01/16,@now
...

But when I use it in powershell script, I can't get it working.
First attempt:
PS C:\> Invoke-Expression -Command "p4 changes @2018/01/16, @now"
Invoke-Expression : At line:1 char:25
+ p4 changes @2018/01/16, @now
+                         ~~~~
Splatted variables like '@now' cannot be part of a comma-separated list of arguments.
At line:1 char:1
+ Invoke-Expression -Command "p4 changes @2018/01/16, @now"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ParserError: (:) [Invoke-Expression], ParseException
    + FullyQualifiedErrorId : SplattingNotPermittedInArgumentList,Microsoft.PowerShell.Commands.InvokeExpressionCommand

Escaping comma (successfully):
PS C:\> Invoke-Expression -Command "p4 changes @2018/01/16',' @now"
p4 : Unintelligible revision specification '2018/01/16'.
At line:1 char:1
+ p4 changes @2018/01/16',' @now
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (Unintelligible ...n '2018/01/16'.:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

Now I think the problem is in "at character" ("@") being interpreted on some level. But I've failed to escape it using multiple methods. How to achieve this?
UPD Testing your ideas:
Grave Accent:
PS C:\> Invoke-Expression -Command "p4 changes `@2018/01/16',' `@now"
p4 : Unintelligible revision specification '2018/01/16'.
At line:1 char:1
+ p4 changes @2018/01/16',' @now
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (Unintelligible ...n '2018/01/16'.:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

Single quote (problem with comma):
PS C:\> Invoke-Expression -Command 'p4 changes @2018/01/16, @now'
Invoke-Expression : At line:1 char:25
+ p4 changes @2018/01/16, @now
+                         ~~~~
Splatted variables like '@now' cannot be part of a comma-separated list of arguments.
At line:1 char:1
+ Invoke-Expression -Command 'p4 changes @2018/01/16, @now'
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ParserError: (:) [Invoke-Expression], ParseException
    + FullyQualifiedErrorId : SplattingNotPermittedInArgumentList,Microsoft.PowerShell.Commands.InvokeExpressionCommand

A: Stop using double quotes, if you have no expandable content then use single quotes. See documentation for about_Quoting_Rules
Otherwise it's as others have said, use the backtick (`).

A: Working solution:
$cmd = @'
p4 changes @2018/01/16','@now
'@;
Invoke-Expression $cmd


text:
Q: The best way of parsing xml What do you suggest to use for parsing such as this XML file:
<file>
  <test1 a="true">
    <line1>aaa</line1>
    <line2>aaa</line2>
    <line3>aaa</line3>
    <line4>aaa</line4>
  </test1>
  <test2 a="true">
    <line1>aaa</line1>
    <line2>aaa</line2>
    <line3>aaa</line3>
    <line4>aaa</line4>
  </test2>
  <test3 a="false">
    <line1>aaa</line1>
    <line2>aaa</line2>
    <line3>aaa</line3>
    <line4>aaa</line4>
  </test3>
</file>

*

*XmlReader

*XmlTextReader

*something another?

I'm looking for the fastest and shortest way. I tried with XmlReader but it needs to much extra variables to check which element is parasing currently.
Thanks in advance.C.H.
--update 1--
The work which i want to do is assigning each element of tests to struct "test"

A: Look in to Linq to XML. I can't speak to 'fastest', but it certainly makes my life easier when working with XML.

A: If the file format is not changing frequently use deserialization. It will give you collection of object you are using to deserialize the file with. That's easiest way. You can read more serialization and deserialization.
http://msdn.microsoft.com/en-us/library/ms731073(v=vs.100).aspx
For the fastest, all of these depends on the size of your file.

A: If performance is a concern then this is a very fast parser
http://www.majestic12.co.uk/projects/html_parser.php


text:
Q: Moq Mock lambda expression I am trying to mock a repository on which a lambda expression is executed. The method that I want to execute looks like this:
public SelectListItem GetProtocolById(int protocolId)
{
    var protocol = UnitOfWork.ProtocolRepository.FindAll(s => s.PROTOCOL_ID == protocolId).FirstOrDefault();
    return new SelectListItem()
    {
        Text = protocol.USER_DEFINED_ID,
        Value = protocolId.ToString()
    };
}

I created a mockRepository in another class
protected MockRepository mockRepository = new MockRepository(MockBehavior.Default);

I have an UnitOfWork and a protocols repositories and I mock them like this:
var protocolRepositoryMock = mockRepository.Create<IRepository<PROTOCOL>>();
var unitOfWorkRBMMock = mockRepository.Create<IUnitOfWorkRBM>();

The FindAll method from IRepository looks like this :
IEnumerable<TEntity> FindAll(Expression<Func<TEntity, bool>> where, params Expression<Func<TEntity, object>>[] includes);

And the definition of the IRepository in my IUnitOfWorkRBM is this one:
IRepository<PROTOCOL> ProtocolRepository { get; set; }

I have tried to mock the unitOfWorkMock for it to be able to execute the lambda expression like this:
 unitOfWorkRBMMock.Setup(s => s.ProtocolRepository.FindAll(It.IsAny<Expression<Func<PROTOCOL, bool>>>()))
                .Returns(new Func<Expression<Func<PROTOCOL, bool>>, IEnumerable<PROTOCOL>>(
                expr => protocolsList.Where(expr.Compile())));

But when I try to call the GetProtocolById method, the protocol comes null.
Any ideas on what I am doing wrong here ?

A: The value of the expression provided can be accessed in the Returns method. Use that to filter the fake list
Review following minimal example that was used to solve the problem.
[TestMethod]
public void _MyTestMethod() {
    //Arrange
    var expectedProtocolId = 1;
    var protocolsList = new List<PROTOCOL> {
        new PROTOCOL {
            PROTOCOL_ID = expectedProtocolId,
            USER_DEFINED_ID = "Some user defined Id"
        },
        new PROTOCOL {
            PROTOCOL_ID = 2,
            USER_DEFINED_ID = "Some other user defined Id"
        }
    };

    var unitOfWorkRBMMock = new Mock<IUnitOfWorkRBM>();

    unitOfWorkRBMMock
        .Setup(_ => _.ProtocolRepository.FindAll(It.IsAny<Expression<Func<PROTOCOL, bool>>>(), It.IsAny<Expression<Func<PROTOCOL, object>>[]>()))
        .Returns<Expression<Func<PROTOCOL, bool>>, Expression<Func<PROTOCOL, object>>[]>((expr, includes) => protocolsList.Where(expr.Compile()));

    var sut = new SUT(unitOfWorkRBMMock.Object);

    //Act
    var result = sut.GetProtocolById(expectedProtocolId);

    //Assert

    Assert.IsNotNull(result);
}

class SUT {
    private IUnitOfWorkRBM UnitOfWork;

    public SUT(IUnitOfWorkRBM unitOfWorkRBM) {
        this.UnitOfWork = unitOfWorkRBM;
    }

    public SelectListItem GetProtocolById(int protocolId) {
        var protocol = UnitOfWork.ProtocolRepository.FindAll(s => s.PROTOCOL_ID == protocolId).FirstOrDefault();
        return new SelectListItem() {
            Text = protocol.USER_DEFINED_ID,
            Value = protocolId.ToString()
        };
    }
}

public interface IUnitOfWorkRBM {
    IRepository<PROTOCOL> ProtocolRepository { get; set; }
}

public interface IRepository<TEntity> {
    IEnumerable<TEntity> FindAll(Expression<Func<TEntity, bool>> where, params Expression<Func<TEntity, object>>[] includes);
}

public class PROTOCOL {
    public int PROTOCOL_ID { get; set; }
    public string USER_DEFINED_ID { get; set; }
}

A: you don't need to compile - you can Return expected result directly.
  unitOfWorkRBMMock.Setup(s => s.ProtocolRepository.FindAll(It.IsAny<Expression<Func<PROTOCOL, bool>>>()))
                    .Returns(new List<PROTOCOL>());


text:
Q: How do I fix 'the SSL server certificate authority is not trusted' message in browser? It started a few weeks ago. One of sites gives me a message
NET::ERR_CERT_WEAK_SIGNATURE_ALGORITHM
You attempted to reach some_web_site.org, but the server presented a certificate signed using a weak signature algorithm (such as SHA-1). This means that the security credentials the server presented could have been forged, and the server may not be the server you expected (you may be communicating with an attacker).
And when I click proceed I get:
Reason : The SSL server certificate authority is not trusted.
It's one of the state public service sites.
From my firewall I downloaded SSL proxy default authority certificate as p12 file and installed it in Windows in my trusted root CA. This certificate is valid until May 2022.
However, nothing changes. Is it my fault or the server owner?
Update: The site loads just fine outside of my organisation's LAN. I can load it via my mobile phone 4G network. My firewall does web filtering and SSL inspection. Does it mean that my proxy certificate is invalid? Why did it work a few weeks before and I didn't change anything from my side?
Update2 Screenshots added

A: You seem to be correct in your suspicions: according to the error message, your proxy certificate uses a SHA-1 signature algorithm, which has a serious known weakness. The validity time is not the issue; the bad algorithm is.
The process to deprecate the SHA-1 algorithm started years ago: with Chrome it started in 2014, as it started to flag end-entity certificates that were using SHA-1 and were valid past January 1, 2017 as "secure, but with minor errors". As time passed and new ways to exploit the weakness were discovered, the flagging was extended in steps to all SHA-1 non-root certificates and made more strict: by now, any up-to-date web browser will mark a site with a SHA-1 certificate anywhere in its certificate chain as unequivocally bad.
Certification authorities compliant with CAB/F baseline requirements stopped issuing any new SHA-1 certificates at the start of year 2016.
Microsoft also went through the process to deprecate SHA-1 certificates in 2017.
If your firewall/proxy still uses a certificate with a SHA-1 signing algorithm, it looks like you've been sort of asleep at the wheel for a while. It became apparent only now probably because of some recent security patch that finally made the SHA-1 algorithm as categorically distrusted everywhere.
You should make sure your proxy can use certificates with better algorithms (if it is up to date and can handle modern TLS on websites, it probably already can), and create a new SSL proxy default authority certificate that uses SHA256 instead of SHA-1. You'll need to distribute it to all the clients whose SSL/TLS traffic you wish to monitor. Once distributed, you can switch your proxy to use the new certificate.
With the screenshots added, it look like the browser actually is mostly happy with the certificate it is getting, as there is a good padlock icon in the address bar. The actual error message is shown instead of the page content, which makes me think this is the proxy's way of telling about a certificate validation failure on the connection between the proxy and the target site.
In the first screenshot, you're browsing outside the LAN and the actual certificate of the site can be seen. Note that it's been renewed recently, as its validity time started on 15.10.2018. The CA certificate used to certify the site is "Thawte RSA CA 2018", so even the CA certificate is at most one year old.
You might actually have a combination of two problems:

*

*the browser was unhappy about the proxy's certificate with the deprecated SHA-1 algorithm, but for the time being, it still considers that a forgivable thing.

*and the proxy was unhappy because it does not have either the "Thawte RSA CA 2018" intermediate certificate or its parent, the "DigiCert Global Root CA" certificate in its own store of trusted CA certificates, and so it cannot verify the site's recently-updated actual certificate.

At the time of this writing, the relevant Thawte CA & intermediate certificates seem to be available here.

A: The problem cannot be fixed, except by the owner of the site getting a proper
SSL certificate.
It can be worked around, for example in Chrome by adding to the shortcut
the parameter of --ignore-certificate-errors.
However, with the current clamp-down on security, such workarounds have
a short life-time.


text:
Q: Modular approach for ruby on rails (ror) I'm new on ruby on rails.
I have a project based on three kind of roles (admin,supplier,customer). I have all the understanding of business logic which will go behind it. But I don't know how to keep code separated. Is there any modular approach we can follow in rails to do anything we want to do with different roles e.g. Admin, Supplier, Customer SEPERATEDLY


text:
Q: could not deduce template argument for 'T' My code is :
std::vector<double> Vec;

template<typename T>
void GetObj(VARIANT &vtProp)
{
    CComSafeArray<T> SafeArray;

    SafeArray.Attach(vtProp.parray);
    ULONG Count = SafeArray.GetCount();
    Vec.resize(Count);
    for(ULONG Index = 0; Index < Count; Index++)
    {
        Vec[Index] = SafeArray[Index];
    }
}

while compilation I got the error below:
error C2783: 'void __cdecl GetObj(struct tagVARIANT &)' : could not deduce template argument for 'T'

Kindly suggest me the correct answer

A: There is nothing in the function template's signature that allows the compiler to deduce the template type, so you need to be explicit:
GetObj<TheActualType>(arg);


text:
Q: WebSphere wcm porlet content url rewrite I'm using WebSphere portal 6.0.1 and use it WCM to create an website. There is some page we use a portlet to show multiple content in it. So in the parent page

http://example.com/wps/portal/en/site/path/parent_page

there will be a portlet show some smaller item. When user click on the item it redirect user to

http://example.com/wps/portal/en/site/path/parent_page/!ut/p/c5/04_SB8K8xLLM9MSSzPy8xBz9CP0os3hnd0cPE3MfAwMDZ2cLAyNzDx8T49BQQwMDU6B8JJK8u6-vG1A-1MI8yNUPLI9ft5d-VHpOfhLQnnCQzbhNsjDHLw-yCSRvgAM4Guj7eeTnpuoX5EZUBnvqOgIAX2ux9g!!/dl3/d3/L0lDU0lKSWdrbUEhIS9JRFJBQUlpQ2dBek15cXchLzRCRWo4bzBGbEdpdC1iWHBBRUEhLzdfQ0dBSDQ3TDAwT1VPNzAyN1JRTjMyTzBPMDAvNF9fX185/?WCM_PORTLET=PC_7_CGAH47L00OUO7027RQN32O0O00_WCM&WCM_GLOBAL_CONTEXT=/wps/wcm/connect/en/site/path/parent_page/small_item

which will show item full content.
This long url is auto generate by  WCM it self. I discover that i can access the page in shorter url like

http://example.com/wps/portal/en/site/path/parent_page/?WCM_PORTLET=PC_7_CGAH47L00OUO7027RQN32O0O00_WCM&WCM_GLOBAL_CONTEXT=/wps/wcm/connect/en/site/path/parent_page/small_item

but this still not a friendly - url for SEO.
So I have these question:

*

*How can we make WCM generate url without !ut..... part?

*Can we make it even shorter like below using .htaccess?

http://example.com/wps/portal/en/site/path/parent_page/small_item

or

http://example.com/wps/portal/en/site/path/parent_page/content-small_item

A: In WebSphere Portal 6.0.* the only chance you have of simplifying portal pages is to give the portal pages a friendly name and then access the pages through those names. However, exactly how the portal chooses to generate its urls is within the product and not possible to change.
The direct WCM links will not get any better than what you just gave an example of.
This gets better in later versions of WebSphere Portal.


text:
Q: set selected page number - kendo grid I am creating a grid using kendo-telrik. In this suppose I am having 100 data. From this in json I have only 10 data(suppose first page contains 10 data in pagination). And I am showing all pages(10 pages for 100 data) all the time.
When I click on another page then get next 10 data and show it in ui. For this I am using page change function of kendo grid and get next 10 data.Now I want to list that data in grid with page which I selected.
For this I create sample which is as - http://jsfiddle.net/pporwal26/y6KdK/76/
 var jsonData = JSON.parse("{\"Report\":\"type1\",\"FileList\":[{\"owner\":\"machine-174\\\\admin\",\"path\":\"C:\\\\workarea\\\\WinTest1lakhfileinKB\\\\WinTest\\\\nGYh\\\\SMv\\\\U1P8FLx\\\\vMbhdo\\\\TgFSW\\\\42Ioulj0w.txt\"},{\"owner\":\"machine-174admin\",\"path\":\"C:\\\\workarea\\\\bada_data\\\\Employee Database - Copy (7) - Copy.mdb\"}],\"Count\":100,\"total\":100,\"page\":1}");
function nextData(page){
jsonData = JSON.parse("{\"Report\":\"type1\",\"FileList\":[{\"owner\":\"machine-170\\\\admin\",\"path\":\"C:\\\\workarea\\\\WinTest1lakhfileinKB\\\\WinTest\\\\nGYh\\\\SMv\\\\U1P8FLx\"},{\"owner\":\"machine-170admin\",\"path\":\"C:\\\\workarea\"}],\"Count\":100,\"total\":100,\"page\":"+page+"}");
createGrid(jsonData);
}
createGrid(jsonData);
function createGrid(jsonData){
$("#grid").kendoGrid({
   pageable: true,
   scrollable: true,
   page: jsonData.page,
   pageable: {
         pageSize: 2,
         refresh: true,
         change:function(e){
           nextData(e.index);
         }
     },
   dataSource: {
       serverPaging: true,
       schema: {
           data: "FileList",
           total: "total"

       },
       data: jsonData
   }
});
}

In this sample when I click on change event than it always show 1 page not the page which I selected. and also want that on each click grid is always create new not add in it. What can I do for that?

A: Well I know that calling createGrid(jsonData); inside of the nextData function, you're going to create a table for every time you increment, that alone will cause bugs. Have you tried commenting that out?
I've personally never used kendoGrid, so if my answer's no good, I do apologies, but from having had a look online, this seems to work?
Worst case, you do need that change, in which case, can't you target the data inside the table and just over ride it in some other function? A pretty morbid way of doing it would be to delete/destroy the current one in order to make a new one. But it would work I guess?


text:
Q: iPhone SDK - How to check files' name in document folder? Users can upload images (jpg or png) from computer to iPhone, and images will be stored in app document folder.
My questions are

*

*how to check the names of images that are currently in document folder?

*how to identify it is a jpg or png?
Thanks in advance!:)

A: The files uploaded via iTunes can be found in the app's document folder:
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
 // Get documents folder
    NSString *documentsDirectory = [paths objectAtIndex:0];

In there, get the files and check the extension to find out if it is JPG, PNG or whatever.