text:
Q: Struggling to make my Break Session work in my Pomodoro Clock I am doing a Pomodoro Clock project and am having trouble with my Break Session not working after my timer has reached zero. The Break Session Increment and Decrement buttons work fine, it's just getting it to do what it's intended to do.
Ignore the code commented out, it was alternative work I had tried before and ultimately decided to go with what I have now.:):)

var breakPlease = document.getElementById("breakPlease").innerHTML = 5;
/*
function increaseBreak() {

let breakLength = document.getElementById("break-length");
if (parseFloat(breakLength.innerText) < 60 ) {
breakLength.innerText = parseFloat(breakLength.innerText) + 1
  }
}

function decreaseBreak() {

let breakLength = document.getElementById("break-length");
if (parseFloat(breakLength.innerText) > 0) {
breakLength.innerText = parseFloat(breakLength.innerText) - 1
  }
}
*/

/*
function increaseSession() {

let sessionLength = document.getElementById("session-length");
if (parseFloat(sessionLength.innerText) < 60) {
let increasedSession = parseFloat(sessionLength.innerText) + 1
sessionLength.innerText = increasedSession;
document.getElementById("startingMinutes").innerText = increasedSession;
  }
}

function decreaseSession() {

let sessionLength = document.getElementById("session-length");
if (parseFloat(sessionLength.innerText) > 0) {
let decreasedSession = parseFloat(sessionLength.innerText) - 1
sessionLength.innerText = decreasedSession;
document.getElementById("startingMinutes").innerText = decreasedSession;
  }
}
*/
let startingMinutes = 25;
let time = startingMinutes * 60;

function increaseBreak() {
  if (breakPlease < 60) {
  document.getElementById('breakPlease').innerHTML = ++breakPlease;
  }
}

function decreaseBreak() {
  if (breakPlease >= 2) {
  document.getElementById('breakPlease').innerHTML = --breakPlease;
  }
}

function increaseSession() {
  if (startingMinutes < 60) {
  document.getElementById('timeItself').innerHTML = ++startingMinutes;
  time = startingMinutes * 60;
  }
}

function decreaseSession() {
   if (startingMinutes >= 2) {
   document.getElementById('timeItself').innerHTML = --startingMinutes;
   time = startingMinutes * 60;
  }
}

const countdownEl = document.getElementById('countdown');

let interval = setInterval(updateCountdown, 1000);

function updateCountdown() {
  const minutesLeft = Math.floor(time / 60);
  let secondsLeft = time % 60;

  if (minutesLeft === 0 && secondsLeft === 0) clearInterval(interval);

  secondsLeft = secondsLeft < 10 ? '0' + secondsLeft : secondsLeft;

  countdownEl.innerHTML = `${minutesLeft}: ${secondsLeft}`;
  time--;

}

function startAndStop() {
  if (interval === null) {
    interval = setInterval(updateCountdown, 1000);
  } else {
    clearInterval(interval);
    interval = null;
  }
  console.log('sAS clicked')
}

function resetTime() {
  console.log('rT clicked')
  startingMinutes = 25;
  time = startingMinutes * 60;
  if (interval == null) {
    updateCountdown();
  }
}
* {
  font-family: verdaan;
}
<!doctype html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

    <title>Hello World</title>

makingWater

25 + 5 'clock'

Break Length

5

          <button id="break-increment" class="btn btn-secondary" onclick="increaseBreak()">
            Break Increase
          </button>
          <button id="break-decrement" class="btn btn-danger" onclick="decreaseBreak()">
           Break Decrease
          </button>

Session Length

25

            <button id="session-increment" class="btn btn-secondary" onclick="increaseSession()">
              Session Increase
            </button>
            <button id="session-decrement" class="btn btn-danger" onclick="decreaseSession()">
              Session Decrease
            </button>

Session

25: 00

        <audio id="beep">
            <source src="http://codeskulptor-demos.commondatastorage.googleapis.com/pang/arrow.mp3" type="audio/mp3" />
    <source src="http://codeskulptor-demos.commondatastorage.googleapis.com/pang/arrow.mp3" type="audio/wav" />
      <source src="http://codeskulptor-demos.commondatastorage.googleapis.com/pang/arrow.mp3" type="audio/mpeg" />
        </audio>
          <button id="start_stop" class="btn btn-dark" onclick="startAndStop()">Start/Stop</button>
          <button id="reset" class="btn" onclick="resetTime()">Reset</button>

A: You need to control your session type. If it is a break, update the time with the break time, otherwise with the work time

var breakPlease = document.getElementById("breakPlease").innerHTML = 5;

let startingMinutes = 25;
let time = startingMinutes * 60;
let isBreak = false;

function increaseBreak() {
  if (breakPlease < 60) {
  document.getElementById('breakPlease').innerHTML = ++breakPlease;
  }
}

function decreaseBreak() {
  if (breakPlease >= 2) {
  document.getElementById('breakPlease').innerHTML = --breakPlease;
  }
}

function increaseSession() {
  if (startingMinutes < 60) {
  document.getElementById('timeItself').innerHTML = ++startingMinutes;
  time = startingMinutes * 60;
  }
}

function decreaseSession() {
   if (startingMinutes >= 2) {
   document.getElementById('timeItself').innerHTML = --startingMinutes;
   time = startingMinutes * 60;
  }
}

const countdownEl = document.getElementById('countdown');

let interval = setInterval(updateCountdown, 1000);

function updateCountdown() {
  const minutesLeft = Math.floor(time / 60);
  let secondsLeft = time % 60;

  if (minutesLeft === 0 && secondsLeft === 0) {
      isBreak = !isBreak;
      time = (isBreak ? breakPlease : startingMinutes) * 60;
      console.log(isBreak ? 'break' : 'work', 'start with', time);
  }

  secondsLeft = secondsLeft < 10 ? '0' + secondsLeft : secondsLeft;

  countdownEl.innerHTML = `${minutesLeft}: ${secondsLeft}`;
  time--;

}

function startAndStop() {
  if (interval === null) {
    interval = setInterval(updateCountdown, 1000);
  } else {
    clearInterval(interval);
    interval = null;
  }
  console.log('sAS clicked')
}

function resetTime() {
  console.log('rT clicked')
  startingMinutes = 25;
  time = startingMinutes * 60;
  if (interval == null) {
    updateCountdown();
  }
}
* {
  font-family: verdaan;
}
<!doctype html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

    <title>Hello World</title>

makingWater

25 + 5 'clock'

Break Length

5

          <button id="break-increment" class="btn btn-secondary" onclick="increaseBreak()">
            Break Increase
          </button>
          <button id="break-decrement" class="btn btn-danger" onclick="decreaseBreak()">
           Break Decrease
          </button>

Session Length

25

            <button id="session-increment" class="btn btn-secondary" onclick="increaseSession()">
              Session Increase
            </button>
            <button id="session-decrement" class="btn btn-danger" onclick="decreaseSession()">
              Session Decrease
            </button>

Session

25: 00

        <audio id="beep">
            <source src="http://codeskulptor-demos.commondatastorage.googleapis.com/pang/arrow.mp3" type="audio/mp3" />
    <source src="http://codeskulptor-demos.commondatastorage.googleapis.com/pang/arrow.mp3" type="audio/wav" />
      <source src="http://codeskulptor-demos.commondatastorage.googleapis.com/pang/arrow.mp3" type="audio/mpeg" />
        </audio>
          <button id="start_stop" class="btn btn-dark" onclick="startAndStop()">Start/Stop</button>
          <button id="reset" class="btn" onclick="resetTime()">Reset</button>


text:
Q: Problem with vis.js Network hierarchical layout I have an example of a very simple hierarchical vis.js network, but it displays as a single line in the wrong direction.
The graph should display from left to right, but instead the entire network is displayed in a single vertical line.
I have tried many different options, but I cannot get it to display properly.
Do you know what I'm doing wrong?

// create an array with nodes
var nodes = new vis.DataSet(
  [
    { id: 1,  value: 21, label: 'GR' },
    { id: 12, value: 10, label: 'PL' },
    { id: 18, value: 28, label: 'MM' },
    { id: 22, value: 12, label: 'I_STORE_LOCATOR' },
    { id: 23, value: 18, label: 'SL' },
        { id: 29, value: 3,  label: 'I_PRICEMATCH' },
        { id: 30, value: 6,  label: 'PM' }
  ]
);

// create an array with edges
var edges = new vis.DataSet(
  [
   {id: 13, eLabel: 100, arrows: "to", from: 1, to: 12, },
     {id: 26, eLabel: 100, arrows: "to", from: 1, to: 18, },
     {id: 17, eLabel: 100, arrows: "to", from: 12, to: 1, },
     {id: 32, eLabel: 60, arrows: "to", from: 18, to: 22, },
     {id: 47, eLabel: 60, arrows: "to", from: 18, to: 23, },
     {id: 53, eLabel: 30, arrows: "to", from: 18, to: 29, },
     {id: 62, eLabel: 30, arrows: "to", from: 18, to: 30, },
   {id: 34, eLabel: 120, arrows: "to", from: 22, to: 23, },
     {id: 40, eLabel: 60, arrows: "to", from: 23, to: 22, },
     {id: 43, eLabel: 120, arrows: "to", from: 23, to: 18, },
     {id: 55, eLabel: 30, arrows: "to",  from: 29, to: 30, },
     {id: 58, eLabel: 60, arrows: "to", from: 30, to: 18, }
  ]
);

// create a network
var container = document.getElementById("mynetwork");
var treeData = {
  nodes: nodes,
  edges: edges,
};

let options = {
    "layout": {
    "randomSeed": 2345,
    "improvedLayout":true,
    "clusterThreshold": 150,
    "hierarchical": {
      "enabled":true,
      "levelSeparation": 150,
      "nodeSpacing": 100,
      "treeSpacing": 200,
      "blockShifting": true,
      "edgeMinimization": true,
      "parentCentralization": true,
      "direction": 'LR',        // UD, DU, LR, RL
      "sortMethod": 'directed',  // hubsize, directed
      "shakeTowards": 'leaves'  // roots, leaves
    }
  }
};

var network = new vis.Network(container, treeData, options);

network.on('click', function (properties) {
  var ids = properties.nodes;

  // ids is an array, loop through the items
  for (let i = 0; i < ids.length; i++){
    treeData.nodes.update({id:ids[i],hidden:true})
  }
});
#mynetwork {
  position: absolute;
  top: 0px;
  left: 0px;
  right: 0px;
  bottom: 0px;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/vis-network/9.1.2/dist/dist/vis-network.min.css" rel="stylesheet"/>

A: The network is unable to determine the correct positioning for the hierarchy as it contains cycles (edges in both directions). A note on this can be found in the official example at https://visjs.github.io/vis-network/examples/network/layout/hierarchicalLayoutMethods.html...

Also note that it's impossible to properly position a "hierarchy" with a cycle (If node 1 is above node 2 and node 2 is above node 1 which one is actually on top?)

Removing the edges which loop back causing cycles (edges 17, 40, 43 and 58) allows the hierarchy to display correctly as per the snippet below. If these edges are required then I don't believe it's possible to use hierarchical layout in vis-network.

// create an array with nodes
var nodes = new vis.DataSet(
  [
    { id: 1,  value: 21, label: 'GR' },
    { id: 12, value: 10, label: 'PL' },
    { id: 18, value: 28, label: 'MM' },
    { id: 22, value: 12, label: 'I_STORE_LOCATOR' },
    { id: 23, value: 18, label: 'SL' },
    { id: 29, value: 3,  label: 'I_PRICEMATCH' },
    { id: 30, value: 6,  label: 'PM' }
  ]
);

// create an array with edges
var edges = new vis.DataSet(
  [
   {id: 13, eLabel: 100, arrows: "to", from: 1, to: 12, },
     {id: 26, eLabel: 100, arrows: "to", from: 1, to: 18, },
     //{id: 17, eLabel: 100, arrows: "to", from: 12, to: 1, },
     {id: 32, eLabel: 60, arrows: "to", from: 18, to: 22, },
     {id: 47, eLabel: 60, arrows: "to", from: 18, to: 23, },
     {id: 53, eLabel: 30, arrows: "to", from: 18, to: 29, },
     {id: 62, eLabel: 30, arrows: "to", from: 18, to: 30, },
   {id: 34, eLabel: 120, arrows: "to", from: 22, to: 23, },
     //{id: 40, eLabel: 60, arrows: "to", from: 23, to: 22, },
     //{id: 43, eLabel: 120, arrows: "to", from: 23, to: 18, },
     {id: 55, eLabel: 30, arrows: "to",  from: 29, to: 30, },
     //{id: 58, eLabel: 60, arrows: "to", from: 30, to: 18, }
  ]
);

// create a network
var container = document.getElementById("mynetwork");
var treeData = {
  nodes: nodes,
  edges: edges,
};

let options = {
    "layout": {
    "randomSeed": 2345,
    "improvedLayout":true,
    "clusterThreshold": 150,
    "hierarchical": {
      "enabled":true,
      "levelSeparation": 150,
      "nodeSpacing": 100,
      "treeSpacing": 200,
      "blockShifting": true,
      "edgeMinimization": true,
      "parentCentralization": true,
      "direction": 'LR',        // UD, DU, LR, RL
      "sortMethod": 'directed',  // hubsize, directed
      "shakeTowards": 'leaves'  // roots, leaves
    }
  }
};

var network = new vis.Network(container, treeData, options);

network.on('click', function (properties) {
  var ids = properties.nodes;

  // ids is an array, loop through the items
  for (let i = 0; i < ids.length; i++){
    treeData.nodes.update({id:ids[i],hidden:true})
  }
});
#mynetwork {
  position: absolute;
  top: 0px;
  left: 0px;
  right: 0px;
  bottom: 0px;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/vis-network/9.1.2/dist/dist/vis-network.min.css" rel="stylesheet"/>

redpajama_set_name: RedPajamaStackExchange


text: Q: Android List view animation while dragging down can any one tell me how to prepare the list view with loading animation when dragged list down. Just like twitter animation for loading new tweets.how to keep the required view when the list view dragged down.


text:
Q: How to resize dynamically allocated array of std::list? I created a dynamically allocated array of lists of size 7 which works fine and elements can be pushed to each list in the array. But, when I try to resize the array to size 10 using realloc, which seems to give no error, but when I try to push elements to the lists, I get Segmentation fault error.
Code:
#include <iostream>
#include <list>

int main()
{
    std::list<int> *slots = new std::list<int>[7];

    for (int i = 0; i < 7; ++i)
    {
        slots[i].push_back(i + 1);
        slots[i].push_back(i + 2);
    }

    for (int i = 0; i < 7; ++i)
    {
        for (const auto &slot : slots[i])
        {
            std::cout << slot << ' ';
        }

        std::cout << '\n';
    }

    slots = (std::list<int> *)realloc(slots, sizeof(std::list<int>) * 10);

    // Segmentation fault
    for (int i = 0; i < 10; ++i)
    {
        slots[i].push_back(i);
    }

    return 0;
}

OUtput:
1 2
2 3
3 4
4 5
5 6
6 7
7 8
Segmentation fault

How to fix this? Thanks.

A: You cannot use realloc on classes with constructors and destructors (like std::list) because realloc fails to call the appropriate constructors and destructors. You also cannot use realloc on memory allocated with new.
Do things the easy way, use a vector (of lists)
std::vector<std::list<int>> slots(7);
...
slots.resize(10);


text:
Q: LESS Compiler PHP with Wordpress 4.0.1 and Bootstrap 3 I'm trying to add a php-compiler in my new Wordpress Theme. Therefore I followed this Tutorial: http://www.tailored4wp.com/how-to-use-less-auto-compiler-in-your-next-wordpress-project-quick-tip-361/
My functions.php
/**
* LESS Compiler.
*/
function autoCompileLess() {

    // include lessc.inc
    require_once( get_template_directory().'/less/lessc.inc.php' );

    // input and output location
    $inputFile = get_template_directory().'/less/bootstrap.less';
    $outputFile = get_template_directory().'/css/bootstrap_less.css';

    // load the cache
    $cacheFile = $inputFile.".cache";

    if (file_exists($cacheFile)) {
        $cache = unserialize(file_get_contents($cacheFile));
    } else {
        $cache = $inputFile;
    }

    $less = new lessc;
    // create a new cache object, and compile
    $newCache = $less->cachedCompile($cache);

    // output a LESS file, and cache file only if it has been modified since last compile
    if (!is_array($cache) || $newCache["updated"] > $cache["updated"]) {
        file_put_contents($cacheFile, serialize($newCache));
        file_put_contents($outputFile, $newCache['compiled']);
    }
}
/**
 * Enqueue scripts and styles.
 */
function scripts() {

    wp_enqueue_style( 'bootstrap-css', get_template_directory_uri() . '/css/bootstrap_less.css' );
}
add_action( 'wp_enqueue_scripts', 'scripts' );

If I change some less files, there won't be any file in output-directory. (I set the right permissions)
And if I add
if(is_user_logged_in()) {
add_action('init', 'autoCompileLess');
}

…/wp-admin will show a blank page with no code in it. What's wrong?
********EDIT*************
I copied the Theme to XAMPP Installation and got these Errors:

Fatal error: Uncaught exception 'Exception' with message 'parse error:
  failed at &:extend(.clearfix all);
  D:\xampp\htdocs\wordpress/wp-content/themes/templateName/less/mixins/grid.less
  on line 11' in
  D:\xampp\htdocs\wordpress\wp-content\themes\templateName\less\lessc.inc.php:3460
  Stack trace: #0
  D:\xampp\htdocs\wordpress\wp-content\themes\templateName\less\lessc.inc.php(2273):
  lessc_parser->throwError() #1
  D:\xampp\htdocs\wordpress\wp-content\themes\templateName\less\lessc.inc.php(121):
  lessc_parser->parse('// Grid system?...') #2
  D:\xampp\htdocs\wordpress\wp-content\themes\templateName\less\lessc.inc.php(753):
  lessc->tryImport(Array, Object(stdClass), Object(stdClass)) #3
  D:\xampp\htdocs\wordpress\wp-content\themes\templateName\less\lessc.inc.php(162):
  lessc->compileProp(Array, Object(stdClass), Object(stdClass)) #4
  D:\xampp\htdocs\wordpress\wp-content\themes\templateName\less\lessc.inc.php(147):
  lessc->compileImportedProps(Array, Object(stdClass), Object(stdClass),
  Object(lessc_parser), 'D:\xampp\htdocs...') #5
  D:\xampp\htdocs\wordpress\w in
  D:\xampp\htdocs\wordpress\wp-content\themes\templateName\less\lessc.inc.php
  on line 3460

A: I found a solution, based on Bass Jobsons comments, thanks to Bass Jobson:
Leafo/lessphp is not compatible to Bootstrap 3.1.1 and it seems not to be actively developed anymore. So I changed to oyejorge/lessphp.
https://github.com/oyejorge/less.php/

Transitioning from Leafo/lessphp
Projects looking for an easy transition from leafo/lessphp can use the
  lessc.inc.php adapter. To use, Download the less.php source code and
  unzip the files into your project so that the new 'lessc.inc.php'
  replaces the existing 'lessc.inc.php'.
Note, the 'setPreserveComments' will no longer have any effect on the
  compiled less.


text:
Q: can't draw bezierPath I have the following code that I placed inside a UIViewController:
- (void)drawRect:(CGRect)rect {
    UIBezierPath *trackPath = [UIBezierPath bezierPath];
    [trackPath addQuadCurveToPoint:CGPointMake(10, 30) controlPoint:CGPointMake(0, 0)];
    trackPath.lineWidth = 2;
    [trackPath fill];
    [trackPath stroke];
}

However, I am not seeing the path. What am I doing wrong?

A: UIViewController doesn't implement drawRect:. You need to override that method in a UIView subclass. Additionally, you're probably gonna want to set a color for the bezier path.


text:
Q: is it possible communication between two clients of sip voip server withoust dialing phone number? I want to develop sip voip application. I want to communicate between two users of sip voip server but not communication between our phone contact users. I have seen many example like siphon, linphone, idoubs but it is not direct communication between logged users of sip voip.
I don't want to dial and sms to our phone contact users. I want to only communication between sip user to user.
so, please give any suggestion or source code which is apply in my app.
Thank You...

A: Yes, you can create button on your softphone which will call pre-defined number.
You also can create users list and call from that list.
Or you can get any softphone with sip&jabber support and use that.


text:
Q: Python - pickle.load() takes one positional argument (2 given) This produces an error:
pickle.load() takes one positional argument (2 given)

Here is my code:
import pickle, os.path

created = False

phoneBook = {}
name = input("Please enter a name(or press enter to end input): ")
while name != '':
    number = input("Please enter number: ")
    phoneBook[name] = number
    name = input("Please enter a name(or press enter to end input): ")
    if name == '':
        print("Thank You!")

print("Your phonebook contains the following entries:")
for name, number in phoneBook.items():
    print("%s - %s" % (name, number))

while not created:
    if not os.path.isfile('phonebook.json'):
        phoneBook_Ori = pickle.load('phonebook.json', 'r')
        created = True
    else:
        phoneBook_Ori = pickle.load('phonebook.json', 'w')
        phoneBook_Upd = phoneBook_Ori.update(phoneBook)
        phoneBook_Ori.write(phoneBook_Upd)

phoneBook_Ori.close

Why isn't it pickling data?

A: This is not how you use pickle.load:
phoneBook_Ori = pickle.load('phonebook.json', 'r')

It takes a file object as an argument when de-serializing from a file, not strings.
Try this instead:
# create file object with permissions
with open('phonebook.json', 'r') as f:
    # load using pickle de-serializer
    phoneBook_Ori = pickle.load(f)

Saving is almost the same, make sure you have the updated phonebook in scope:
with open('phonebook.json', 'wb') as f:
    phoneBook_Ori = pickle.dump(phonebook, f)

As for the rest of the code, you may want to read another answer I've given that is very similar.


text:
Q: How can you separate a specific part of a website body in JS here is the body:
"kind": "youtube#searchResult",
    "etag": "\"RmznBCICv9YtgWaaa_nWDIH1_GM/uHwvNpWXbfDW_4Wj8a7WcvZxdKo\"",
     "id": {
     "kind": "youtube#video",
     "videoId": "MXVWCuahiD4"
},

its a youtube api's output from a channel called Camodo Gaming, anyway i need to get the part that says "videoID": "[id]". I don't know how i should split the body. Google cant answer this question.
Here is my current code(using a npm-module request):
var request = require('request');
request('https://www.googleapis.com/youtube/v3/search?
part=snippet&channelId=UCC6ulNJ-KDoIa3VI2gcvQpA&maxResults=1&order=date&type=video&key={token}', function (error, response, body) {
  console.log('error:', error);
  console.log('statusCode:', response && response.statusCode);

  var str = body
  //how can i split the string?
  var split = str.split() // ?
  console.log(split)
});

EDIT:
here is the whole body:
{
 "kind": "youtube#searchListResponse",
 "etag": "\"RmznBCICv9YtgWaaa_nWDIH1_GM/-0EYfTuxeWYgCGHPclJlgnzp8FU\"",
 "nextPageToken": "CAEQAA",
 "regionCode": "FI",
 "pageInfo": {
  "totalResults": 858,
  "resultsPerPage": 1
 },
 "items": [
  {
   "kind": "youtube#searchResult",
   "etag": "\"RmznBCICv9YtgWaaa_nWDIH1_GM/jlYGCUcC2rF87jrQ8VYhA_RRByk\"",
   "id": {
    "kind": "youtube#video",
    "videoId": "paXZZap3bpo"
   },
   "snippet": {
    "publishedAt": "2018-03-23T11:00:05.000Z",
    "channelId": "UCC6ulNJ-KDoIa3VI2gcvQpA",
    "title": "MASSIVE HURRICANE IN THE  ZOMBIE APOCALYPSE! - GTA 5 Mod Gameplay - Zombie Multiplayer Roleplay",
"description": "MASSIVE HURRICANE IN THE ZOMBIE APOCALYPSE! - GTA 5 Mod Gameplay - Zombie Multiplayer Roleplay Welcome to Camodo Gaming's Let's Play of GTA 5 Zombie Apocalypse. We are trying out a zombie...",
    "thumbnails": {
     "default": {
      "url": "https://i.ytimg.com/vi/paXZZap3bpo/default.jpg",
      "width": 120,
      "height": 90
     },
     "medium": {
      "url": "https://i.ytimg.com/vi/paXZZap3bpo/mqdefault.jpg",
      "width": 320,
      "height": 180
     },
     "high": {
      "url": "https://i.ytimg.com/vi/paXZZap3bpo/hqdefault.jpg",
      "width": 480,
      "height": 360
     }
    },
    "channelTitle": "Camodo Gaming",
    "liveBroadcastContent": "none"
   }
  }
 ]
}

A: Your result comes in JSON format, which can be easily parsed into a real JS object, from where you can just call .videoId to get the videoId.

var request = require('request');
request('https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=UCC6ulNJ-KDoIa3VI2gcvQpA&maxResults=1&order=date&type=video&key={token}', function(error, response, body) {
  console.log('error:', error);
  console.log('statusCode:', response && response.statusCode);
  var json = JSON.parse(body);
  console.log(json);
  console.log(json.items[0].id.videoId);
});


text:
Q: Adding one variable to another variable I'm a student and struggling to get my javascript to add the VAT to the other 'variable'
can somebody please assist - the vat displays as "0"
function calculateTotal(){
  var total = 0;
  var vat = total*0.14;

  for (var k = 0; k < document.forms.service.length; k++)
  {
    if(document.forms.service.elements[k].checked){
      total+=Number(document.forms.service.elements[k].value);
    }
  }

  document.getElementById("total").innerHTML= "The total is R " + total;
  document.getElementById("vat").innerHTML= "The total VAT is R " + vat;
}

A: Move var vat = total*0.14; to the end of the function. You have to calculate the vat after you calculate the total.
function calculateTotal(){
  var total = 0;

  for (var k = 0; k < document.forms.service.length; k++)
  {
    if(document.forms.service.elements[k].checked){
      total+=Number(document.forms.service.elements[k].value);
    }
  }

  var vat = total*0.14;
  document.getElementById("total").innerHTML= "The total is R " + total;
  document.getElementById("vat").innerHTML= "The total VAT is R " + vat;
}


text:
Q: How to can I write php asynchroneous functions using reactphp I thought I can do more at same time so I started with reactphp.
The code runs so fine, but I wanted to be sure that the code was indeed asynchroneous I tried the code below which gave me no confidence, it echoed the strings 'in natural order' like "one two three four..." but I was looking for output like "one four three two..." just as it happens in javascript.

function callDone(){
    $g = 'abcdefghuytegbnwsgwseeveddvvdvdcvdvbshasfcfddbbcdgcdvoiuyyttreewwaazxcvbnjjjhgfffhhhabcdefghuytegbnwsgwseeveddvvdvdcvdvbshasfcfddbbcdgcdvoiuyyttreewwaazxcvbnjjjhgfffhhh';
    $r = str_split($g);
    for($i=0;$i<count($r);$i++){
        $g .= $r[$i];
    }
    return 1;
}
$promise = new React\Promise\Promise(function($resolve){
    echo microtime(true). "
start
";
    $resolve(callDone());
}
$promise->then(function($v){
    echo 'one
';
});
$promise->then(function($v){
    echo 'two
';
});
$promise->then(function($v){
    echo 'three
';
});
$promise->then(function($v){
    echo 'four
';
});
$promise->then(function($v){
    echo 'five
';
});

this will print
"one two three four five" But I needed something out of order like: "one three two..." to confirm this is really asynchroneous.
Any help thanks in advance.

A: The problem with the your example is the expectation that these calls should be some kind randomized. The asynchronous aspect of ReactPHP comes mostly from the event-loop which must be non-blocking(as you mentioned in one of the comments below). Not using the event-loop means you are using the standard call stack of PHP.
If you want to see an "more asynchronous" approach you could modify your code a bit.
$loop = \React\EventLoop\Factory::create();

function callDone(){
    $g = 'abcdefghuytegbnwsgwseeveddvvdvdcvdvbshasfcfddbbcdgcdvoiuyyttreewwaazxcvbnjjjhgfffhhhabcdefghuytegbnwsgwseeveddvvdvdcvdvbshasfcfddbbcdgcdvoiuyyttreewwaazxcvbnjjjhgfffhhh';
    $r = str_split($g);
    for($i=0;$i<count($r);$i++){
        $g .= $r[$i];
    }
    return 1;
}
$promise = new React\Promise\Promise(function($resolve){
    echo microtime(true). "
start
";
    $resolve(callDone());
});

$promise->then(function($v) use ($loop) {
    $loop->addPeriodicTimer(0.1, function () {
        echo 'one
';
    });
});

$promise->then(function($v) use ($loop) {
    $loop->addPeriodicTimer(0.2, function () {
        echo 'two
';
    });
});
$promise->then(function($v){
    echo 'three
';
});
$promise->then(function($v){
    echo 'four
';
});
$promise->then(function($v){
    echo 'five
';
});

$loop->run();

We added the event-loop to your code to start a more asynchronous approach.
This will add an asynchronous time to your example which will echo "one" every 0.1 seconds and "two" every 0.2 seconds. As you may see these two timers won't block each other because the event-loop handles these timers.
I hope this helps!


text:
Q: update data from another table postgresql using IN I have 2 tables :table1 and table2.When using this query,
SELECT *
FROM table1 a
WHERE a.name IN (SELECT name FROM table2 )

The result is 20.
When I want update data based on this query
UPDATE table1 SET number='1'
FROM table1 a
WHERE a.name IN (SELECT name FROM table2)

The result is all the number will be set to 1 instead of only 20.The default number is 0.

A: Try this
UPDATE table1 t1 SET number=1
JOIN table2 t2 ON t1.name = t2.name


text:
Q: Acra reporting using email I am trying to use ACRA to report unhandled exceptions in my app.
Gave permission:
<uses-permission android:name="android.permission.READ_LOGS"/>
<uses-permission android:name="android.permission.INTERNET" />
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme"
    android:name=".MyApplication">

gradle:
compile 'ch.acra:acra:4.9.0'

Extended Application Class
package online.hannuveda.transafe_rx;

import org.acra.*;
import org.acra.annotation.*;
import android.support.multidex.MultiDexApplication;

@ReportsCrashes(formUri = "",
        mailTo = "akshaycjoshi@gmail.com",
        mode = ReportingInteractionMode.TOAST,
        resToastText = R.string.crash_toast_text)

public class MyApplication extends MultiDexApplication
{
    @Override
    public void onCreate() {
        super.onCreate();
        ACRA.init(this);
    }
}

In my login button, I am deliberately creating an exception using this:
public void Login_Click(View v)
{

    int i = 12/0;
}

When this exception occurs, I see the toast, then the app crashes but I don't see any email in my inbox. Any idea what is wrong ?

A: Remove formUri = "", and try again.
If you pass both formUri and mailTo, it will first try to send it via HTTP to the endpoint "" and use the mailTo as fallback in case there is no internet permission, but you do have the permission so it only tries to send it to "", and won't try to mail it.

A: Firstly, remove formUri. When you use mailTo in addition to formUri it send the email if there is no internet at the time of the crash.
Further, this permission:
<uses-permission android:name="android.permission.READ_LOGS"/>

Is only for some apps, and I think you have to apply to use it. On newer versions of Android, you don't need that permission any more.


text:
Q: Why is Dr Manhattan's method of killing so messy? In this video we see Dr Manhattan

 kill two mobsters, causing their gory remains to get stuck to the
 ceiling (and their girls).

Additionally, when he

 kills Rorschach, he turns into a bloody splatter on the ground.

Yet, according to The Comedian, Dr Manhattan can turn a

gun into steam, the bullets into mercury and the bottle into goddamn snowflakes

So is The Comedian lying? Or is there a practical reason why Dr Manhattan prefers to explode people?

A: I tried to find a source to back up my answer, but I failed to do so.
What I'll try to do here is to put myself in Dr. Manhattan's shoes.
So, we all know that Dr. Manhattan has a large apathy towards human values, his level of consciousness makes him have a very particular look at concepts like death, life, good, bad, and so on.
He definitely has some behaviors that us, mere humans, have as well, but when compared to the average human being, Manhattan displays a much higher level of detachment to "standard" human values.
That being said, for Manhattan, it doesn't matter if someone dies of cancer, flu, shot in the head, or exploded.

A live body and a dead body contain the same number of particles. Structurally, there's no discernible difference. Life and death are unquantifiable abstracts. Why should I be concerned?

That's a line from Dr. Manhattan himself.
What I think Dr. Manhattan is actually doing when he kills the mobsters in that particular scene (and also in the scenes where he kills Vietcongs) is severing the bonds between the molecules that constitute their bodies. For us, it looks like as they are exploding, but this is what might be actually happening.
Manipulating the bonding between molecules is the first thing he learns after his accident as Jon Osterman. Remember the sequence where he fails a couple of times before being able to fully reconstruct his body?
It looks like that for Manhattan, it's easier to sever the bonding between molecules than making that person turn into water or any other type of inorganic material.
I think that also it would take more effort from him to cause, let's say, a rupture in a few brain blood vessels from his victims. A much "cleaner" death, but from Manhattan's point of view, it achieves the same result as "exploding" them.


text:
Q: solr fieldcollapsing and maximum group.limit I'm using Solr 3.4 and FieldCollapsing. I would like to group all messages using FieldCollapsing.
Per default, every group contains only 1 message.
I can modify the numbers of documents per group by changing the Parameter group.limit.
That's a bit inconveniently for grouping all available messages to specific groups.
Is there a way to set group.limit to infinite?
The current workaround is to set group.limit to an very high value, which isn't an satisfying solution.

A: You can set group.limit to -1. Then you will get infinite documents per group.


text:
Q: Android Emulator v/s Phone I'm runnning an app that I've created that use the Google Maps API.
It works as expected on the emulator , that I'm using , however , the graphics seem to render in a different way on my phone.
Please see the following images for reference

Here's my activity.xml file
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:tools="http://schemas.android.com/tools"
                android:layout_width="match_parent"
                android:layout_height="match_parent" >

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:padding="@dimen/padding_medium"
    android:text="@string/hello_world"
    tools:context=".MainActivity" />

  <TextView
     android:id="@+id/textView1"
     android:layout_width="fill_parent"
     android:layout_height="30dp"
     android:background="@drawable/repeat"
     android:layout_marginTop="0dp"
     android:text=""
     android:textAppearance="?android:attr/textAppearanceLarge" />

   <com.google.android.maps.MapView
       android:id="@+id/mapView"
       android:layout_marginTop="30dp"
       android:layout_width="fill_parent"
       android:layout_height="fill_parent"
       android:enabled="true"
       android:clickable="true"
       android:apiKey="--private--" />

</RelativeLayout>

Why is the same image being observed differently - one on the device, and one on the emulator ?

A: For testing on real hardware you need to use a key different from the debug key. I think you are using a debug keystore.
Visit : https://developers.google.com/maps/documentation/android-api/v1/?csw=1#getfingerprint
Read that paragraph on google.
Is important that the application is exported as a signed application with the same key used for the google api (and NOT the debug key).
For create a valid read that paragraph:
Visit : http://developer.android.com/guide/publishing/app-signing.html#releasemode
and then use the same key to obtain the google maps api key.
Once you have the key for your application you can export a signed application by clicking with right button of your mouse on the project select Android Tools and then Export as a signed application package and follow the wizard (probably you can create a new key using that wizard).
hope that help.


text:
Q: How install PC-Probe II Software related to old asus motherboard in windows 10 Here is my motherboard's model in asus web site:
https://www.asus.com/SupportOnly/M3A78/HelpDesk_Download/
It is very old & i am so sorry about it.
I installed windows 10 on it recently.
Every thing is working very well on win 10.
But there was a nice & useful software related to my motherboard with the name of ASUS PC Probe II.
Check Utility part of my motherboard.
https://www.techspot.com/downloads/265-asus-pc-probe.html
pc probe ii asus windows 10
When i tried to install win 7 of that soft on win 10 i got an error.
This motherboard is very old and asus has no support on it any more.
It seems there is a new software in microsoft store with the name of
Probe II Sense.
I installed it and it does n't show any information such as cpu temperature.
I think before install ASUS PC Probe II i should install my motherboard's driver in win 10.
Here is the files of my motherboard (win 7):

What is AsAcpi.sys and how can i install it on win 10 without any damage?
Give me a solution to install ASUS PC Probe II because this software is very important for me.

My motherboard driver is ATK0110.
I found this link on the net :
https://www.catalog.update.microsoft.com/Search.aspx?q=ACPI%5CATK0110
But i do n't know is it safe to install this driver on win 10 or not & how can i install .sys & .ini file inside of that cab file in microsoft web site.

Here is PC Probe II error during install :

I copied those three files from microsoft web site's driver in System32 folder of windows 10 and did restart.
After restart i could n't install PC-Probe II again.


text:
Q: Can we use "Verb + ed" for future tense? Why Can't we use Verb+ed to tell future?
Example:

If he changed this in the future, his future will be xyz.

If suppose by mistake I changed this software code, will the employee get more salary next month?
Is above sentence construction is correct?

A: With changed, or were to change, you need would. This is a hypothetical situation.
The future would be "If I change the code, will the employee get more salary?

A: "Second" conditional:
= If he changed this, his future would be bright.
simple past in the first clause, would + infinitive in the second clause.
Also conditional ("first" conditional)
If you study this example, you will understand. [present tense + will + infinitive]
[There is no future in these examples as they are conditionals/]


text:
Q: Dynamically transform in css using ng-style I could not get transform to work when it's inside ng-style.
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>

    <link rel="stylesheet" href="style.css" />

Test

{{number}}

    <input type="number" ng-model="number" value=1>

Link: http://plnkr.co/edit/txSzAKxLDq48LVitntro?p=preview
If I change the input number the top div should change and spin at the same time. It should look like the word Test above it when it has value of 3.
So how to get transform to work in this case?
Thanks.

A: You can't use brace binding inside a JS string inside an attribute. You can append the variable onto the string instead:

{{number}}

Also, I replaced your double-quotes with singles.
However, you might consider adding a function to your controller to return the appropriate style:
Controller:
// Create a variable to store the transform value
$scope.transform = "rotate(0deg)";
// When the number changes, update the transform string
$scope.$watch("number", function(val) {
    $scope.transform = "rotate("+val+"deg)";
});

HTML:

{{number}}

Updated Plunker


text:
Q: geo application with php i am doing one concept.but i have no idea to do that concept. plz nybody give an idea for that....
actually there is a site which have the registered restaurents  on that site at the same another side user registration is there. now user login then automatically display distinct restaurents which is in that site. how to display distinct restaurents?
and next problem is administrator divided 3 jones . each jone having diffrent shipping charge. i mean  the distance between  restaurent  and user address is equall to with in  the one mile then charge one shipping charge. if there is a 2 miles distance between restaurent and user then charges another shipping charge?
how to do this...anybody give an idea for this problem...
thanks.

thanks to all for replys. first i have a small question. i want to create 2regions(region:1,shape:circle, distance:1km),(region:2,shape:circle, distance:2km) of origin.

A: I answered a question possibly related to this one a while back:
StackOverflow: Distance between two addresses

A: I'm not sure if I got your question right, but I think you might find Google Maps API useful, specifically XML/JSON Web services.


text:
Q: getuid/geteuid strange behaviour I've got a simple code, which basically looks like:
package main

import (
    "fmt"
    "golang.org/x/sys/unix"
)

func main() {
    fmt.Printf("real: %d, effective: %d\n", unix.Getuid(), unix.Geteuid())
}

Which basically outputs the real and effective user id. Now, once build with: go build main.go; I also call sudo chown root:root main && sudo chmod 4755 main to get -rwsr-xr-x permissions on the file.
If I understand the concept of the setuid bit (the s part), it allows me later to use setuid in the source file (noting, that I'll have to use either unix.Setreuid or unix.RawSyscall in conjunction with runtime.LockOSThread). Yet, the current compiled code no matter what always returns real: 1000, effective: 1000.
At first I thought that maybe it is the case with some Go code, double and tripple checked it, yet, result is still the same. Then I went further and made a mock up in c:
int main(int argc, char* argv){
   printf("real: %d, effective: %d\n", getuid(), geteuid());
   fflush(stdout);
}

Compiled, chown'ed to root:root, chmod'ed to 4755, and guess what? It still does the very same thing, it outputs real: 1000, effective: 1000.
So, if both: Go and C versions once compiled, properly changed in terms of permissions, return the same result: ignoring the setting, this is might to do something with system settings otherwise.
Update[0]: I've figured out that such a situation can be caused by a nosuid option for the mounted drive; so I've copied the executable to another drive, which doesn't have such an option. Still no effect.
So, what should I do:

*

*To fight that behavior?

*To detect such an environment in future?

Looking forward to see your suggestions.

A: More deep research of the nosuid option showed that the whole process, including the compilation has to happen on the drive mounted without nosuid option.
So, basically speaking, the steps to fight the issue are:

*

*Create a directory on a nosuid disabled drive;

*Ensure directory group is your group;

*Ensure directory group permissions have w option;

*Copy the source to this directory;

*go build within the directory;

*Apply chown root:root to the result;

*Apply chmod 4755 to the result;

*Enjoy the result from /nonosuid/directory/

And to detect environment you need to search for a destination without nosuid parameter during the installation.


text:
Q: What Rbac action/permission would allow Azure App Service Network Access Restrictions Which Rbac action would allow Azure App Service Network --> Access Restrictions ? We dont want every user to have auth to set/unset ip-rules using 'Networking --- Access Restrictions' for app-services.

A: I have tried to change the network access and I can get the action information from the brower.

So the action should between this:

You can use a custom role,
 $role = Get-AzRoleDefinition -Name "Virtual Machine Contributor"

 $role.Id =$null

 $role.Name = "testcustombowman"

 $role.Description = "111111111111111111111111111111111111111111111"

 $role.Actions.RemoveRange(0,$role.Actions.Count)

 $role.Actions.add("Microsoft.Web/sites/config/Read")

 $role.AssignableScopes.Clear()

 $role.AssignableScopes.Add("/subscriptions/xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx")

 New-AzRoleDefinition -Role $role

Have a look of this Offcial doc, and this.
But I still recommend you to use a simple way, directly give the relevant people only Read permissions.
It is highly recommended that you use the simple method, add role assignment -> Select Reader -> Select User
As you can see, the relevant users are unable to operate the settings you said in my case.


text:
Q: Angular material autocomplete not working, no errors shown I've implemented my autocomplete, no errors, everything seems ok however absolutely nothing happens. I enter something in the input field and no action seems to happen, nothing is shown in the console.
HTML
  <form>
    <mat-form-field>
      <input type="text" matInput [formControl]="myControl" [matAutocomplete]="auto">
    </mat-form-field>

    <mat-autocomplete #auto="matAutocomplete">
      <mat-option *ngFor="let n of testValues" [value]="n">
        {{n}}
      </mat-option>
    </mat-autocomplete>
  </form>

TS
import { MatAutocomplete } from '@angular/material/autocomplete';
import { FormControl } from '@angular/forms';
...
public testValues = ['one', 'two', 'three', 'four'];
public myControl: FormControl;
...
constructor() {
    this.myControl = new FormControl();
}

EDIT: I have imported
import {MatAutocompleteModule} from '@angular/material/autocomplete';

in my app module.
Version of material -
"@angular/material": "^5.0.0-rc.2",

A: You are missing a filter method in your .ts
You have to subscribe to your myControl valueChanges this way:
this.myControl.valueChanges.subscribe(newValue=>{
    this.filteredValues = this.filterValues(newValue);
})

So everytime your form control value changes you call your custom filterValues() method, that should look like:
filterValues(search: string) {
    return this.testValues.filter(value=>
    value.toLowerCase().indexOf(search.toLowerCase()) === 0);
}

So you use your testValues array as a base array, and your filteredValues array in your html:
<mat-option *ngFor="let n of filteredValues" [value]="n">
    {{n}}
</mat-option>

Filtering is not automatic, you have to use your custom method to filter the options. Hope it helps


text:
Q: How to provide RESTful web service(s) from WPF application? Typically a WPF application is a consumer/client of a RESTful service(s) on a web server. I would like to have it reversed - WPF application should be able to expose an web API. This would be consumed by an web app.
The flow:
web app ---sends a command to--> WPF app
** WPF app makes a 'long running job' until its user decides to stop **
WPF app ---passes data back to--> web app

The communication should be in Json format. I have prepared OpenAPI (in YAML) schema for it at the http://editor.swagger.io/. In the future it could be used to make changes to the WPF app's web API.
It allows to generate ASP.NET Core server c# code stub. What would be the requirements to run ASP.NET Core server in WPF and weither it would be light weight enough for use?
public static IWebHost BuildWebHost(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .Build();

// somewhere in the WPF app: BuildWebHost(args).Run();

The code is auto-generated by https://github.com/swagger-api/swagger-codegen.
There is a post which failed to integrate ASP.NET Core 2.x into WPF application. Unfortunatelly, ASP.NET Core 3.0 and later will only run on .NET Core.
I have some bits here and there but not a working concept. My options could be:

*

*Use a 3rd party framework or library. Should be able to use OpenAPI/YAML schema or Swagger generated server stub code etc.

*

*Could ServiceStack be the missing piece here?

*Integrate ASP.NET Core into WPF. Is it is even possible?

*Launch a separate web server (not a self-hosting) with web services from the WPF application. Sounds bad.

*Implement WCF web service(s) and requests.

*...

How to implement the web server/service(s) at WPF side? Maybe there is an existing 3rd party framework which could save me from reinventing the wheel?
PS. There is a similar question how to expose a restful service inside a WPF project but it is outdated.

A: This sounds like your requirement:

WPF application should be able to expose an web API. This would be consumed by an web app.

But then you're against the only solution that would make it possible:

Launch a web server with web services from the WPF application. Sounds bad.

I'm not sure how else you're expecting being able to expose a Web API without launching a web server? Inside a UI App you'd want to launch a self-hosted Service.
Self Hosting
In ServiceStack you can just start a self-hosted Service in your WPF App which can either be a self-hosted .NET Framework HTTP Listener or an ASP.NET Core on .NET Framework App. Both options Microsoft have said are going to be supported indefinitely, but .NET Framework is being phased out with ASP.NET Core 3.0 only going to run on .NET Core and .NET Framework stopping development at v4.x as .NET 5 is just going to be the next version of .NET Core.
But that shouldn't change what solutions are available to you now, if you need to run a Web Service in a WPF .NET Framework App you'll need to run a self-hosted .NET Framework HTTP Server which can either be a self-hosted HTTP Listener or ASP.NET Core (on .NET FX) App.


text:
Q: (initramfs) Terminal - Instead of Ubuntu login screen I've been using Ubuntu 12.04 LTS normally, but today when I turned my laptop on, and selected Ubuntu out of two options: Windows and Ubuntu, the following screen appeared:
Here's snapshot of the issue.

A: It seems like a filesystem error.You follow below steps it will help you sure:
1)Boot your machine with ubuntu live cd and select try ubuntu
2)Install Gparted application in it via internet
3)After installation open Gparted tool
4)Select your hard drive in Gparted tool and select first partition and right click and choose "check" option and then ok >> apply >> click on right symbol on top and done you have completed successfully.
5)Now boot your machine with your hard disk only.


text:
Q: See the file name and size within a (.Z) compressed file without uncompressing it I have tons of .Z compressed files scattered across various directores and need to see the size of the file within it. I don't plan on uncompressing all the .Z files. Is there a way to see the content (typically 1 file) the size of? I am aware of only zcat, which only cats the file.
Thanks!
Steve

A: The utility uncompress do not have the option to list the archive (and uncompressed size) like gzip. But you can decompress in memory and count the bytes of decompressed file like this:
uncompress -c archive.Z|wc -c


text:
Q: making jquery work in expressjs app It is a noobish question.
I am writing an expressjs app. I am not able to get jquery or bootstrap working.
// app.js
app.use(express.static(__dirname + '/public'));

Also tried
app.use(__dirname + '/public');
or
app.use(path.join(__dirname + '/public'))
or
app.set(__dirname + '/public');
or
app.set(path.join(__dirname + '/public'))

// views/home.html
<head>
    <script src="/js/jquery.min.js"></script>
</head>
<body>
<script>
    $(function(){
     alert('hello');
    });
</script>
</body>

//public>js>jquery.min.js
It is not working. I am using express 4.
Template works fine other than jquery
I have a need for this to work offline while writing this app, so can not use CDN
DIRECTORY STRUCTURE
    app.js
    views
    --layouts
    --partials
    public
    --js
    ----jquery.min.js

Using 'hbs' package, handlebars for templating
Thanks

A: Looks to me like you shouldn't be able to reach your view with your current setup. When you say app.use(express.static(__dirname + '/public'));, you are saying that when you hit http://{hostname}:{portNumber}, you'll be served content from the the /public folder. You shouldn't be able to access any resources on your file system that do not fall within the /public folder. So maybe if you set up a folder structure like:
app.js
--public
----views
------layouts
------partials
------home.html
----js
------jquery.min.js

that I think would work (assuming that your view.html still points to jquery.js in the folder structure correctly).


text:
Q: Capistrano no access to directory When I'm trying to enable systemd service I got
DEBUG[a8223480] Command: ( /usr/bin/env sudo systemctl enable /etc/systemd/system/api.service )
cap aborted!
SSHKit::Runner::ExecuteError: Exception while executing on host MY_IP: sudo exit status: 1

The same happens when I manually try to:
execute :sudo, :ln, '-s', '/etc/systemd/system/api.service', '/etc/systemd/system/multi-user.target.wants/api.service'

or even when I touch file in /etc/systemd/system/multi-user.target.wants/ directory.
However when I log in to my server I can execute any of above command.
Where is the problem?


text:
Q: Jquery remove and add new class in list I'm new here. So maybe this is a silly question. I have a CSS code below:

Cover

About

CV

Contact

So now when I click to "About", the class "about" will be changed to "active". Similiar with other rows. And how to avoid duplicate the class "active"?
My jQuery code below but nothing happens:
$('#nav.about a').click(function() {
   $('#nav.about a').removeClass('about').addClass('active');
});

Thanks in advance for any helps.
Cheers.

A: Your selector is wrong, the selector #nav.about a looks for an a element that's a child of an element with both the id of nav and the class of about. For your HTML, you're looking for: #nav a.about'; giving the jQuery:
$('#nav a.about').click(function() {
   $(this).removeClass('about').addClass('active');
});

With regards to the question added, in the comments (below):

[How to avoid the class "active" which is selected many times? ...when I clicked "About", this class set to "active"; also when I clicked "Contact", this class set to "active" too. So I want to limit only one "active" class at same time.

To achieve this, simply select the element(s) with that class-name within the click() method, as below:
$('#nav a.about').click(function() {
   $('#nav a.active').removeClass('active');
   $(this).removeClass('about').addClass('active');
});

References:

*

*CSS Selectors.

A: change $('#nav.about a') to $('#nav a.about')
$('#nav.about a').click(function() {
   $('#nav a.about').removeClass('about').addClass('active');
});

A: You need to change your selector. What you have is saying find me an anchor element that is a descendant of an element with ID nav AND class about". What you want is below, which says "find me an anchor tag with class about that is a descendant of the element with ID nav:
$('#nav a.about').click(function() {
   $(this).removeClass('about').addClass('active');
});


text:
Q: Best way to split a string for the last space I'm wondering the best way to split a string separated by spaces for the last space in the string which is not inside [, {, ( or ". For instance I could have:
a = 'a b c d e f "something else here"'
b = 'another parse option {(["gets confusing"])}'

For a it should parse into ['a', 'b', 'c', 'd', 'e', 'f'], ["something else here"]
and b should parse into ['another', 'parse', 'option'], ['([{"gets confusing"}])']
Right now I have this:
def getMin(aList):
    min = sys.maxint
    for item in aList:
        if item < min and item != -1:
            min = item
    return min

myList = []
myList.append(b.find('['))
myList.append(b.find('{'))
myList.append(b.find('('))
myList.append(b.find('"'))
myMin = getMin(myList)
print b[:myMin], b[myMin:]

I'm sure there's better ways to do this and I'm open to all suggestions

A: You can use regular expressions:
import re
def parse(text):
    m = re.search(r'(.*) ([[({"].*)', text)
    if not m:
        return None
    return m.group(1).split(), [m.group(2)]

The first part (.*) catches everything up to the section in quotes or parenthesis, and the second part catches anything starting at a character in ([{".
If you need something more robust, this has a more complicated regular expression, but it will make sure that the opening token is matched, and it makes the last expression optional.
def parse(text):
    m = re.search(r'(.*?)(?: ("[^"]*"|\([^)]*\)|\[[^]]*\]|\{[^}]*\}))?$', text)
    if not m:
        return None
    return m.group(1).split(), [m.group(2)]

A: Matching vs. Splitting
There is an easy solution. The key is to understand that matching and splitting are two sides of the same coin. When you say "match all", that means "split on what I don't want to match", and vice-versa. Instead of splitting, we're going to match, and you'll end up with the same result.
The Reduced, Simple Version
Let's start with the simplest version of the regex so you don't get scared by something long:
{[^{}]*}|\S+

This matches all the items of your second string—the same as if we were splitting (see demo)

*

*The left side of the | alternation matches complete sets of {braces}.

*The right side of the | matches any characters that are not whitespace characters.

It's that simple!
The Full Regex
We also need to match "full quotes", (full parentheses) and [full brackets]. No problem: we just add them to the alternation. Just for clarity, I'm throwing them together in a non-capture group (?: so that the \S+ pops out on its own, but there is no need.
(?:{[^{}]*}|"[^"]*"|\([^()]*\)|\[[^][]*\])|\S+

See demo.
Notes Potential Improvements

*

*We could replace the quoted string regex by one that accepts escaped quotes

*We could replace the brace, brackets and parentheses expressions by recursive expressions to allow nested constructions, but you'd have to use Matthew Barnett's (awesome) regex module instead of re

*The technique is related to a simple and beautiful trick to Match (or replace) a pattern except when...
Let me know if you have questions!

A: Perhaps this link will help:
Split a string by spaces -- preserving quoted substrings -- in Python
It explains how to preserve quoted substrings when splitting a string by spaces.


text:
Q: How to format a string using append.text concatenation? I am using a trackbar to adjust the value accordingly and the output is shown in a text box. I want to show the value with some text after it. The code I have used shows the text I want displayed however also shows this; i.e. slider moved to 200.
i.e. windowsforms.textbox.text: 200 °C
private void trackBar_Temp_Scroll(object sender, EventArgs e)
{
    Oven_Temp.Text = trackBar_Temp.Value.ToString();
    Oven_Temp.AppendText(Oven_Temp + "°C");
}

How comes the code shows the windows form section in the output with this code?

A: Your call to append the text should just be: Oven_Temp.AppendText("°C");
Better yet, use string concatenation to just do it all in one line:
Oven_Temp.Text = trackBar_Temp.Value.ToString() + "°C";
The problem is that you are including Oven_Temp inside your call to AppendText, which is the textbox object itself. So the type name of the textbox then shows up in your output.


text:
Q: Why &= operator doesn't work the same as && I'm just curious how java works. Can someone explain why getBoolean is called in Case 1 and not called in Case 2?
public class Main {

    public static void main(String[] args) {
        System.out.println("---------- Case 1 ----------");
        boolean b = false;
        b &= getBoolean(true);

        System.out.println("---------- Case 2 ----------");
        b = false;
        b = b && getBoolean(true);
    }

    private static boolean getBoolean(boolean bool) {
        System.out.println("getBoolean(" + bool + ") was called\n");
        return bool;
    }

}

Output:
---------- Case 1 ----------
getBoolean(true) was called

---------- Case 2 ----------

A: b &= a is a shortcut to b = b & a not to b = b && a
It is because of the difference between & and && operators.

*

*The & operator always evaluates both sides of conditions.

*The && operator evaluates the second only if needed.
So, getBoolean(true) will not run in the 2nd case.

A: In Case 2 getBoolean(true); is not evaluated, because the && is a short-circuit operator, e.g. if the expression will be false it stops evaluating
Case 1 just sets the result of the getBoolean() method to the b variable.

Update, thanks to @KisHan:
Note that b &= a is equal to b = b & a and not b = b && a

A: In second case b is false and for && if first condition is false it won't move ahead.
 b = b && getBoolean(true);//b is false

So &&(Logical AND) first checks the left side of the operation, if it's true than it continues  to the right side.
While &(Bitwise AND) operator evaluates both sides of expression as it's bitwise  AND operator.As it performs AND operation between leftside and right side.
So in first case it will be
b = b & getBoolean(true);//will perform AND operation to evaluate Expression

A: in first case it's bitwise and trying to get the assigned value (getBoolean()).
in second case the && does a short circuit evaluation. Where if first expression is false then the second won't evaluate.

in which the second argument is only executed or evaluated if the first argument does not suffice to determine the value of the expression:

b = b && getBoolean(true); // b already false and there is no use even getBoolean(true) is true or false , because the result is already false as b is false.

A: & means bitwise AND: on a bit-by-bit level, it sets the output to true if both of the input bits were true. && means logical AND: if both inputs are truthy, the expression returns true. && is also short-circuiting (stops evaluation and returns false immediately if the first input is falsy), which is what you're seeing here.


text:
Q: correlation heat map I want to make a heat map of correlated data and instead of getting the correlation scale from 0.85, I want it from 0.90. I need to know how can I tweak this scale.

The commands I am using are:
data<-read.table("data_corr", header=T)
tiff('corrheatmap.tiff')
library(gplots)
z<-cor(data)
lowColor = "purple" #change this if you want
highColor = "blue" #change this if you want
colorMin = 0 # I have made this 0.9 and also 90 in any case I don't see the difference
heatmap.2(z, Rowv=FALSE, Colv=FALSE, dendrogram="none", key=TRUE, density.info="none", trace="none", col=colorpanel(100, lowColor, highColor), scale="none", cexRow=0.15, cexCol=0.15)

A: Maybe I misunderstood your question, but I think you can use the breaks argument. For me it works like
heatmap.2(z, breaks = seq(0.9, 1, 0.001), Rowv=FALSE, Colv=FALSE, dendrogram="none", key=TRUE, density.info="none", cexRow = 0.15, cexCol = 0.15, col=colorpanel(100, lowColor, highColor), trace="none")


text:
Q: how do I test httpOnly cookie flag I have set the following property in websphere for the jsession cookie
    com.ibm.ws.webcontainer.HTTPOnlyCookies.
Any idea how best to test this using JavaScript in Firefox or IE?

A: Firebug - click on the Cookies tab

A: firecookie for firefox gives me the answer.

A: It's a pain in IE. I have IE9 so your screens may be different.
Press F12, go to the network tab, and then press Start Capturing. Back in IE then open the page you want to view. Back in the F12 window you show see all the individual HTTP requests, select the one that's the page or asset you're checking the cookies on and double click on it. You should then be able to see all the response headers and cookies on their relevant tabs.

Edit:
A HttpOnly Cookie would look something like this:
Set-Cookie: SessionId=z5ymkk45aworjo2l31tlhqqv; path=/; HttpOnly
The cookie may not be sent with every response, so you may need to clear all of your cookies and then try again to make sure one is sent with the request you're monitoring.

A: The easiest way to do it on Chrome or Firfox is as below:

*

*Open the page for instance somedomain.com

*Open dev tools by right clicking on page and then clicking on Inspect or Inspect Element

*Click on Network tab

*Click on any of the actual request and go to Headers section

*Now look for set-cookie in response headers
Here is the screenshot for details

A: add the following lines to your app
String
sessionid = request.getSession().getId();
response.setHeader("SET-COOKIE", "JSESSIONID=" + sessionid + "; secure; HttpOnly");


text:
Q: How do I import JavaScript files in Rails 3? I've just started working with Ruby on Rails, and I'm having some difficulty calling JavaScript functions from HTML. I'm using Rails 3.2.13, Ruby 1.9.3, and RubyMine 5.0.2.
I have a CoffeeScript file called "home.js.coffee" in "app/assets/javascripts/" that apparently compiles to "application.js" in the same folder. In "app/views/home/", I have the HTML file for the home page "index.html.erb". I have a function in "home.js.coffee" called cubes():
cubes = alert math.cube 3

This is really basic for now. I want to get comfortable first.
This is an object called math:
math =
    cube: (x) -> x* square x

I created a button in index.html.erb that should theoretically call this function:
<button onclick="cubes()">Try it</button>

The problem is getting it to find the JavaScript file. What needs to be in index.html's head? What needs to be in application.html's head?

A: The problem is that the function is in another scope. If you compile the CoffeeScript with the -b option, that will make the functions globally available, but the simple solution would be:
root = exports ? this
root.cubes = -> alert math.cube 3

and then you can call cubes() from your HTML.


text:
Q: Is there a RubyMotion free edition for Mac apps? RubyMotion now has a free starter edition for iOS and Android apps. Is there an equivalent free edition for devs building Mac OS X apps?

A: TLDR: Not yet, but HipByte (the vendor) does not object to the idea in principle.
Long answer, from an email exchange with Mark Villacampa of HipByte:
"On iOS and Android, the starter version adds a splash screen to the app that you can remove by purchasing a full license. On OSX, there is no equivalent of a launch image, so it is more difficult to control. In the future, we will look for ways to work around this limitation, and find an alternative way for OSX."


text:
Q: Measure of progress towards a proof Can one define some measure of progress towards a proof of a statement? I'm not sure if it's even possible for general first order logic statements so let's restrict ourselves to propositional statements. Assume for simplicity that we know if the statement in question is true or false beforehand.
Then if one is using the DPLL system for proving a propositional statement false (or true after taking the negation of the statement and trying to prove the unsatisfiability of that), then one can easily define a measure of progress towards the proof - if the statement has $n$ variables and we encounter failure after branching on $k$ variables, then we have made $2^{-k}$ fraction progress towards a proof of unsatisfiability.
If one works with the resolution proof system, then I can't think of a polynomial-time computable measure. For an exponential-time measure, one could examine all clauses derived so far and calculate what fraction of the search space they prune.
For more general proof systems which allow introducing new variables however (like the Extended Frege system, for instance), I can't think of any measure. (Edit: except in a very limited sense in which we explore the space of all possible proofs and then decide whether a particular step counted as progress towards a proof of unsat)
So my question is whether there exist better measures of progress towards a proof of unsatisfiability (or tautology) of a propositional formula than the ones above.
A relevant link might be this which talks about defining a measure of progress in terms of computing a function in terms of proving lower bounds. If we take the function to output 0 if the input formula is unsat and 1 if it is not, then it could be relevant to the measure in question above.

A: I'm not an all an expert on this, but here is what I hope is a relevant paper by Haim Gaifman:
Reasoning with limited resources and assigning probabilities to arithmetical statements
The paper describes how to develop a "local" logic involving a set of axioms and using modus ponens as the inference rule, from which one can assign probabilities to the event that arithmetical statements are true or false. This is very much along the lines of your stated intuition about satisfiability formulas and in fact he has an example concerning primality testing.

A: Vacuously it sounds unlikely that there is such a measure (i.e. that's polynomial time and tells you that you've made better than $2^{-O(n)}$ progress).  Otherwise you could follow a hill-climbing strategy and solve SAT in sub-exponential time.  I'd expect that the same thought occurred to you, i.e. that I'm not interpreting your question deeply enough.  It might help if you went into a bit more detail about what sorts of measures you'd consider acceptable, that wouldn't let you solve SAT sub-exponentially.


text:
Q: Value of state variable different inside useEffect hook (firestore onSnapshot callback) I am running into an issue where a state value (loadMore) inside a firestore's onSnapshot's callback is different to what it is when entering the hook, and I'm unable to understand why. Perhaps some smarter soul out there will be able to spot the problem:
   useEffect(() => {
     console.log("loadMore", loadMore); // returns false
     if (cursor) {
      onSnapshot(
        query(
          firestore
            .collectionGroup("posts")
            .orderBy("createdAt", "desc")
            .startAfter(cursor)
            .limit(POSTS_PER_REQUEST_LIMIT)
        ),
        (querySnapshot) => {
          console.log("loadMore", loadMore); // returns true
        }
      );
    }
    }, [cursor, loadMore]);

As you can see, the problem is that, as expected, loadMore === false when the useEffect hook is fired but the onSnapshot's callback function still believes it is true. Why? I will keep searching for answers but, in the meantime, will be questioning my own sanity. Thanks to anyone who can help.

A: It appears that onSnapshot's success listener has stale values. This can be because it's an outdated listener which needs to be unsubscribed from when one of the dependencies changes.
Firestore's onSnapshot returns a function that you can use to unsubscribe / clean up outdated callbacks.
You can return that function in useEffect and it should fix your issue:
useEffect(() => {
  if (cursor) {
   const unsubscribe = onSnapshot(
     query(
       firestore
         .collectionGroup("posts")
         .orderBy("createdAt", "desc")
         .startAfter(cursor)
         .limit(POSTS_PER_REQUEST_LIMIT)
     ),
     (querySnapshot) => {
       console.log("loadMore", loadMore); // should be correct now
     }
   );
   return unsubscribe;
 }
}, [cursor, loadMore]);

You can read more about effect cleanup in the React documentation: https://reactjs.org/docs/hooks-effect.html#effects-with-cleanup


text:
Q: how to write a web browser from stratch use c These days I'm aware of the powerful web browser. In order to know what happend behind the screen. I want to write a simple web browser. But When I try to find  document about that. Nothing find! Any one konw how to write a simple web browser or know where is the book will be useful. Please tell me !
Thank you very much!

A: Start off with a simple browser -- e.g., look at existing text only ones like lynx or w3m. Once you've got them cracked, then you can work up to adding graphical elements. It can get complicated fairly quickly, so make sure you've read the appropriate RFCs for HTTP and the W3C standards as well. These aren't light reading material though :-)

A: Here's something to get you started:
https://developer.mozilla.org/en/Download_Mozilla_Source_Code
C might not be the best language for this job.


text:
Q: Add class to parent if all childeren have class So I'm creating a progress bar, but I'm running into a little problem.
The rule I'm trying to implement:
for each li.page check if li.question = li.question.done, if true .addClass .done to this
So in the HTML below, #p1 should have class done, #p2 and #p3 shouldn't.
The current JS results in adding class .done to all .page li's in the page if one .page has all questions done.
Hope someone can help me get this to work, all help is appreciated!
This is the html:

1

2

3

4

5

6

And this JS:
var doneCheck = function(){
    $(".page").each(function () {
        questionsInPage = $(this).closest(".questions").find("li").length;
        questionsDone = $(this).closest(".questions").find("li.done").length;

        var done = questionsDone == questionsInPage;

        $(".page").each(function() {
            if (done) {
                $(this).parent().addClass('done');
            };
        });
    });
}

A: For each page I would check the number of li against the number of elements with class question and done. If they match set page to done.

var doneCheck = function() {
  $(".page").each(function() {
    if($('.question.done', this).length==$('ul li',this).length)
      $(this).addClass('done');
  });
}
doneCheck();

1

2

3

4

5

6

A: Instead of finding all the done questions, count the number of not done questions. If it's zero, all the questions are done. Use this to set the done property of the page.

function doneCheck() {
  $(".page").each(function() {
    var allDone = $(this).find(".questions li.question:not(.done)").length == 0;
    $(this).toggleClass("done", allDone);
  });
}

$("#check").click(doneCheck);
.page.done {
  background-color: green;
}

1

2

3

4

5

6

<button id="check">Check</button>

FYI, you can't use == to compare the results of two selectors. If you want to test whether they're equivalent, use .is:
if (questionsDone.is(questionsInPage)

But your second loop is wrong, because it sets the class on all .page elements based on the done status of the current page of the loop.


text:
Q: PHP saving sessions but My website was working fine till I rebooted my server. PHP is not saving sessions... well kinda. I can see the sessions in the session dir and new ones are made when people try to login but when I var dump $_SESSION I get array(0) { } I have tried chmoding the session folder, re installing php.
This is a dedicated server and not shared.
Any suggestions?
Thanks

A: I think this is what you mean:
Also if your wondering how long the default session lifetime (24 mins) is here is some more information:
PHP : What is the default lifetime of a session
<?php

    session_start();

    var_dump($_SESSION);

    $_SESSION['information'] = "Test information";

    var_dump($_SESSION);

?>

Output
array(0) { }
array(1) { ["information"]=> string(16) "Test information" }


text:
Q: How to define a controller with multiple parameters but only send one in CodeIgniter? He guys!
I am creating the next controller
function add($action,$data){

}

Wich gives me functionality for the next url:

controller/add/proyect/0

but this is a multiple purpose controller.
So, i need to call it like this:

controller/add/proyect

I dont want to send data, i just want to add the proyect.
when i do that, the compiler sends me the error:

Missing argument 1 for add()

This is what i tried:
function add($action,$data=null){

}

and
function add($action,$data=false){

}

But still not working.
Any ideas?

A: The two examples where you set a default for data should be working fine.  You don't need to set a default for all parameters.
Your issue probably lies within the function itself.  You might have the function set up to only return a value if $data is equal to something.  Do you have any lines in the function that say
if(!$data){

or maybe
if(empty($data)){

We definitely need to see the whole function before we can give you an answer why it's not working.


text:
Q: Editing Django formset data creating new records instead of updating Please Help!
I am trying to update a group of formsets that are related the main form (Project Information) by the main forms pk. The create form works fine, but I am finding it extremely difficult to implement the update version.
It's the save as an update part that I can't figure out for the formsets. The main form updates the database correctly. The formsets just create new records instead of updating the existing ones. I do not know how to instance the formsets.
Here the code.
view.py
@login_required
def edit_project(request):
    SampleInformationFormSet = formset_factory(SampleInformationForm, extra=1)
    DissolutionMethodsFormSet = formset_factory(DissolutionMethodsForm, extra=1)

    form = ProjectInformationForm(request.POST or None)
    si_formset = SampleInformationFormSet(request.POST or None, prefix='si')
    d_formset = DissolutionMethodsFormSet(request.POST or None, prefix='d')

    if request.method == 'POST':
        form = ProjectInformationForm(request.POST or None)
        si_formset = SampleInformationFormSet(request.POST or None, prefix='si')
        d_formset = DissolutionMethodsFormSet(request.POST or None, prefix='d')

        pi_pk = ''
        p = ''

        if form.is_valid():
            pi_pk = form.cleaned_data['hd']
            p = ProjectInformation.objects.get(pk=pi_pk)
            form = ProjectInformationForm(request.POST, instance=p)
            form.save()  # This form saves correctly

        for si_form in si_formset:
            si_form.save() # I do not know how to attach an instance to these formsets

        for d_form in d_formset:
            d_form.save()

            messages.success(request, 'Your project has been updated!')
            return redirect('edit_project')

        else:
            pass

        form = ProjectInformationForm(request.POST or None)
        si_formset = SampleInformationFormSet(request.POST or None, prefix='si')
        messages.warning(request, 'There was an error saving your form.')

    study_id_select = list(
        ProjectInformation.objects.values('dissolution_study_id', 'id').filter())

    context = {'form': form, 'si_formset': si_formset, 'd_formset': d_formset, 'study_id_select': study_id_select}
    return render(request, 'main/edit_project.html', context)

models.py   I'm just going to include part of three of the seven models to keep this a little shorter.
class ProjectInformation(models.Model):
    username = models.ForeignKey(User, on_delete=models.CASCADE)
    compound_code = models.CharField(max_length=60)
    product_type = models.ForeignKey(ProductType, on_delete=models.CASCADE)
    main_component = models.CharField(max_length=100)

class SampleInformation(models.Model):
    sample_index = models.CharField(max_length=30)
    sample_type_purpose = models.ForeignKey(SampleTypePurpose, on_delete=models.CASCADE)
    specification_number = models.CharField(max_length=20, blank=True, null=True)
    project = models.ForeignKey(ProjectInformation, on_delete=models.CASCADE, blank=True, null=True)

class DissolutionMethods(models.Model):
    number_of_methods = models.IntegerField(default=1,
                                            validators=[MaxValueValidator(10), MinValueValidator(1)],
                                            blank=True, null=True)
    dissolution_method_index = models.CharField(max_length=10)
    project = models.ForeignKey(ProjectInformation, on_delete=models.CASCADE, blank=True, null=True)

forms.py
class ProjectInformationForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['hd'] = forms.CharField(widget=forms.HiddenInput, required=False)

    class Meta:
        model = ProjectInformation
        fields = '__all__'

class SampleInformationForm(forms.ModelForm):
    class Meta:
        model = SampleInformation
        fields = '__all__'

Please help if you can. This project has been a trial by fire and the flames are hot!

A: Finally solved it myself.
@login_required
def edit_project(request):
    SampleInformationFormSet = formset_factory(SampleInformationForm, extra=1)
    DissolutionMethodsFormSet = formset_factory(DissolutionMethodsForm, extra=1)

    form = ProjectInformationForm(request.POST or None)
    si_formset = SampleInformationFormSet(request.POST or None, prefix='si')
    d_formset = DissolutionMethodsFormSet(request.POST or None, prefix='d')

    if request.method == 'POST':
        form = ProjectInformationForm(request.POST or None)
        si_formset = SampleInformationFormSet(request.POST or None, prefix='si')
        d_formset = DissolutionMethodsFormSet(request.POST or None, prefix='d')

        pi_pk = ''
        p = ''

        if form.is_valid():
            pi_pk = form.cleaned_data['hd']
            p = ProjectInformation.objects.get(pk=pi_pk)
            form = ProjectInformationForm(request.POST, instance=p)
            form.save()

        si = p.sampleinformation_set.all()  # All the Methods related to the instance
        d = p.dissolutionmethods_set.all()

        si_cnt = 0
        for si_form in si_formset:
            if si_form.is_valid():
               update = si_form.save(commit=False)
               update.pk = si[si_cnt].pk
               update.save()
               si_cnt += 1

        d_cnt = 0
        for d_form in d_formset:
            if d_form.is_valid():
                update = d_form.save(commit=False)
                update.pk = d[d_cnt].pk
                update.save()
                d_cnt += 1


text:
Q: Rigged Hilbert space and QM Are there any comprehensive texts that discuss QM using the notion of rigged Hilbert spaces? It would be nice if there were a text that went through the standard QM examples using this structure.

A: I don't know of any books which use this language exclusively, but the basic idea is pretty straightforward:
All Hilbert spaces are isomorphic (if their dimensions match).  This would present conceptual problems in quantum mechanics if we ever talked about the Hilbert space alone; how could we distinguish them?  But it's OK because we are actually interested in a Hilbert space $\mathcal{H}$ equipped with an algebra of operators $\mathcal{A}$.
For example, the real difference between $\mathcal{H} = L^2(\mathbb{R})$ and $\mathcal{H} = L^2(\mathbb{R}^3)$:  When we talk about the former, we're talking about $L^2(\mathbb{R})$ with the natural action of the 1d Heisenberg algebra $\mathcal{A}_1$ (generated  by $P$ and $Q$ such that $[Q,P] = i\hbar$).   When we talk about the latter, we're talking about the Hilbert space with the natural action of the 3d Heisenberg algebra $\mathcal{A}_3$.
Neither algebra actually acts on the entirety of $\mathcal{H}$.  $(Q\psi)(x)= x\psi(x)$ doesn't necessarily lie in $L^2$.  Likewise, the action of the differentiation operator $P = -i\hbar \frac{\partial}{\partial x}$ on a vector $v \in \mathcal{H}$ isn't defined if $v$ is not a differentiable function.  And $P^2$ is only defined on twice-differentiable functions.  However, there are some functions on which the action of any power $P^nQ^m$ is defined:  If $v$ and all of its derivatives vanish faster at infinity than any polynomial, the action of any element of $\mathcal{A}_1$ is defined.  Likewise, $\mathcal{A}_3$ really acts on the set $\mathcal{S}$ of functions in $L^2(\mathbb{R}^3)$ whose partial derivatives all vanish fast enough at infinity.
In general, if you have a Hilbert space and an algebra $\mathcal{A}$ of operators with continuous spectrum, there's a maximal subspace $\mathcal{S} \subset \mathcal{H}$ on which $\mathcal{A}$ acts.  This is the subspace of $v \in \mathcal{H}$ for which $av$ is defined and  $||a v|| < \infty$ for any $a \in \mathcal{A}$.  It is called the space of smooth vectors for $\mathcal{A}$.  (Exercise:  $\mathcal{S}$ is dense in $\mathcal{H}$.)
$\mathcal{S}$ gets a topology from being a subspace of $\mathcal{H}$, but it actually has a much stronger topology from the family of seminorms $v \mapsto ||a v||$ (for $a \in \mathcal{A}$).  This topology makes it a nuclear vector space.
Given $\mathcal{S} \subset \mathcal{H}$, you can construct the space $\mathcal{S}^* \supset \mathcal{H}$ of continuous (wrt the nuclear topology) complex-linear linear functionals on $\mathcal{S}$.  (Here we are using the Riesz representation theorem to identify $\mathcal{H}$ with its dual $\mathcal{H}^*$.)  This space should be thought of as the space of bras, in the Dirac bra-ket sense.  The bra $\langle x |$ is the linear function which maps $\psi \in \mathcal{S}$ to $\psi(x) =\langle x | \psi \rangle $, aka, the Dirac delta function $\delta_x$ with support at $x$.  (The space of kets is the conjugate space, consisting of conjugate-linear functionals on $\mathcal{S}$.  The ket $|x \rangle$ maps a state $\psi \in \mathcal{S}$ to $\psi^*(x) = \langle \psi| x\rangle$.)
This space $\mathcal{S}$ is worth considering because it gives rigorous meaning to the idea that elements of $\mathcal{A}$ with continuous spectrum have eigenvectors, and that you can expand some states in these eigenbases.  The elements of the algebra $\mathcal{A}$ can't have eigenvectors in $\mathcal{H}$ if they have continuous spectrum.  But they do have eigenvectors in the space of bras.   The definition is a standard extension-by-duality trick:  $v \in \mathcal{S}^*$ is an eigenvector of $a \in \mathcal{A}$ with eigenvalue $\lambda$ if $(av)(\psi) = \lambda v(a^*\psi)$ for all $\psi \in \mathcal{S}$.  (Exercise:  $\langle x|$ is the eigenbra with eigenvalues $x$ of the position operator $Q$.)
The triplet $(\mathcal{S}, \mathcal{H}, \mathcal{S}^*)$ is a rigged Hilbert space.  The language of rigged Hilbert spaces was invented to capture the ideas I've outlined above: the smooth vectors of an algebra of operators with continuous spectrum, and the dual vector space where the eigenbases of these operators live.  The language actually matches the physics very nicely -- especially the bra-ket formalism  --  but it provides a level of precision that's not really necessary for most calculations (e.g., with floating point arithmetic).

A: There aren't too many examples of rigged Hilbert spaces treated at length in the literature. I plan to write an article on the rigged Hilbert space approach to the Schroedinger hydrogen atom. You can use the PhD thesis by Rafael de la Madrid (http://galaxy.cs.lamar.edu/~rafaelm/dissertation.html) and all the articles here: https://scholar.google.com/citations?user=OqTexTYAAAAJ&hl=en


text:
Q: Manage Azure-Account within code Is it possible to mange an azure account within code? Like
var ac = new AzureAccount(name, password);
ac.CreateStorageAccount(name);
ac.CreateCoAdmin(name);
...

I already know about the Azure cmdlets, but that doesn't help.

A: You'll need to look at the Service Management API. There is an operation that allows you to create a storage account for example (comes with a C# example): Create Storage Account.
Adding a co-admin on the other hand won't be that simple. I believe there's support in the Service Management API to manage co-admins. If this is really important to you you can try to look at how the portal does it. You'll see that it executes 2 requests to add a co-admin to a subscription:

*

*Call https://manage.windowsazure.com/Users/GetPrincipalId with the email address of the new admin. This will return a "LiveID" (like 00053ACD9A5B316C).

*Call https://manage.windowsazure.com/Users/AddCoAdministrator with the email address, the LiveId, and information about the subscription to add the user.

This isn't documented and before even calling these services you'll need to manage authentication first.

A: Windows Azure accounts are created when user provide their personal information along with a financial source (i.e. Credit Card) which can pay the balance incurred by the services used by the specified user. Once you are logged into your account you can add more administration. This process is managed upto certain degree of control directly by the Windows Azure team and there is no API to automate these functionality for various reasons.
However once you have got a new Subscription to Windows Azure, you certainly can use REST API to exactly create new services (i.e Cloud Service, VM, Storage etc) which are available within your Subscription. To make it happen just create a new reference dll (or class) and add all the REST API to in and then use that reference (or class) to exactly call they way you want.


text:
Q: How do you associate an Azure web app with a vnet using PowerShell Az? I know it can be done using Azure CLI like this:
az webapp vnet-integration add -g $resourceGroupName -n $applicationName --vnet $vnetName --subnet $subnetName

Is there an equivalent command using PowerShell Az?

A: If you reference the docs at https://learn.microsoft.com/en-us/azure/app-service/web-sites-integrate-with-vnet, at the bottom is a link to the Script Center gallery where this is a full PS1 script at https://gallery.technet.microsoft.com/scriptcenter/Connect-an-app-in-Azure-ab7527e3 which shows how to integrate web app with vnet.
The final lines of interest (it uses AzureRM, but should be easy to convert to Az):
$PropertiesObject = @{
"vnetName" = $VirtualNetworkName; "vpnPackageUri" = $packageUri
}

New-AzureRmResource -Location $location -Properties $PropertiesObject -ResourceName "$($webAppName)/$($vnetName)/primary" -ResourceType "Microsoft.Web/sites/virtualNetworkConnections/gateways" -ApiVersion 2015-08-01 -ResourceGroupName $webAppResourceGroup -Force


text:
Q: Checking that Ragel matched the entire input Are there better ways to require that Ragel consume all of the input? Here is what I'm using now:
=begin
%%{
  machine my_lexer;
  # ...
  # extract tokens and store into `tokens`
  # ...
}%%
=end

class MyLexer

  %% write data;

  def self.run(string)
    data = string.unpack("c*")
    eof = data.length
    tokens = []
    %% write init;
    %% write exec;
    data.length == p ? tokens : nil
  end

end

Most of the above is boilerplate, except for the data.length == p test. It works -- except that it doesn't verify that the lexer ended in a final state. So, I have test cases that give me tokens back even if the entire input was not successfully parsed.
Is there a better way?
(Testing for the final state directly might work better. I'm looking into how to do that. Ideas?)

A: You can handle errors using either global or local error actions.
For global error actions you can use this syntax:
$!action

For local error actions, which are local to your machine definition, you can use this syntax:
$^action

If you put a flag on your action, you can check the flag to detect an error.

A: I'm only starting out with ragel, but it's possible you want to look at EOF actions or Error actions, executed respectively when the input ends or when the next character satisfies no transition from the current state.


text:
Q: Iptables not loading at boot I'm using Ubuntu 14.04 as a firewall with iptables.
I have a network interface like this:
iface lo inet loopback
        pre-up iptables-restore < /etc/iptables.rules

This method has been working for years, but not anymore. My firewall is up to date.
I also enabled logging:
iface lo inet loopback
        pre-up iptables-restore < /etc/iptables.rules > /var/log/iptables-boot.log

but it's empty.
I also tried it with a script at  /etc/network/if-up.d/script:
#!/bin/sh
iptables-restore < /etc/iptables.rules >> /var/log/iptables_boot.log
echo "iptables loaded" >> /var/log/iptables_boot.log

Where, the logfile only contains "iptables loaded" but nothing else. That means the script runs, but no iptables rules are added to the kernel.
Any ideas?
thanks!

A: I am not sure why your iptables configuration is not loading. It could be because you are using domain names, rather then ip address
IMO easiest "solution" is to use iptables-persistent
First, configure or load your rules (you will be asked to save the current set of rules as a part of the install)
Then run
sudo apt-get -y install iptables-persistent

For additional information, including modifying your rules in the future,  See
 http://www.microhowto.info/howto/make_the_configuration_of_iptables_persistent_on_debian.html
and (for ip address vs. domain name)
iptables-persistent doesn't load rules on boot


text:
Q: How to call a PHP function from CLI? Let's say I have a private function addUser() in function.php that takes $username as an input variable and does some stuff:
function addUser($username) {

//do some stuff

}

Now I want to call this function and pass the value $username, if possible with PHP CLI. I guess that won't work from outside function.php since it's private, but how could I do this then?

A: php -r 'include("/absolute/path/to/function.php"); addUser("some user");'

This should work. Because you are basically executing all that code in between 's. And in that you can include function.php and, should appropriately call addUser().
see phpdoc.

A: You get your command line argumenst passed in a argv array:
function addUser($username) {

//do some stuff

}

addUser( $argv[1] );

A: You can use $argv.  $argv[0] = the filename, $argv[1] = first thing after filename.
I.e. php function.php "some arg"
would be addUser("some arg");

A: function funcb()
{
    echo 'yes';
}

if (php_sapi_name() === 'cli') {
    if (count($argv) === 1) {
        echo 'See help command'.PHP_EOL;
        exit();
    }

    if (function_exists($argv[1])) {
        $func = $argv[1];
        array_shift($argv);
        array_shift($argv);
        $func(...$argv);
    }
}

This works for me!


text:
Q: Riemann integration and equality ae Let $f,g:[a,b] \to \mathbb{R}$ be Riemann integrable functions such that $f = g$ a.e. (with respect to Lebesgue outer measure). Then how would one show that $\int f = \int g$ as Riemann integrals? For Lebesgue integrals it's clear enough, but I don't know how to procede for Riemann integrals.
I suppose it would be helpful to first show that if some function $h$ is Riemann integrable and $h=0$ a.e. then the Riemann integral $\int h = 0$. But I don't know how to show that.
Edit: Assume that we don't know anything about Lebesgue integration at this point.

A: Suppose $h$ is Riemann integrable on $[a,b]$ and vanishes except on a set of measure zero.  Consider any partition $P$ of $[a,b]$.  Then the upper sum $U(h,P)$ is $\ge 0$, because no interval of $P$ has measure zero.  Similarly the lower sum $L(h,P)$ is $\le 0$.  By Riemann-integrability, the Riemann integral is $0$.

A: If $h$ is Riemann integrable it is Lebesgue integrable, and the two integrals agree. But if $h=0$ a.e. (with respect to Lebsgue measure) then it's Lebesgue integral is $0$. Since the Riemann integral equals the Lebesgue integral, the Riemann integral is also $0$.


text:
Q: Is R an equivalence relation ? if yes, how? $a$ is related to $b$ ($a\mathrel{R} b$) if and only $a\cdot b > 0$ over the set of non-zero rational numbers.  Is $R$ an equivalence relation? If yes how?

A: Reflexive: For any non-zero rational $x$ we have $x^2 \geq 0$.
Symmetric: Multiplication is commutative, done.
Transitive: If $xRy$ and $yRz$, then all of $x, y, z$ have the same sign and hence $xRz$, and we are done.
This really just uses the properties of multiplication we know for $\mathbb{Q}$. Nothing too involved here.

A: Maybe the quickest way to do this is to notice that $ab>0$ if and only if $a$ and $b$ are either both positive or both negative, so there you have a partition of the set.


text:
Q: Can't stop the particles from overshooting I am trying to create a simple particle simulation. There are two types of particles static and moving. Static particles attract moving particles towards their centre. Static particles have a strength attribute which dictates how hard they are pulling the moving particles
var angle:Number = Math.atan2(moving.y - static.y , moving.x - static.x);
var dist = Point.distance(new Point(moving.x,moving.y) , new Point(static.x,static.y));

moving.velX += Math.cos(angle + Math.PI) * static.strength / dist;
moving.velY += Math.sin(angle + Math.PI) * static.strength / dist;

The problem is a when a particle is just passing through the centre the distance is very small that results in very large velocity values.
I added an extra check for distance before calculating velocity.
if (dist < 1)
    dist = 1;

But the problem still persists. I cant figure out the problem.
Here is a snapshot of an overshoot happening.

A: You are probably declaring that dist value before running the dist calculation or after running the vel calculation. Instead, make sure that the dist check you are doing is between the dist calculation and the vel calculation. Vesper is correct as well, in that to get the correct force effect, it should use the distance squared. But even doing that, you can still get undesirable (although completely accurate, mathematically) results.
var angle:Number = Math.atan2(moving.y - static.y , moving.x - static.x);
var dist = Point.distance(new Point(moving.x,moving.y) , new Point(static.x,static.y));

if (dist < 1) dist = 1; // just make sure your constraint goes here.

moving.velX += Math.cos(angle + Math.PI) * static.strength / dist / dist; // this uses dist squared
moving.velY += Math.sin(angle + Math.PI) * static.strength / dist / dist; // but don't use this method in addition to Vesper's or you'll have dist to the power of 4.

A: Normal force fields use square of distance as modifier, you here use single power of distance, of course the force field performs differently. You should change the var dist line to the following:
var dist:Number = (moving.x-static.x)*(moving.x-static.x) + (moving.y-static.y)*(moving.y-static.y);

This way dist will hold square of actual distance, so dividing by dist would give you the proper force field configuration.
And, please rename static, as it's a reserved word in AS3.