text:
Q: merge objects in same array based on common value in Javascript I have an array:
[
  {
    assignmentId:17,
    email:"john.smith@email.com"
    expectation: "Make sure to proofread!",
    firstName:"John"
    id:23
    ignoreForFeedback: true
    lastName:"Smith"
    level:2
    levelFraction:null
    score:35
  },
  {
    assignmentId:17
    countsPerCategory: Array(4)
    email:"john.smith@email.com"
    firstName:"John"
    frequentErrors: Array(5)
    id:23
    ignoreForGrading: true
    lastName:"Smith"
  },
  {
    assignmentId:17,
    email:"cl@email.com"
    expectation: "cite sources",
    firstName:"Cindy"
    id:45
    ignoreForFeedback: true
    lastName:"Lee"
    level:2
    levelFraction:null
    score:32
  },
  {
    assignmentId:17
    countsPerCategory: Array(4)
    email:"cl@email.com"
    firstName:"Cindy"
    frequentErrors: Array(5)
    id:45
    ignoreForGrading: true
    lastName:"Lee"
  }
]

I want to combine the Objects with the same 'id' into the same object within the array. Their common keys should also be combined (eg: 'firstName', 'email'). Can someone suggest the best way to do this? Either with ES6 or Lodash

A: You can use lodash#groupBy to group all items in the array by id and then use lodash#map with an iteratee of lodash#assign that is wrapped with a lodash#spread to make the array callback as a list of arguments for lodash#assgin.
var result = _(array)
  .groupBy('id')
  .map(_.spread(_.assign))
  .value();

var array = [
  {
    assignmentId:17,
    email:"john.smith@email.com",
    expectation: "Make sure to proofread!",
    firstName:"John",
    id:23,
    ignoreForFeedback: true,
    lastName:"Smith",
    level:2,
    levelFraction:null,
    score:35
  },
  {
    assignmentId:17,
    countsPerCategory: Array(4),
    email:"john.smith@email.com",
    firstName:"John",
    frequentErrors: Array(5),
    id:23,
    ignoreForGrading: true,
    lastName:"Smith"
  },
  {
    assignmentId:17,
    email:"cl@email.com",
    expectation: "cite sources",
    firstName:"Cindy",
    id:45,
    ignoreForFeedback: true,
    lastName:"Lee",
    level:2,
    levelFraction:null,
    score:32
  },
  {
    assignmentId:17,
    countsPerCategory: Array(4),
    email:"cl@email.com",
    firstName:"Cindy",
    frequentErrors: Array(5),
    id:45,
    ignoreForGrading: true,
    lastName:"Lee"
  }
];

var result = _(array)
  .groupBy('id')
  .map(_.spread(_.assign))
  .value();

console.log(result);
body > div { min-height: 100%; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>

Here's an alternative solution that uses Array#filter which takes advantage of the 2nd argument of the Array#filter which gives context to the filter's callback function. We use the this context as a mechanism to store cached objects by their id and then use this to decide whether to retain these objects from the array or not.
var result = array.filter(function(v) {
  return this[v.id]?
    !Object.assign(this[v.id], v):
    (this[v.id] = v);
}, {});

var array = [
  {
    assignmentId:17,
    email:"john.smith@email.com",
    expectation: "Make sure to proofread!",
    firstName:"John",
    id:23,
    ignoreForFeedback: true,
    lastName:"Smith",
    level:2,
    levelFraction:null,
    score:35
  },
  {
    assignmentId:17,
    countsPerCategory: Array(4),
    email:"john.smith@email.com",
    firstName:"John",
    frequentErrors: Array(5),
    id:23,
    ignoreForGrading: true,
    lastName:"Smith"
  },
  {
    assignmentId:17,
    email:"cl@email.com",
    expectation: "cite sources",
    firstName:"Cindy",
    id:45,
    ignoreForFeedback: true,
    lastName:"Lee",
    level:2,
    levelFraction:null,
    score:32
  },
  {
    assignmentId:17,
    countsPerCategory: Array(4),
    email:"cl@email.com",
    firstName:"Cindy",
    frequentErrors: Array(5),
    id:45,
    ignoreForGrading: true,
    lastName:"Lee"
  }
];

var result = array.filter(function(v) {

  // does this `id` exist?
  return this[v.id]?

    // assign existing object with the same id
    // from the `this` cache object. Make sure
    // to negate the resulting object with a `!`
    // to remove this value from the array
    !Object.assign(this[v.id], v):

    // Assign the value from the `this` cache.
    // This also retains this value from the existing
    // array
    (this[v.id] = v);

}, {});

console.log(result);
body > div { min-height: 100%; top: 0; }

A: You can use JavaScript's built in Array.reduce() method. The idea is you can create a map with the IDs and use lodash.merge() method (or whatever method you choose for merging objects) to merge all of the objects with the same ID into a single object. Then you can use .map() on the idMap you created to get the objects back into a single array.

    var data = [{
        assignmentId: 17,
        email: "john.smith@email.com",
        expectation: "Make sure to proofread!",
        firstName: "John",
        id: 23,
        ignoreForFeedback: true,
        lastName: "Smith",
        level: 2,
        levelFraction: null,
        score: 35
      },
      {
        assignmentId: 17,
        countsPerCategory: Array(4),
        email: "john.smith@email.com",
        firstName: "John",
        frequentErrors: Array(5),
        id: 23,
        ignoreForGrading: true,
        lastName: "Smith"
      },
      {
        assignmentId: 17,
        email: "cl@email.com",
        expectation: "cite sources",
        firstName: "Cindy",
        id: 45,
        ignoreForFeedback: true,
        lastName: "Lee",
        level: 2,
        levelFraction: null,
        score: 32
      },
      {
        assignmentId: 17,
        countsPerCategory: Array(4),
        email: "cl@email.com",
        firstName: "Cindy",
        frequentErrors: Array(5),
        id: 45,
        ignoreForGrading: true,
        lastName: "Lee"
      }
    ];

    var idMap = data.reduce(function(result, current) {
      if (result[current.id] == null) {
        result[current.id] = current;
      } else {
        _.merge(result[current.id], current);
      }

      return result;
    }, {});

    var results = Object.keys(idMap).map(function(key) {
      return idMap[key];
    });

    console.log(results);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>

A: What I can suggest is to use a combination of forEach() and some() methods to iterate the array elements and test if the iterated object id is already processed or not.
This is the solution:
var merged = [];

arr.forEach(function(item) {
  var idx;
  var found = merged.some(function(el, i) {
    idx = el.id === item.id ? i : null;
    return el.id === item.id;
  });
  if (!found) {
    merged.push(item);
  } else if (idx !== null) {
    for (k in Object.keys(item)) {
      if (item.hasOwnProperty(k)) {
        merged[idx][k] = item[k];
      }
    }
  }
});

Working Demo:

var arr = [{
    assignmentId: 17,
    email: "john.smith@email.com",
    expectation: "Make sure to proofread!",
    firstName: "John",
    id: 23,
    ignoreForFeedback: true,
    lastName: "Smith",
    level: 2,
    levelFraction: null,
    score: 35
  },
  {
    assignmentId: 17,
    countsPerCategory: [],
    email: "john.smith@email.com",
    firstName: "John",
    frequentErrors: [],
    id: 23,
    ignoreForGrading: true,
    lastName: "Smith"
  },
  {
    assignmentId: 17,
    email: "cl@email.com",
    expectation: "cite sources",
    firstName: "Cindy",
    id: 45,
    ignoreForFeedback: true,
    lastName: "Lee",
    level: 2,
    levelFraction: null,
    score: 32
  },
  {
    assignmentId: 17,
    countsPerCategory: [],
    email: "cl@email.com",
    firstName: "Cindy",
    frequentErrors: [],
    id: 45,
    ignoreForGrading: true,
    lastName: "Lee"
  }
];
var merged = [];

arr.forEach(function(item) {
  var idx;
  var found = merged.some(function(el, i) {
    idx = el.id === item.id ? i : null;
    return el.id === item.id;
  });
  if (!found) {
    merged.push(item);
  } else if (idx !== null) {
    for (k in Object.keys(item)) {
      if (item.hasOwnProperty(k)) {
        merged[idx][k] = item[k];
      }
    }
  }
});
console.log(merged);

A: Thank you for your help everyone, but I ended up going with my own implementation.
        let ids = [];
        let combinedUsers = [];

        users.forEach(function (user) {
            ids.push(user.id);
        });

        ids = _.uniq(ids);
        ids.forEach(function(id){
            let user = users.filter(function(userObj){
                return id === userObj.id
            });

            if(user.length > 1){
                user = Object.assign(user[0], user[1]);
                combinedUsers.push(user);
            } else {
                combinedUsers.push(user[0]);
            }

        });
        return combinedStudents;


text:
Q: Filldraw square in tikz I am trying to filldraw a square with sides 7sqrt(7). I am not getting the desired output.
\begin{tikzpicture}
\filldraw(0,0) rectangle (7*\sqrt{7},7*\sqrt{7});
\end{tikzpicture}

A: \documentclass[tikz, border=1cm]{standalone}
\begin{document}
\begin{tikzpicture}
  \filldraw(0,0) rectangle ({7*sqrt(7)},{7*sqrt(7)});
\end{tikzpicture}
\end{document}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python script to check ROOT SSL Certificate I want to write a script that can verify a root CA certificate from its subordinate CA. Currently, I can only return the lowest level certificate.
(For example, if you view the certification path for this web page, the script would return the certificate issued by R3, but I need to get the ISRG Root X1.)
Some of the code I'm using to pull a certificate from a hostname is as follows:
'''
def get_certificate(hostname, port):
hostname_idna = idna.encode(hostname)
sock = socket()

sock.connect((hostname, port))
peername = sock.getpeername()
ctx = SSL.Context(SSL.SSLv23_METHOD) # most compatible
ctx.check_hostname = False
ctx.verify_mode = SSL.VERIFY_NONE

sock_ssl = SSL.Connection(ctx, sock)
sock_ssl.set_connect_state()
sock_ssl.set_tlsext_host_name(hostname_idna)
sock_ssl.do_handshake()
cert = sock_ssl.get_peer_certificate()
crypto_cert = cert.to_cryptography()
sock_ssl.close()
sock.close()

return HostInfo(cert=crypto_cert, peername=peername, hostname=hostname)

def get_common_name(cert):
try:
    names = cert.subject.get_attributes_for_oid(NameOID.COMMON_NAME)
    return names[0].value
except x509.ExtensionNotFound:
    return None

def get_issuer(cert):
try:
    names = cert.issuer.get_attributes_for_oid(NameOID.COMMON_NAME)
    return names[0].value
except x509.ExtensionNotFound:
    return None

'''
I'm not sure how to climb the chain of authority to find the ROOT CA from its subordinate levels.
Does anyone know how to return the root/tier 1 CA from its tier 2 or 3 certs?


text:
Q: Understanding a metric with prescribed range I have the following question in my book:

Show that any subset $A$ of the set of non negative reals with $0 \in A$, is the set of all distances between points of some metric spaces.

And the solution is given to be:
For a given set $A$ of non negative reals with $0 \in A$ , we define a function $ d: A \times A \rightarrow \mathbb R$ by  $$ d(x,y) =
 \begin{cases}
\text{max}\{x,y\}, & \text{if}  x \neq y \\
0 , & \text {if} x=y
\end {cases}
$$
Then $d$ is clearly a Metric on $A$ and for any $x \in A$ , $d(0,x) = x$ ; also for any $x , y \in A $ , $d(x,y) = \text{max}(x,y)$ or $0$ so that $d(x,y) \in A$. Thus $(A,d)$ is the required metric space.
Now my question is: Is the metric taken in the solution fixed? Can we take any other metric e.g the usual metric or any other metric on $A$?
My next question is there any special significance of the 'max' metric used in the solution on any space? By special I mean like the usual metric is the usual distance between points in the co-ordinate plane, such as if this metric has any significance.

A:
Is the metric taken in the solution fixed?

If you mean "is it unique", the answer is no. For example, take any bijection $\varphi:A\to A$ and let $d_\varphi(x,y) = \max(\varphi(x), \varphi(y)) $ for $x\ne y$.  More generally, let $B$ be any set of the same cardinality as $A$ and define $d_\varphi$ on $B$ as above, using a bijection $\varphi:B\to A$. This is described as "pulling a metric back by $\varphi$".
Also, the underlying set need not have the same cardinality as $A$. Given any set $X$, we can define a metric on $A\times X$ by
$d((a,x),(a',x'))=\max (a,a')$ unless $(a,x)=(a',x')$. In particular, we  can put such a metric on $A\times \mathbb{R}$ and then pull it back to $\mathbb{R}$ by some bijection $\mathbb{R}\mapsto A\times \mathbb{R}$.

any special significance of the 'max' metric

It has a reasonable interpretation as the required fuel capacity of a plane that has to fly from $x$ to $y$ with a required stopover at $0$, where it is refueled.
It's also an example of a ultrametric, meaning $d(x,y)\le \max(d(x,z), d(y,z))$. Absent any assumptions on the structure of $A$, we pretty much have to use an ultrametric: given that we must have a triangle with two side length $a,b\in A$, what should the third sidelength of the triangle be? We don't know if any other elements of $A$ (if they even exist) can fit the triangle inequality. Using the smaller of $a,b$ risks violating the triangle inequality, if it happens to be less than half of the larger. So the only safe choice is to have the third side be $\max(a,b)$. Hence, an ultrametric. Notice that $\max$ function comes up naturally here.


text:
Q: How to increase size of ggplot - squeezed horizontal bar chart I'm trying to plot some values against US states in a horizontal bar chart in GGPlot.
The code is:
g <- df %>%
  select(Sample.Measurement, State.Name) %>%
  group_by(State.Name) %>%
  count() %>%
  arrange(n) %>%
  ggplot(., mapping = aes(x=reorder(State.Name, n), y =n))+
  geom_bar(stat = "identity", width=.8, position = position_dodge(width = .25))+
  labs(
    title = "",
    y= "Frequency"
  )+
  coord_flip()

g+theme(axis.text=element_text(size=20),
        axis.title=element_text(size=30,face="bold"))

The theming element was in a bid to change the text size.
What I really want to do is extend the depth of the chart so that the individual states have more space. How do I do that?

A: Edit the chunk options, namely fig.height and fig.width.
e.g.
```{r fig.height = 10, fig.width = 5}
#your plot code
```


text:
Q: Why can't I control the click event of this link with jQuery? I know jQuery pretty well. This one is driving me nuts because it's SO simple.
I have this in the :

and in the body I have a series of links:
Delete

But EVERY time I click those links, it takes me right ot that PHP page. Why isn't jQuery intercepting the click? Any theories?
PS I've tried adding a simple alert() event to the click() function, with no change, and I've tried using "a.delete_social" in the jQuery $() call. Neither worked.

A: Try this to prevent the URL from loading:
$(".delete_social").click(function(e) {
    e.preventDefault();
    return false;
});

Also, you should be getting an alert and other code to run inside the click handler. If it's not, then something else on the page is causing something weird to occur.

A: If these links are loaded in dynamically, you'll need to use $.live() to control them:
$(".delete_social").live("click", function(e){
  e.preventDefault();
  // do stuff
});

$.live() causes dynamically-added elements to adhere to previously-declared rules.

A: Here's a couple of questions I'd ask while debugging:

*

*Are you sure the click event is being attached to the anchors?

*

*Try moving your script take to the bottom of the page and attaching the click events without using the ready function.

*Is $(".delete_social").length greater than 0?

*Are there any JavaScript errors when I load the page?

*Is jQuery loading correctly?

*

*Does $.fn.jquery return the current version of jquery you're using?

*Consider using event.preventDefault(); instead.

A: Try this:

A: Check the rest of your javascript. return false; or .preventDefault(); should do the trick. If they're not working, it usually means there's an error somewhere else in your js, and your browser never gets to that line of code.


text:
Q: In Node, delete all files older than an hour? I want to delete any files older than an hour.  This is for automatically cleaning up a tmp uploads directory.
Here is my code:
fs.readdir( dirPath, function( err, files ) {
    if ( err ) return console.log( err );
    files.forEach(function( file ) {
        var filePath = dirPath + file;
        fs.stat( filePath, function( err, stat ) {
            if ( err ) return console.log( err );
            var livesUntil = new Date();
            livesUntil.setHours(livesUntil.getHours() - 1);
            if ( stat.ctime < livesUntil ) {
                fs.unlink( filePath, function( err ) {
                    if ( err ) return console.log( err );
                });
            }
        });
    });
});

However this just deletes everything in the directory, regardless of whether or not it was uploaded over an hour ago.
Am I misunderstanding how to check the age of the file in Node?

A: Simple recursive solution only del all files !dirs run every 5 hours del older files that 1 day
const fs = require('fs');
const path = require('path');

setInterval(function() {
    walkDir('./tmpimages/', function(filePath) {
    fs.stat(filePath, function(err, stat) {
    var now = new Date().getTime();
    var endTime = new Date(stat.mtime).getTime() + 86400000; // 1days in miliseconds

    if (err) { return console.error(err); }

    if (now > endTime) {
        //console.log('DEL:', filePath);
      return fs.unlink(filePath, function(err) {
        if (err) return console.error(err);
      });
    }
  })
});
}, 18000000); // every 5 hours

function walkDir(dir, callback) {
  fs.readdirSync(dir).forEach( f => {
    let dirPath = path.join(dir, f);
    let isDirectory = fs.statSync(dirPath).isDirectory();
    isDirectory ?
      walkDir(dirPath, callback) : callback(path.join(dir, f));
  });
};

Source of function

A: I've used find-remove for a similar usecase.
According to the documentation and what you are trying to do, the code will be:
var findRemoveSync = require('find-remove');
findRemoveSync(__dirname + '/uploads', {age: {seconds: 3600}});

I'm actually running that every 6 minutes and deleting files older than 1 hour by doing:
setInterval(findRemoveSync.bind(this,__dirname + '/uploads', {age: {seconds: 3600}}), 360000)

See this example on how I'm using find-remove to cleanup the /uploads folder.

A: I am using rimraf to recursively delete any file/folder that is older than one hour.
According to the docs, you should use getTime() on the ctime Date object instance in order to compare.
var uploadsDir = __dirname + '/uploads';

fs.readdir(uploadsDir, function(err, files) {
  files.forEach(function(file, index) {
    fs.stat(path.join(uploadsDir, file), function(err, stat) {
      var endTime, now;
      if (err) {
        return console.error(err);
      }
      now = new Date().getTime();
      endTime = new Date(stat.ctime).getTime() + 3600000;
      if (now > endTime) {
        return rimraf(path.join(uploadsDir, file), function(err) {
          if (err) {
            return console.error(err);
          }
          console.log('successfully deleted');
        });
      }
    });
  });
});

A: It looks like you're comparing whatever "stat.ctime" is to the entire Date object.
if ( stat.ctime < livesUntil ) {

Shouldn't it read:
if ( stat.ctime < livesUntil.getHours() ) {

A: I tried to create my own function thanks to other response in this topic. It is a typescript style using like an Helper in a @NestJs project (used for ExceptionHandling here).
Dependencies
I'm also using

*

*momentJs for definig date

*Node js fs package

*and path
Parameter

*

*parentDirectory : the directory where the function will walk through and delete all files older than 60 hours
import * as path from 'path';
import * as fs from 'fs';
import * as moment from 'moment';
import { InternalServerErrorException } from '@nestjs/common';

export default function walk(parentDirectory: string): void {
  let list;
  let i = 0;

  try {
    // store list of all file and directory in the current directory
    list = fs.readdirSync(parentDirectory);
  } catch (e) {
    throw new InternalServerErrorException(e.toString());
  }

  return (function next() {
    const file = list[i++];

    if (file) {
      const filePath = path.resolve(parentDirectory, file);
      const stat = fs.statSync(filePath);

      if (stat && stat.isDirectory()) {
        // if it's a directory, continue walking
        walk(filePath);

        return next();
      } else {
        // see stats of the file for its creation date
        fs.stat(filePath, (err, stat) => {
          if (err) console.error(err);

          // using moment.js to compare expiration date
          const now = moment();
          const endTimeFile = moment(stat.ctimeMs).add(60, 'minutes');

          if (now > endTimeFile) {
            try {
              // delete file if expired
              fs.unlinkSync(filePath);
              console.log(`successfully deleted ${filePath}`);
            } catch (err) {
              throw new InternalServerErrorException(
                'file not deleted successfully',
              );
            }
          }
        });

        return next();
      }
    }
  })();
}

A: const path = require('path');
const fs = require('fs');

var uploadsDir = __dirname + '/Test';
let modifiedFiles = [];
var noOfFile = 2;

var files = fs.readdirSync(uploadsDir);
files.forEach((file, index) => {
    var stat = fs.statSync(path.join(uploadsDir, file));
    modifiedFiles.push({ cTime: stat.ctime.valueOf(), Name: file, Index: index });
    console.log(stat);
});

var data = modifiedFiles.sort((a, b) => b.cTime - a.cTime);
var MaxCTime = data[noOfFile - 1].cTime;
data.forEach((v) => {
    if (MaxCTime > v.cTime) {
        fs.unlink(path.join(uploadsDir, v.Name));
    }
});
console.log('older files deleted except last 2 modified');

A: Here's a plain Node script (for instance name it cleanlogs.js), tested on v18.7.0 using the fs promises api (native module). You really dont need any fancy npm modules:
import * as fs from 'node:fs/promises';
import path from 'path';

/**
 * Remove all files in a directory older than the given number of seconds.
 * @param {String} directory The directory to look in.
 * @param {String[]} extensions The file extensions to match.
 * @param {Number} seconds The minimum number of seconds since the creation time of the file.
 */
(async (directory, extensions, seconds) => {
    const currentTime = Math.floor(new Date().getTime() / 1000);

    const files = Array.from(await fs.readdir(directory)).filter((file) => {
        return extensions.indexOf(file.split('.').at(-1)) !== -1;
    });

    for (const file of files) {
        const filePath = path.join(directory, file);
        const stats = await fs.stat(filePath);
        const birthTime = Math.floor(stats.birthtimeMs / 1000);
        if (currentTime - birthTime > seconds) {
            fs.rm(filePath);
        }
    }
})('./logs', ['log'], 60 * 60 * 12);

The example removes files in the ./logs directory for any file with the log extension (e.g. error.log), older than 12 hours (60 * 60 * 12 seconds).


text:
Q: How to capture the event of ng-change? Here's my code, But the $event is undefined. Does anyone know how can I capture the event?
<!DOCTYPE html>

    <select class="form-control input-sm" ng-model="fda" ng-change="alert($event)" ng-options="value for value in names">
    </select>

A: ngMouse, ng-change does not provide an event object.
But my suggestion is to create another variable, assign $event to that, then pass it via ng-change.

<!DOCTYPE html>

    <select
        class="form-control input-sm"
        ng-click="event = $event"
        ng-model="fda"
        ng-change="alert(event)"
        ng-options="value for value in names">
    </select>

More details

A: ng-change is not a directive for handling the change event (I realize that this is confusing given the name). So this is as expected. Github source
If you need to get the event, you can use ng-click instead:

<!DOCTYPE html>

    <select class="form-control input-sm" ng-model="fda" ng-click="alert($event)" ng-options="value for value in names">
    </select>

A: Capture event beforehand
If you need the ng-change functionality but also want to get the element being changed you could also use ng-focus to capture the element before change.
<select ... ng-focus="setFocus($event)" ng-change="alert()" ... />

Expanded example below:

<!DOCTYPE html>

         <select class="form-control input-sm" ng-model="fda" ng-change="alert()" ng-focus="setFocus($event)" ng-blur="cancelFocus($event)" ng-options="value for value in names">
         </select>

A: You can use this sample:
<!DOCTYPE html>

    <select class="form-control input-sm" ng-model="fda" ng-click="e=$event"ng-change="alert(e)" ng-options="value for value in names">
    </select>

A: You can't, this answer is taken from a quick google search result:
ng-change is not a directive for handling the change event
(I realize that this is confusing given the name), but is actually
instead notified when ngModelController.$setViewValue() is called
and the value changes (because ng-change adds a listener to the
$viewChangeListeners collection). So this is as expected.


text:
Q: Kubernetes mount.nfs: access denied by server while mounting I have a kubernetes cluster that is running in out network and have setup an NFS server on another machine in the same network. I am able to ssh to any of the nodes in the cluster and mount from the server by running sudo mount -t nfs 10.17.10.190:/export/test /mnt but whenever my test pod tries to use an nfs persistent volume that points at that server it fails with this message:
Events:
  FirstSeen LastSeen    Count   From            SubObjectPath   Type       Reason       Message
  --------- --------    -----   ----            -------------   --------    ------      -------
  19s       19s     1   default-scheduler           Normal      Scheduled   Successfully assigned nfs-web-58z83 to wal-vm-newt02
  19s       3s      6   kubelet, wal-vm-newt02          Warning
FailedMount MountVolume.SetUp failed for volume "kubernetes.io/nfs/bad55e9c-7303-11e7-9c2f-005056b40350-test-nfs" (spec.Name: "test-nfs") pod "bad55e9c-7303-11e7-9c2f-005056b40350" (UID: "bad55e9c-7303-11e7-9c2f-005056b40350") with: mount failed: exit status 32
Mounting command: mount
Mounting arguments: 10.17.10.190:/exports/test /var/lib/kubelet/pods/bad55e9c-7303-11e7-9c2f-005056b40350/volumes/kubernetes.io~nfs/test-nfs nfs []
Output: mount.nfs: access denied by server while mounting 10.17.10.190:/exports/test

Does anyone know how I can fix this and make it so that I can mount from the external NFS server?
The nodes of the cluster are running on 10.17.10.185 - 10.17.10.189 and all of the pods run with ips that start with 10.0.x.x. All of the nodes on the cluster and the NFS server are running Ubuntu. The NFS server is running on 10.17.10.190 with this /etc/exports:
/export         10.17.10.185/255.0.0.0(rw,sync,no_subtree_check)

I set up a persistent volume and persistent volume claim and they both create successfully showing this output from running kubectl get pv,pvc:
NAME          CAPACITY   ACCESSMODES   RECLAIMPOLICY   STATUS    CLAIM              STORAGECLASS   REASON    AGE
pv/test-nfs   1Mi        RWX           Retain          Bound     staging/test-nfs                            15m

NAME           STATUS    VOLUME     CAPACITY   ACCESSMODES   STORAGECLASS   AGE
pvc/test-nfs   Bound     test-nfs   1Mi        RWX                          15m

They were created like this:
apiVersion: v1
kind: PersistentVolume
metadata:
  name: test-nfs
spec:
  capacity:
    storage: 1Mi
  accessModes:
    - ReadWriteMany
  nfs:
    # FIXME: use the right IP
    server: 10.17.10.190
    path: "/exports/test"
---
kind: PersistentVolumeClaim
apiVersion: v1
metadata:
  name: test-nfs
spec:
  accessModes:
    - ReadWriteMany
  resources:
    requests:
      storage: 1Mi

My test pod is using this configuration:
apiVersion: v1
kind: ReplicationController
metadata:
  name: nfs-web
spec:
  replicas: 1
  selector:
    role: web-frontend
  template:
    metadata:
      labels:
        role: web-frontend
    spec:
      containers:
      - name: web
        image: nginx
        ports:
          - name: web
            containerPort: 80
        volumeMounts:
            # name must match the volume name below
            - name: test-nfs
              mountPath: "/usr/share/nginx/html"
      volumes:
      - name: test-nfs
        persistentVolumeClaim:
          claimName: test-nfs

A: You have to set a securityContext as privileged: true. Take a look at this  link

A: It's probably because the uid used in your pod/container has not enough rights on the NFS server.
You can runAsUser as mentioned by @Giorgio or try to edit uid-range annotations of your namespace and fix a value (ex : 666). Like this every pod in your namespace
will run with uid 666.
Don't forget to chown 666 properly your NFS directory.

A: The complete solution for kubernetes cluster to prepare NFS folders provisioning is to apply the followings:
# set folder permission
sudo chmod 666 /your/folder/ # maybe 777

# append new line on exports file to allow network access to folder
sudo bash -c "echo '/your/folder/ <network ip/range>(rw,sync,no_root_squash,subtree_check)' >> /etc/exports"

# set folder export
sudo exportfs -ra

A: In my case I was trying to mount the wrong directory...
      volumes:
        - name: nfs-data
          nfs:
            # https://github.com/kubernetes/minikube/issues/3417
            # server is not resolved using kube dns (so can't resolve to a service name - hence we need the IP)
            server: 10.100.155.82
            path: /tmp

I did not have /tmp in the /etc/exports in the server...

A: Another option is to add the uid/gid information to the nfs container itself. You can do this by creating a script to add the entries to /etc/passwd and then launch the provisioner:
groupadd -g 102 postfix
adduser -u 101 -g 102 -M postfix
groupadd -g 5000 vmail
adduser -u 5000 -g 5000 -M vmail
adduser -u 33 -g 33 -M www-data
groupadd -g 8983 solr
adduser -u 8983 -g 8983 -M solr

...

/nfs-server-provisioner -provisioner=cluster.local/nfs-provisioner-nfs-server-provisioner

This allows the user/group information to be preserved over the NFS boundary using NFSv3 (which is what nfs-provisioner uses). My understanding is that NFSv4 doesn't have this problem, but I've been unable to get NFSv4 working with the provisioner.

A: In my case, it was the way I mounted NFS. The configuration that worked was following:
/media/drive *(rw,sync,no_root_squash,insecure,no_subtree_check)

Note that this is insecure, you might want to tweak it to make it secure, while still making it work!


text:
Q: How to make an embedded video not autoplay I'm embedding a Flash video into an HTML and would like the user to have to click it to begin playing. According to the Adobe <object> / <embed> element documentation, there are variety of methods to do this:
1) Add a Flash parameter inside the <object> tag:
<param name="play" value="false">

2) Add the attribute play inside the <embed> tag:
<embed ... play="false">

3) Add the attribute flashvars inside the <embed> tag:
<embed ... flashvars="play=false">

Which is awesome. Only ... none of them work for me:
http://johnboxall.github.com/test/flash/flash.htm
My code looks like this now:
<object width="590" height="475">
    <param name="movie" value="untitled_skin.swf">
    <param name="play" value="false">
    <embed src="untitled_skin.swf" width="590" height="475" type="application/x-shockwave-flash" play="false" flashvars="autoplay=false&play=false" menu="false"></embed>
</object>

Anyone have any ideas? What am I doing wrong?

A: I had the same problem and came across this post. Nothing worked. After randomly playing around, I found that <embed ........ play="false"> stopped it from playing automatically. I now have the problem that I can't get a controller to appear, so can't start the movie! :S

A: A couple of wires are crossed here. The various autoplay settings that you're working with only affect whether the SWF's root timeline starts out paused or not. So if your SWF had a timeline animation, or if it had an embedded video on the root timeline, then these settings would do what you're after.
However, the SWF you're working with almost certainly has only one frame on its timeline, so these settings won't affect playback at all. That one frame contains some flavor of video playback component, which contains ActionScript that controls how the video behaves. To get that player component to start of paused, you'll have to change the settings of the component itself.
Without knowing more about where the content came from it's hard to say more, but when one publishes from Flash, video player components normally include a parameter for whether to autoplay. If your SWF is being published by an application other than Flash (Captivate, I suppose, but I'm not up on that) then your best bet would be to check the settings for that app. Anyway it's not something you can control from the level of the HTML page. (Unless you were talking to the SWF from JavaScript, and for that to work the video component would have to be designed to allow it.)

A: Try replacing your movie param line with
<param name="movie" value="untitled_skin.swf&autoStart=false">

A: Try adding these after <Playlist>
<AutoLoad>false</AutoLoad>
<AutoPlay>false</AutoPlay>

A: fenomas's answer was really good...it got me off of looking into the HTML code. I know that jb was looking for something that works in Captivate, but the question is broad enough to include people working out of Flash (I'm using CS5), so I thought I'd throw in the specific answer to my situation here.
If you're using the stock Adobe FLVPlayback component in Flash (you probably are if you used File > Import > Import Video...), there's an option in the Properties panel, under Component Parameters. Look for 'autoPlay' and uncheck it. That'll stop autoplay when the page loads!


text:
Q: How to save multiple files at once through delphi save dialog I'm not able to save multiple files at a time in delphi save dialog box. Multiple files means I want save files without mentioning anything(or only asterisk) at "filename" field in delphi TsaveDialog. Please let me know how to achieve that.

A: Of course not, because that is not what it is intended for.  You CANNOT obtain multiple filenames from a single save dialog.  It only provides one filename at a time.  That is by design.
I suspect what you really want is to prompt the user for just a folder path instead. Use the SelectDirectory() function (or the Win32 SHBrowseForFolder() function directly) for that, then you can create whatever files you need in that folder.

A: The save dialog doesn't save files. It allows the user to select file names. The save dialog doesn't support multiple selection so if you want to have a file dialog that allows multiple selections you need an open dialog. But an open dialog typically is used to select names of existing files, whereas a save dialog can specify a name of a file that does not yet exist.
Wildcards when entered into file dialogs are used to filter the displayed list of files. The file dialog won't return file names containing wildcards.
You imagine using wildcards, but how would you be able to do that and create new files? Wildcards are used to pattern match against existing files.
Maybe what you need is a folder selection dialog. Or perhaps you should ask the user for the name of the "master" file and then you generate the names of the "auxiliary" files using the master file name as a stem. I'm guessing because you've not told us any specifics behind your question.
My advice is to reconsider carefully what you are attempting to achieve. Think of all possible corner cases. Explore what UI idioms are used by other programs. Make sure you understand fully the capability of the file dialog controls. And then design your UI to fit with all of these constraints.


text:
Q: How should i solve this error:bad operand types for binary operator '&&' I don't know what's wrong but this code is giving me this  error: bad operand types for binary operator '&&'
  if((n%2==0) && (n>>6) && (n<<20))
{

          ans = "Not Weird";
      }

A: Greater than is just >, not >>, which is a shift operator. Same for less than and < vs <<.
The shift operator returns an integral type and && expects both sides to be of type boolean. For more information on the shift operators, see this question: How do shift operators work in Java?

A: >> and << are bitwise operators. They evaluate to integral types and Java does not convert integral types implicitly to boolean types, which are required for && arguments and the if condition.
So you ought to rewrite to
if (n > 6 && n < 20 && n % 2 == 0)

I've taken the liberty of removing the superfluous parentheses and re-ordered the statements so the computationally cheaper > and < are evaluated first, and the more expensive % only if necessary. It's a micro-optimisation but demonstrates to readers of your code that you know what you're doing.

A: Here >> is a signed shift right operator. For example
  int x = -4;
  System.out.println(x>>1);
  int y = 4;
  System.out.println(y>>1);

will give you
-2
2

The same applies for shift Left  << operator.
You want to check greater than or less than. So for that purpose you need '>' or '<' operator.
so the correct conditional checking will be like
  if((n%2==0) && (n>6) && (n<20)) {
       ans = "Not Weird"
   }


text:
Q: Blaze-Apollo w/ Meteor, observer not triggering the subscribe on variable change I am trying to re-fetch the data on variable change from blaze-apollo using graphql query.
The query is :
this.rows = this.gqlQuery({
    query: GET_DATA,
    variables: {
        databaseId: dbId,
        accessToken: accessToken,
        limit: 2
    },
    fetchPolicy: "network-only"
});

The subscriber is :
 this.rowsObservableSub = this.rows.observer.subscribe({
    next: ({ loading }) => {
        console.log("loading is ===> ", loading);
    }
});

and the observer is called as:
this.autorun(()=> {
    if(this.searchTerm.get()){
        const variables = {
            databaseId: dbId,
            accessToken: accessToken,
            limit: 4
        };
        this.rows.observer.setVariables(variables);
    }
});

this.rowObservableSub is not triggered on the change in variable when searchTerm changes.

A: Found the solution, the following changes tell the observer to persist with the network-only fetchPolicy instead of hitting the cache
this.rows.observer.setVariables(variables, true)


text:
Q: IsWithinDistance method doesn't work with geojson file for library TopologySuite I'm trying to get all the points within a distance of 10 meter for example. the Withindistance() doesn't work and it doesn't give me any error so i don't know what is the issue.
Here is my controller :
public IActionResult GetWeather()
        {

            IList<WeatherViewModel> Tags = new List<WeatherViewModel>();

            var geometryFactory = NtsGeometryServices.Instance.CreateGeometryFactory(srid: 4326);
            var searchAreaCoordinate = new NetTopologySuite.Geometries.Coordinate(-1.88049067645237,52.486034913778894);
            var searchArea = geometryFactory.CreatePoint(searchAreaCoordinate);

            Root weather = JsonConvert.DeserializeObject<Root>(System.IO.File.ReadAllText(@"C:\local\weather.json"));
            var features = (from c in  weather.features select c)
            .Select(x=> new {x.id,x.type,x.geometry.coordinates,Coor= new Point(x.geometry.coordinates[0],x.geometry.coordinates[1]){ SRID = 4326 },

            })
            .Where(x=>x.Coor.IsWithinDistance(searchArea, 10))

            .ToList();
            ;

            foreach (var item in features)
            {
                Tags.Add(new WeatherViewModel()

                {
                            id = item.id,
                            type = item.type,
                            Long = item.coordinates[0],
                            Lat = item.coordinates[1],
                            test = item.Coor.ToString(),
                            Distance = item.Coor.Distance(searchArea)

                            // WKT = item.z
                            // WKT = new NetTopologySuite.Geometries.Coordinate( item.coordinates[0] , item.coordinates[1])

                }
                );
            }

            return View(Tags);
        }
    }

Note that I'm getting all the records . The Where() doesn't work so if i comment it out ill still get all the results:
Json Class
public class Root
   {
       public string type { get; set; }
       public ParameterDescription parameter_description { get; set; }
       public List<double> bbox { get; set; }
       public List<Feature> features { get; set; }
   }
public class Geometry
   {
       public string type { get; set; }
       public List<double> coordinates { get; set; }
   }

   public class Feature
   {
       public string id { get; set; }
       public string type { get; set; }
       public Properties properties { get; set; }
       public Geometry geometry { get; set; }
       public Geometry Coor {get;set;}
   }

Json sample
{
   "type": "FeatureCollection",

   "features": [
       {
           "id": "1",
           "type": "Feature",
           "properties": {
               "t": [
                   1,

               ],
               "s": [
                   1,

               ],
               "Time": [
                   "2021-11-01",

               ]
           },
           "geometry": {
               "type": "Point",
               "coordinates": [
                   -1.881,
                   52.486
               ]
           }
       },

   ]
}

Any idea?


text:
Q: free -m: free size reduced because of cache/buff I'm using the function rosbag of ROS. rosbag can record lots of data from other ROS nodes. In a word, it will generate a huge file, such as a file of 200MB.
After generating such a file, I found that the buff/cache of the system increases a lot. Here is my capture:
Before rosbag:

After rosbag:

You can see that after rosbag, buff/cache increased a lot, at the same time, free decreased from 19983 to 10896.
I can't understand. As my understanding, free means the free size of RAM, buff/cache is the size of cache. Why can cache use the size of RAM? And I've also found that if I deleted the file generated by rosbag, the buff/cache would get back from 17999 to 8925. Is this the action of the system? When will the buff/cache increase? When will the buff/cache decrease?

A: In free's output:

*

*"free" represents memory which is unused;

*"buff/cache" represents memory used by buffers (data in memory which is waiting to be written to disk) and cache (data on disk which is also available in memory);

*"available" represents the amount of memory a process can allocate and use without hitting swap (most of the time it's this value you should care about).

When a process writes a large amount of data, that data goes to buffers before being written to disk. Those buffers take up room in memory, so the amount of unused memory goes down. But that memory can be made available, so the amount of available memory doesn't go down.
When you delete the file, the buffers are no longer needed and are reclaimed (there's no point in even keeping them as cache).
Buffers increase when processes write data; they decrease when that data is written to disk. Cache increases when on-disk data is made available in memory (either by reading it from disk, or converting buffers into cache); it decreases when memory pressure means it's no longer useful to keep it around. Both live in memory, so their size affects the amount of free memory; but both can be reclaimed, so their size doesn't affect the amount of available memory.


text:
Q: I started web crawling using Storm Crawler but I do not know where crawled results go to? Im not using Solr or Elastic Search The Storm Crawler started crawling data but it seems I cannot find where data is stored I need to save this data to to a database so I can connect the data to a remote server and have it indexed.  Storm crawler seems to focus mainly on Solr and Elastic integration!!!  I just want to store its data to a database so i can use with any site search solution like Typesense, flex search and any other site search software.
Im very new at the web craping so im just installed required software to run.

A: SC does not focus on SOLR or ES. There is for instance a SQL module.
As for "where the crawled results go", it depends on what your topology does. Maybe try to explain what bolts are running etc...


text:
Q: Several rdlc files at the same time in the same reportviewer As per the title, I haven't found any way to generate a report with differente rdlc files at the same time in VB .NET
The point is that I have to create like 8 different reports with different tables and formats, but I need to show them all at once in the reportviewer, so the user can scroll down and see one by one, and of course, print them out in one shot.
I've read something about "PDFtk" to print different reports in different pdfs and merge them down but it's not what I am looking for, because the pdf creation may fail and....and I am pretty sure there must be something like this done already by someone..
Anyone has any idea how to merge them???
Thanks

A: Hi I faced the same problem, after doing some searching I arrived that the simplest way to achieve what you're looking for is to create a main report and than include your 8 reports as subreport of the main report.
It works great for me. There could be just one problem. If your 8 reports have header and footer it won't be displayed because ssrs just shows the header and footer of the main report and suppresses those of the subreports
Hope this can help you

A: Just in case is useful for someone else I did it this way:
1./ Create parameter from code like this
*Dim params as New List(Of ReportParameter)
 params.add(New ReportPArameter("NAME_IN_REPORT", "ANYVALUE") 'Repeat this per each parameter
 With RViewer
    .LocalReport.ReportEmbeddedResource="ProjectName.ReportName.rdlc"
    .LocalReport.SetParameters(params)
    .RefreshReport()
 End With*

2./ At the same time you create a main report and create the parameters with the same name you create them in the 1st step (e.g. NAME_IN_REPORT)
3./ Create another report with the structure (tables, lines, textboxes,etc) and create the params as well (because we are gonna have to connect this params with the ones in step 2)
4./ This param association is made in the main report, once we added the subreport, right button over the subreport, subreport properties and Parameters section.
Name              Value
NAME_IN_REPORT      [@NAME_IN_REPORT]
At the end, the params travel like this between reports:
code params --> main report params --> subreport params
Hope it helps to someone, otherwise let me know and I'll help you as much as I can


text:
Q: Type '() => Promise>' cannot be used as an index type [ReactJs] I currently am working on a control panel for a page that loads up a list of cards.
I have two different routes from an API that are as follows:
const apiVideoUrl = "http://localhost:3000/videos/";
const apiManualUrl = "http://localhost:3000/manuals/";

They both return sets of data that are displayed as cards, and they both contain Id, Title, URL and ThumbnailUrl. I've been successful with just loading either videos or manuals seperately, but I Cannot seem to get them to load up together.
my componentDidMount() is as follows and is where the error is arrising from:
async componentDidMount() {
    const apiVideoUrl = "http://localhost:3000/videos/";
    const apiManualUrl = "http://localhost:3000/manuals/";

    const getVideos = async () => {
      return await axios.get(apiVideoUrl);
    };

    const getManuals = async () => {
      return await axios.get(apiManualUrl);
    };

    try {
      const [videos, manuals] = await Promise.all[(getVideos, getManuals)];

      // render to state setState({ prop: ? })
    } catch (error) {
      this.setState({ error });
    }
  }

The error:
Type '() => Promise<AxiosResponse<any>>' cannot be used as an index type.ts(2538)

is given from:
  const [videos, manuals] = await Promise.all[(getVideos, getManuals)];

The code for the rest of the page  is as follows (just incase it's needed):
import React, { Component } from "react";
import HelpCard from "./HelpCard";
import "../help/HelpCard.css";
import axios from "axios";
import InfiniteScroll from "react-infinite-scroller";

interface State {
  url: string;
  title: string;
  adminhelpcard: SingleAdminHelpCard[];
  error: null;
  response: {};
  thumbnail: string;
}

interface SingleAdminHelpCard {
  id: string;
  url: string;
  title: string;
  thumbnail: string;
}

interface Props {}

export default class HelpList extends Component<Props, State> {
  state = {
    title: "",
    thumbnail: "",
    id: "",
    url: "http://localhost:3000/videos/",
    adminhelpcard: [],
    itemsCountPerPage: 1,
    activePage: 1,
    error: null,
    response: {}
  };

  loadAdminHelpCard = () => {
    axios
      .get(this.state.url)
      .then((res) => {
        this.setState((prevState) => {
          const adminhelpcard = prevState.adminhelpcard;
          return {
            adminhelpcard: [...prevState.adminhelpcard, ...res.data],
            url: res.data.next
          };
        });
      })
      .catch(function(error) {
        // handle error
        console.log(error);
      });
  };
  static props: any;

  async componentDidMount() {
    const apiVideoUrl = "http://localhost:3000/videos/";
    const apiManualUrl = "http://localhost:3000/manuals/";

    const getVideos = async () => {
      return await axios.get(apiVideoUrl);
    };

    const getManuals = async () => {
      return await axios.get(apiManualUrl);
    };

    try {
      const [videos, manuals] = await Promise.all[(getVideos, getManuals)];

      // render to state setState({ prop: ? })
    } catch (error) {
      this.setState({ error });
    }
  }

  deleteProduct(id: any) {
    const { adminhelpcard } = this.state;

    const apiVideoUrl = `http://localhost:3000/videos/${id}`;
    const apiManualUrl = `http://localhost:3000/manuals/${id}`;

    const options = {
      method: "DELETE"
    };

    fetch(apiVideoUrl, options)
      .then((res) => res.json())
      .then(
        (result) => {
          this.setState({
            response: result,
            adminhelpcard: adminhelpcard.filter((adminhelpcard: SingleAdminHelpCard) => adminhelpcard.id !== id)
          });
        },
        (error) => {
          this.setState({ error });
        }
      );
    fetch(apiManualUrl, options)
      .then((res) => res.json())
      .then(
        (result) => {
          this.setState({
            response: result,
            adminhelpcard: adminhelpcard.filter((adminhelpcard: SingleAdminHelpCard) => adminhelpcard.id !== id)
          });
        },
        (error) => {
          this.setState({ error });
        }
      );

    console.log(this.state.id);
  }

  editProduct(id: any, title: string, url: string, thumbnail: string) {
    const { adminhelpcard } = this.state;
    const apiVideoUrl = `http://localhost:3000/videos/${id}`;
    const apiManualUrl = `http://localhost:3000/manuals/${id}`;

    const options = {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        title,
        url,
        thumbnail
      })
    };

    fetch(apiVideoUrl, options)
      .then((res) => res.json())
      .then(
        (result) => {
          this.setState({
            response: result,
            adminhelpcard: adminhelpcard.filter((adminhelpcard: SingleAdminHelpCard) => adminhelpcard.id !== id)
          });
        },
        (error) => {
          this.setState({ error });
        }
      );
    fetch(apiManualUrl, options)
      .then((res) => res.json())
      .then(
        (result) => {
          this.setState({
            response: result,
            adminhelpcard: adminhelpcard.filter((adminhelpcard: SingleAdminHelpCard) => adminhelpcard.id !== id)
          });
        },
        (error) => {
          this.setState({ error });
        }
      );
  }

  render() {
    console.log(this.state.adminhelpcard);
    return (

        <React.Fragment>
          {this.state.adminhelpcard ? (

              <InfiniteScroll
                pageStart={1}
                loadMore={this.loadAdminHelpCard}
                hasMore={this.state.url ? true : false}
                threshold={0}
                loader={

                    Loading ...

                }>
                {this.state.adminhelpcard.map((adminhelpcard: SingleAdminHelpCard, i) => (
                  <HelpCard
                    id={adminhelpcard.id}
                    key={adminhelpcard.id + i}
                    title={adminhelpcard.title}
                    url={adminhelpcard.url}
                    thumbnail={adminhelpcard.thumbnail}
                    deleteProduct={this.deleteProduct.bind(this)}
                    editProduct={this.editProduct.bind(this)}
                  />
                ))}
              </InfiniteScroll>

          ) : (

Loading Cards

          )}
        </React.Fragment>

    );
  }
}

What is triggering this error and for what reason?
--------------------------EDIT----------------------------------
This is the return of the console.log
[
  {
    "data": [
      {
        "id": 1,
        "url": "https://s3.eu-west-2.amazonaws.com/ts-ui.e.mp4",
        "title": "How to train your dragon video",
        "thumbnail": "https://i.ytimg.com/vi/l3uyjXJl2Fw/hqdefault.jpg"
      },
      {
        "title": "Guide - Web",
        "url": "https://s3.eu-west-2.amazonaws.com/ts-ui.e-6928.mp4",
        "thumbnail": "https://i.ytimg.com/vi/Um3BhY0oS2c/hqdefault.jpg",
        "id": 2
      },
      {
        "title": "Reports - Non-Supervisors",
        "url": "https://s3.eu-west-2.amazonaws.com/ts-ui.e-Videos+1263198.mp4",
        "thumbnail": "",
        "id": 3
      },
      {
        "id": 4,
        "url": "https://s3.eu-west-2.amazonaws.com/ts-ui.e-Videos+1263198.mp4",
        "title": " - Non-Supervisors",
        "thumbnail": ""
      },
      {
        "id": 5,
        "url": "https://s3.eu-west-2.amazonaws.com/ts-ui.e-Videos+1263198.mp4",
        "title": " - Non-Supervisors",
        "thumbnail": ""
      },
      {
        "id": 6,
        "url": "https://s3.eu-west-2.amazonaws.com/ts-ui.e-198.mp4",
        "title": "Supervisors",
        "thumbnail": ""
      },
      {
        "id": 7,
        "url": "https://s3.eu-west-2.amazonaws.com/ts-ui.e-deos+1263198.mp4",
        "title": "Supervisors",
        "thumbnail": ""
      }
    ],
    "status": 200,
    "statusText": "OK",
    "headers": {
      "pragma": "no-cache",
      "content-type": "application/json; charset=utf-8",
      "cache-control": "no-cache",
      "expires": "-1"
    },
    "config": {
      "transformRequest": {},
      "transformResponse": {},
      "timeout": 0,
      "xsrfCookieName": "XSRF-TOKEN",
      "xsrfHeaderName": "X-XSRF-TOKEN",
      "maxContentLength": -1,
      "headers": {
        "Accept": "application/json, text/plain, */*"
      },
      "method": "get",
      "url": "http://localhost:3000/videos/"
    },
    "request": {}
  },
  {
    "data": [
      {
        "id": 1,
        "url": "https://s3.eu-west-2.amazonaws.com/ts-ui.e-ite.pdf",
        "title": "How to train your dragon",
        "thumbnail": ""
      },
      {
        "id": 2,
        "url": "https://onaws.com/ts-ui.e-s.pdf",
        "title": "How to train your dragon test3",
        "thumbnail": ""
      },
      {
        "id": 3,
        "url": "https://sm/ts-ui.e-ide.pdf",
        "title": "Resume full guide",
        "thumbnail": ""
      }
    ],
    "status": 200,
    "statusText": "OK",
    "headers": {
      "pragma": "no-cache",
      "content-type": "application/json; charset=utf-8",
      "cache-control": "no-cache",
      "content-length": "634",
      "expires": "-1"
    },
    "config": {
      "transformRequest": {},
      "transformResponse": {},
      "timeout": 0,
      "xsrfCookieName": "XSRF-TOKEN",
      "xsrfHeaderName": "X-XSRF-TOKEN",
      "maxContentLength": -1,
      "headers": {
        "Accept": "application/json, text/plain, */*"
      },
      "method": "get",
      "url": "http://localhost:3000/manuals/"
    },
    "request": {}
  }
]

A: In:
const [videos, manuals] = await Promise.all[(getVideos, getManuals)];
There is an Error on Promise. The syntax is Promise.All([])
You can use:
const [videos, manuals] = await Promise.All([getVideos(), getManuals()])
Read if you don't get it: https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

A: You seem to just misspell brackets.
const [videos, manuals] = await Promise.all[(getVideos, getManuals)];

If you want to wait getVideos and getManuals resolved, you should call method Promise.all (with parenthesis) and pass Iteralbe as an argument (with square brackets):
const [videos, manuals] = await Promise.all([getVideos(), getManuals()]);

If you want to use values of promises right here, you can write code like:
Promise.all([getVideos(), getManuals()]).then(([videos, manuals]) => { /* do stuff */ });

See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all


text:
Q: How can I retrieve the data object using SQL package on Node.JS? I have a mysql query executed from NodeJS using mysql npm package.
Upon success, I want to read the value in Javascript.
Both are on the same domain.
On console.log the value I read is 3.
How can I retrieve the data object values?

var mysql      = require('mysql');
var connection = mysql.createConnection(connectionOptions);

connection.query(
  "SELECT * FROM pruebas.Usuarios2 where RFC = '123'",
  (err, result, fields) => {
     if (result.length) {
       // here I need an instruction that can send me the result of 3
       // to my javascript console
     } else {
       console.log('no login');
     }
   }
 );

A: You don't send from Node to Javascript. You call Node from Javascript using an Ajax call and return a value.
The answer to this question is a good exemple of how to do it:
Basic Ajax send/receive with node.js


text:
Q: Pig script to compress and decompress the hdfs data in bzip2 How to compress hdfs data to bzip2 using pig such that on decompression it should give the same dir structure which it had initially.I am new to pig.
I tried to compress with bzip2 but it generated many files due to many mappers being spawned and hence reverting back to plain text file(initial form) in the same dir structure becomes difficult.
Just like how in unix if we compress bzip2 using tarball and then after decompression of bzip2.tar gives me exactly same data and folder structure which it had initially.

eg Compression:-  tar -cjf compress_folder.tar.bz2 compress_folder/
Decompression:-  tar -jtvf compress_folder.tar.bz2

will give exactly same dir st.

A: Approach 1:
you can try running one reducer to store only 1 file on hdfs. but compromise will be performance here.
set default_parallel 1;

to compress data, set these parameters in pig script , if not tried this way:-
set output.compression.enabled true;
SET mapred.output.compression.codec 'org.apache.hadoop.io.compress.BZip2Codec';

just use JsonStorage while storing file
STORE file INTO '/user/hduser/data/usercount' USING JsonStorage();

Eventually you also want to read data, use TextLoader
data = LOAD '/user/hduser/data/usercount/' USING TextLoader;

Approach 2:
filecrush: file merge utility available at @Mr. github


text:
Q: I can't connect to internet through wifi using Xubuntu Everytime i try to connect to internet using wifi i type the password, Xubuntu tries to connect for a little while and then asks me the password again. I'm using a D-Link modem/router.
Network controller [0280]: Realtek Semiconductor Co., Ltd. RTL8191SEvA Wireless LAN Controller [10ec:8171] (rev 10)
 Subsystem: Hewlett-Packard Company Device [103c:1467]
 Kernel driver in use: rtl8192se

A: You can install another driver. You need to be connected to internet by wire.
sudo add-apt-repository ppa:hanipouspilot/rtlwifi
sudo apt-get update
sudo apt-get install rtlwifi-new-dkms linux-firmware

and reboot.


text:
Q: Program seems to skip getchar() So I'm new to coding in C and coding in general. I'm learning with a book and a code in there just won't work and I don't know why. It's probably a trivial matter but as I said..I'm a bloody noob. Anyway this is the code:
#include <stdio.h>

void main()
{
    char a, b;

    printf("Welches Zeichen ist groesser?");
    printf("\nGeben Sie ein Zeichen ein:");
    a = getchar();
    printf("Nun ein anderes Zeichen:");
    fflush(stdin);
    b = getchar();

    if( a > b)
    {
        printf("'%c' ist groesser als '%c'!\n", a, b);
    }
    else if( b > a)
    {
        printf("\n'%c' ist groesser als '%c'!\n", b, a);
    }
    else
    {
    printf("\nBitte nicht zweimal das gleiche Zeichen eingeben!");
    }
}

I don't get any compiler error messages, it just seems to 'skip' the second getchar and go straight to the last printf. I feel like it has something to do with fflush(stdin). It doesn't matter if it's in the code or not. I already tried fflush(stdout) but with the same outcome. Can somebody tell me why and please don't be too harsh.
Thanks in advance!

A: As pointed out before fflush() is only for output streams, not input.
To read different lines fgets() might be attractive to you. No fflush() required.
If you can get hold of the ANSI final draft of the early C standard it has two sections, the specification and a "rationale" saying why some choices were made. It really helped me learn C in the days. Now days I download and save an ISO final draft to see where C is now.
7.21.5.2 The fflush function
Synopsis
#include <stdio.h>
int fflush(FILE *stream);
Description
If stream points to an output stream or an update stream in which the most recent operation was not input, the fflush function causes any unwritten data for that stream to be delivered to the host environment to be written to the file; otherwise, the behavior is undefined.
If stream is a null pointer, the fflush function performs this flushing action on all streams for which the behavior is defined above


text:
Q: GitHub connected via Git Bash but not via Ubuntu Bash (WSL) I can push my code to my remote GitHub repo via PowerShell or Git Bash, but when I try to do the same via Ubuntu Bash (WSL), I get the following error:
C:\Windows\System32\OpenSSH\ssh.exe': 1: Syntax error: Unterminated quoted string
fatal: Could not read from remote repository.
Please make sure you have the correct access rights and the repository exists.

A: You need to use this command
git config --global core.sshCommand /mnt/c/Windows/System32/OpenSSH/ssh.exe


text:
Q: Display WooCommerce Unit Prices at Product variations I like to display unit prices at variable products. I like it to do based on a product attribute whic contains the following: 5 kg, 2 l etc. So, I get the attribute, extract the numbers from it and do some math. The problem is, that all of the code displays the multipier number of 1. Here is my code:
function product_variation_unit_price( $data, $product, $variation ) {

    $price  = wc_get_price_to_display( $variation );
    $unit = array_shift( wc_get_product_terms( $product->id, 'pa_unit', array( 'fields' => 'names' ) ) );
    $unit_number_extracted = preg_replace('/[^0-9]/', '', $unit);

    if ( (!empty($unit) ) AND $unit_number_extracted == 1 ) {
        $unit_price = sprintf( __( 'Gross unit price: %s', 'loremipsum' ), wc_price($price * $unit_number_extracted) );
    } else if( (!empty($unit) ) AND $unit_number_extracted > 1 ) {
        $unit_price = sprintf( __( 'Gross unit price: %s', 'loremipsum' ), wc_price($price / $unit_number_extracted) );
    }

    $data['price_html'] .= '<span> ' . $unit_price . '</span>';
    return $data;
}
add_filter( 'woocommerce_available_variation', 'product_variation_unit_price', 10, 3 );

I guess I should foreach the variations, but I don't know how to do that in this situation.
Thanks if you can help!


text:
Q: Swift TableView Cell I am trying to create tableView cells and customize the layout. But it seems anything I add inside my cells get stuck being the same size height and width as the cell itself. How can I make it to where I can design my cells however I like? i.e, make my images a specific size with margins and paddings. Even my text height is being stretched out to the cells height. I added the borders so that it's visible for what I mean. The height of my label should be just the size of the text itself but it is still stretching.
I am stuck on tableview cells and want to design my cell layout fully programmatically without storyboarding. I've been trying to teach myself all day and just keep going in circles.
import UIKit

    class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

        let tableView = UITableView()

        override func viewDidLoad() {
            super.viewDidLoad()

            self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
            self.tableView.delegate = self
            self.tableView.dataSource = self
            self.view.addSubview(self.tableView)
        }

        override func viewDidLayoutSubviews() {
            super.viewDidLayoutSubviews()
            tableView.frame = view.bounds
        }

        func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            tableView.deselectRow(at: indexPath, animated: true)
        }

        func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
            return 200
        }

        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return 8
        }

        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

            cell.textLabel?.text = "Here is some text"
            cell.textLabel?.layer.cornerRadius = 10
            cell.textLabel?.layer.borderWidth = 5
            cell.textLabel?.layer.borderColor = UIColor.black.cgColor

            cell.imageView?.image = UIImage(named: "spiderman")!
            cell.imageView?.layer.cornerRadius = 10
            cell.imageView?.layer.borderWidth = 5
            cell.imageView?.layer.borderColor = UIColor.black.cgColor
            return cell
        }
    }

A: Thats because you are using UITableViewCell's default textLabel
If you open a storyboard and play around with cell with 'basic' style, you will see that the text is always aligned to center.
I dont think you can adjust height or position of these two predefined properties (.textLabel and .imageView) directly.
Try to create imageView and label manually, and dont use cell.textLabel directly.
Example:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

    let label = UITextView(frame: CGRect(x: 200, y: 0, width: 500, height: 50))
    label.text = "Here is some text"
    label.layer.cornerRadius = 10
    label.layer.borderWidth = 5
    label.layer.borderColor = UIColor.black.cgColor
    cell.addSubview(label)

    let image = UIImage(named: "spiderman")!
    let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
    imageView.image = image
    imageView.layer.cornerRadius = 10
    imageView.layer.borderWidth = 5
    imageView.layer.borderColor = UIColor.black.cgColor
    cell.addSubview(imageView);
    return cell
}


text:
Q: Multi-Tenant application using Azure Active Directory We want to develop a multi-tenant web application where the tenants could use one or more of the following identity providers:

*

*Microsoft LiveID(Microsoft Account)

*Windows Azure Active Directory (WAAD)

*Office 365

*ADFS

We have evaluated ACS and it works with all the above identity providers. However it is being deprecated in favor of Windows Azure Active Directory. We looked into Azure AD and it does support creating multi-tenant applications which are backed by Azure AD / Office 365 tenants. This helps us to support customers having Azure AD instance or Office 365.
I would like to know whether:

*

*Azure AD supports federation scenarios with ADFS and Microsoft Account as well?

*In case of ADFS, will it also support SSO?

*Does Azure AD support features like Custom Login screen and Home Realm Discovery (HRD) similar to ACS?

*Will Azure AD help in supporting tenants who want to use multiple identity providers(e.g. both Microsoft Account and ADFS)?

Also, as per our application requirements, we do not want to store any of tenant/customer user account details in our Azure AD instance. We would like Azure AD to take care of authentication and SSO with identity providers mentioned above without any need of storing tenant/customer info.

A: *

*As of today Azure AD (AAD) can only connect to ADFS when the latter represents the on-premises directory connected to the corresponding AAD tenant. ADFS instances ran by different organizations are not directly supported, though the can be used if they are themselves projected via AAD. Microsoft Accounts are supported as guests - if you add one Microsoft Account to your directory, you'll be able to accept it in your applications.

*In case of ADFS: if the constraint above is respected (the ADFS instance is the one connected to AAD) then yes, you'll get SSO

*As of today, it does not. You can however customize specific parts of the authentication page (logo, etc)

*See #1

In the case of multitenancy, you don't need to store any info in your AAD. When a user from a new AAD tenant consent to the use of your app, a corresponding entry will appear in their own directory.
HTH
V.


text:
Q: Poisson process and queuing system In a queuing system, the inter-arrival times are known to be exponentially distributed.
My textbook states: "It can be shown that, if the underlying distribution of inter-arrival times { T1, T2, ..., Tn } is exponential, the arrival times are uniformly distributed on the interval (0, T). The arrival times- T1, (T1 + T2), (T1 + T2 + T3), ... , (T1 + ... + Tn) are obtained by adding inter-arrival times."
But isn't the sum of exponential random variables distributed as Erlang? Implying that arrival times should be Erlang distributed?
How are arrival times distributed? Is the distribution of arrival times Uniform or Erlang? Why so? I'd like some clarity on the topic.

A: If interarrival times ($IA$) are i.i.d. $IA\sim \text{Exponential}(\lambda)$ then the $n$th arrival time is $S_n \sim \text{Erlang}(n,\lambda)$. as a quick check, you can see that $S_1 \sim \text{Erlang}(1,\lambda)$ which is the same as $\text{Exponential}(\lambda)$.
However, the textbook is giving you more info. Given that the arrival times are on the interval $[0,T]$, they are distributed uniformly on that interval as a consequence of the interarrival distribution (or alternatively, a consequence of a stationary Poisson Process).
Notice the difference between arrival time $S_n$ and this conditional arrival time $(S_n|S_n\in [0, T])$
$$(S_n|S_n\in [0, T])\sim \text{Uniform}(0, T)$$.
This extends to the case $(S_n|S_n\in [t_1, t_2])\sim \text{Uniform}(t_1, t_2)$ with $t_1<t_2$.
See the proof/derivation here on Math.SE.

With Exponential interarrivals, $(S_n|S_n\in [t_1, t_2])\sim \text{Uniform}(t_1, t_2)$ for $t_1<t_2$ doesn't invalidate that $S_n \sim \text{Erlang}(n,\lambda)$.  For a visual example, see two graphs below generated with the same Exponential interarrival times.

MATLAB code:
Rate = .85;
ArrivalNumber = 5;
SampleSize = 50000;
% Add Interarrival Times
S5 = sum((-1/Rate)*log(1-rand(SampleSize,ArrivalNumber)),2);

fh=@(x) ((Rate^ArrivalNumber)*x.^(ArrivalNumber-1).*exp(-Rate.*x))...
    ./factorial(ArrivalNumber-1);  % Erlang PDF
Times = cumsum((-1/Rate)*log(1-rand(20000,50)),2);
IntervalTimes = [];
Interval = [15 35];
for i = 1:size(Times,1)
    Times_i = Times(i,:);
    IntervalTimes_i = Times_i(Times_i >= Interval(1) & Times_i <= Interval(2));
    IntervalTimes = [IntervalTimes; IntervalTimes_i(:)];
end

figure, hold on, box on
title('Event Times on Interval [15, 35]')
h = histogram(IntervalTimes,'Normalization','pdf','DisplayName','Simulation')
xlim([0 40])
p = plot([15 35],ones(1,2)./(35-15),'k-','LineWidth',2.2,'DisplayName','Uniform(15,35)')
xlabel('Arrival Times on Interval [15, 35]')
ylabel('PDF')
legend('show')

figure, hold on, box on
title('S_5 \sim Erlang(5,\lambda = 0.85)')
h = histogram(S5,'Normalization','pdf','DisplayName','Sum of Exponential(\lambda)')
Xrange = 0:.01:25;
p = plot(Xrange,fh(Xrange),'k-','LineWidth',2.2,'DisplayName','Erlang(5,\lambda)')
xlim([0 20])
legend('show')
xlabel('5th Arrival Time, S_5')
ylabel('PDF')


text:
Q: Can someone explain what is the force the ball will exert? If a ball is falling under free fall then the force exerted by the ball on the ground would be $mg$. But that's not the case in real life ball would hit with more force. But when i draw free body diagram there is only one force that is acting on it $mg$
Can someone explain what is the force the ball will exert ?

A: Interesting question. Ball force affecting ground is $$ F_c = \frac{\Delta p}{t_i} = \frac{mv}{t_i}  $$, because end speed is zero.
Now let's assume ball started to fall from some altitude, so it reached it's "contacting" speed $v$ according to :
$$ v = v_0 + a \space t = g \space t_f $$
Plunging this into formula above, we get :
$$ F_c = \frac{mg \space t_f}{t_i} = W \frac{t_f}{t_i} $$
So ball force affecting ground is it's weight scaled by falling time over interaction time with ground ratio.
Analogically ground will exert normal force with same magnitude on ball. That's why eggs breaks falling down :-)
Only in case when $ t_f \approx t_i $, i.e. when falling time approaches interaction time, contact force equals weight. This principle is exploited in various kinds of trampolines and Life net used by firefighters.

A: The ground must do work on the falling ball to bring it to a stop. From the work energy theorem the net work done on the ball equals its change in kinetic energy or
$$F_{Ave}d=\frac{mv^2}{2}=mgh$$
$$F_{Ave}=\frac{mgh}{d}$$
Where $F_{Ave}$ = average impact force, $d$ = stopping  distance after impacting the ground due to deformation of the ground and/or ball, and $h$ = height from which the ball dropped. Assumes $d$ << $h$ to neglect the change in potential energy after impact
Hope this helps

A:
the force exerted by the ball on the ground would be $mg$

Why do you say that?
The force that the ball exerts on the ground depends on the modulus of elasticity (stiffness) of the ground and can be very high. The normal reaction of the ground stops the ball over a certain distance. If the modulus of elasticity of the ground is high, the stopping distance is short and the force of reaction is high.

A: perhaps you also want to calculate the contact force between the ball and the ground.
your ball  is falling from height $H$ with start velocity $v_0$   and then touch the ground. if we take a simple model of the ground with stiffness $k$ and damper $d$  you get this equation of motion.
$$m\ddot{x}+d\,\dot{x}+k\,x=m\,g\tag 1$$
your contact force is the spring plus the damper force  (free body diagram)
$$F_c=d\,\dot{x}+k\,x$$
to find the solution of equation (1), you need the initial conditions:
$x(t=0)=0$
$\dot{x}(t=0)=v_e$
where $v_e$ is the velocity of your ball when it touch the ground:
$v_e=\sqrt{v_0^2+2\,g\,H}$
where $v_0$ is the start velocity of ball.
This diagram shows the contact force :

the blue line is the weight of the ball. the red one is the start velocity $v_0=0$ and the green one the start velocity is $v_0=10$
you see that your contact force is much higher then the  weight force and is depending on the velocity $v_e$ which is a function of the height $H$ and the start velocity $v_0$


text:
Q: Looking to get specific value from list inside of a dict I have a list of data below. I am trying to pull "bid_price" from the data.
current = requests.get("https://www.deribit.com/api/v2/public/get_book_summary_by_instrument?instrument_name=BTC-PERPETUAL").json()

Using print(current), I receive this data
{
   'jsonrpc':'2.0',
   'result':[
      {
     'volume_usd':566908519.99,
     'volume':79073.94,
     'quote_currency':'USD',
     'open_interest':48034981,
     'mid_price':7059.63,
     'mark_price':7060.06,
     'low':6686.25,
     'last':7057.75,
     'instrument_name':'BTC-PERPETUAL',
     'high':7581.75,
     'funding_8h':1.576e-05,
     'estimated_delivery_price':7057.61,
     'current_funding':0.0,
     'creation_timestamp':1557711700003,
     'bid_price':7059.5,
     'base_currency':'BTC',
     'ask_price':7059.75
      }
   ],
   'usIn':1557711700003222,
   'usOut':1557711700003412,
   'usDiff':190,
   'testnet':False
}

I have tried to use "xbt_bid_price = current['result']['bid_price']" - which throws a "TypeError: list indices must be integers or slices, not str". I am unsure how to gain access to the "bid_price" value specifically. It seems like this should be easy to do, but for some reason I cannot seem to figure this one out.
FWIW, I have also tried "xbt_bid_price = (current.get[0]0)" -- which failed as well.
EDIT:
Question has been solved, all answers provided worked - thanks! Command needed was: xbt_bid_price = current['result'][0]['bid_price']

A: When you do current['result']['bid_price'], you provide the index bid_price to the list current[result] which results in an error TypeError: list indices must be integers or slices, not str".
So you need to use list indexes in order to fetch your data, by iterating over the list.
current = {
   'jsonrpc':'2.0',
   'result':[
      {
     'volume_usd':566908519.99,
     'volume':79073.94,
     'quote_currency':'USD',
     'open_interest':48034981,
     'mid_price':7059.63,
     'mark_price':7060.06,
     'low':6686.25,
     'last':7057.75,
     'instrument_name':'BTC-PERPETUAL',
     'high':7581.75,
     'funding_8h':1.576e-05,
     'estimated_delivery_price':7057.61,
     'current_funding':0.0,
     'creation_timestamp':1557711700003,
     'bid_price':7059.5,
     'base_currency':'BTC',
     'ask_price':7059.75
      }
   ],
   'usIn':1557711700003222,
   'usOut':1557711700003412,
   'usDiff':190,
   'testnet':False
}

#Iterate over the list result
for li in current['result']:
    #Get the bid price
    print(li.get('bid_price'))

The output will be
7059.5

A: try this out:
your data:
current = {
   'jsonrpc':'2.0',
   'result':[
      {
     'volume_usd':566908519.99,
     'volume':79073.94,
     'quote_currency':'USD',
     'open_interest':48034981,
     'mid_price':7059.63,
     'mark_price':7060.06,
     'low':6686.25,
     'last':7057.75,
     'instrument_name':'BTC-PERPETUAL',
     'high':7581.75,
     'funding_8h':1.576e-05,
     'estimated_delivery_price':7057.61,
     'current_funding':0.0,
     'creation_timestamp':1557711700003,
     'bid_price':7059.5,
     'base_currency':'BTC',
     'ask_price':7059.75
      }
   ],
   'usIn':1557711700003222,
   'usOut':1557711700003412,
   'usDiff':190,
   'testnet':False
}

here you can get bid price
v = current['result'][0]['bid_price']
print(v)

output
7059.5

A: current["result"] gives a list with one item (the dictionary) as there are square brackets before the braces.
Try the following to get the bid price.
    xbt_bid_price = current["result"][0]["bid_price"]


text:
Q: Showing month value when no data exists SQL Server I have a SQL Server 2012 table that holds session per user and I need to find out monthly total of minutes for activity and if there are no results for the month then to show "0". Table below:
User   SessionStart              SessionEnd
1      2014-03-01 08:00:00.000   2014-03-01 08:10:00.000
1      2014-03-15 09:00:00.000   2014-03-15 09:30:00.000
1      2014-05-01 04:00:00.000   2014-05-01 04:50:00.000
1      2014-06-01 02:00:00.000   2014-06-01 02:05:00.000
1      2014-07-01 09:00:00.000   2014-07-01 10:30:00.000
1      2014-09-01 01:00:00.000   2014-09-01 01:07:00.000
1      2014-12-05 08:00:00.000   2014-12-05 08:10:00.000
2      2014-01-01 01:01:00.000   2014-01-01 01:11:00.000
1      2015-03-01 08:00:00.000   2015-03-01 08:10:00.000
1      2015-05-01 04:00:00.000   2015-05-01 04:50:00.000
1      2015-06-01 02:00:00.000   2015-06-01 02:05:00.000
...    ...                       ...

What I'm ending up with is:
User   Month   Year   Minutes
1      3       2014   40
1      5       2014   50
1      6       2014   5
1      7       2014   90
1      9       2014   7
1      12      2014   10
1      3       2015   10
1      5       2015   50
1      6       2015   5

What I'd like to get:
User   Month   Year   Minutes
1      1       2014   0
1      2       2014   0
1      3       2014   40
1      4       2014   0
1      5       2014   50
1      6       2014   5
1      7       2014   90
1      8       2014   0
1      9       2014   7
1      10      2014   0
1      11      2014   0
1      12      2014   10
1      1       2015   0
1      1       2015   0
1      3       2015   10
1      4       2015   0
1      5       2015   50
1      6       2015   5

I've tried using:
SELECT User
      ,MONTH(SessionStart)
      ,YEAR(SessionStart)
      ,SUM(DATEDIFF(minute, SessionStart, SessionEnd)) AS Minutes
FROM SessionTable
WHERE User = 1 AND YEAR(SessionStart) >= 2014
GROUP BY SessionStart, User

I have a table called "Months" that holds the number of the month (Month) and name of the month (MonthName) and have tried performing a left outer join on this table and have also tried using case selects. I've searched on this issue on Stackoverflow and see somewhat similar issues, but not one that involves using the date. Struggling to think today...

A: You can generate all the rows with a cross join and then use left join to bring in your summaries.  Assuming that some row exists for each month, you can get this information from the session table itself:
SELECT u.User, yyyymm.mm, yyyymm.yy
       COALESCE(SUM(DATEDIFF(minute, s.SessionStart, s.SessionEnd)), 0) AS Minutes
FROM (SELECT 1 as user) u CROSS JOIN
     (SELECT DISTINCT YEAR(SessionStart) as yyyy, MONTH(SessionStart) as mm
      FROM SessionTable
      WHERE SessionStart >= '2014-01-01'
     ) yyyymm LEFT JOIN
     SessionStart ss
     ON u.user = ss.user AND
        YEAR(SessionStart) = yyyymm.yy AND MONTH(SessionStart) = yyyymm.mm
GROUP BY u.User, yyyymm.yyyy, yyyymm.mm;

A: You're on the right track with your months table. Could you post your example that's not working using the left outer join?  If you start with months and left outer join to your SessionTable you should be fine.
Something like...
SELECT User
      ,MONTH(m.month)
      ,YEAR(m.year)
      ,SUM(DATEDIFF(minute, s.SessionStart, s.SessionEnd)) AS Minutes
FROM Months m
  LEFT OUTER JOIN SessionTable s
    ON m.year = s.year
    AND m.month = s.month
    AND s.User = 1
WHERE YEAR(m.year) >= 2014
GROUP BY s.SessionStart, s.User

NOTE:

*

*Don't filter your sessionTable data in the where clause when you're using month as the primary data source - filter it in the LEFT OUTER JOIN.  If you put it in the WHERE, you're turning things into an INNER JOIN.

*You want to use your months table when returning your data for the month/year info

That work?

A: You need to have a calendar table which is generally a list of predefined dates with in some range..
You need to have months table for your need..which can be generated using numbers table ..
This is a Pseudo code only:
create table months
(
monthdate datetime
)

insert into monthdate
select dateadd(day,n,getdate()-10000)
from numbers
where n<=10000

Now you have months table ,all you need to do is a left join
select *
from monthstable mt
join yourtable yt
on yt.date=mt.date

This way you will preserve all dates which you dont have as well
** some good links :**
http://www.sqlservercentral.com/blogs/dwainsql/2014/03/30/calendar-tables-in-t-sql/
http://www.sqlservercentral.com/articles/T-SQL/62867/


text:
Q: Wordpress: Issue registering/enqueueing style sheet New to wordpress and I can't get stylesheets to load in my plugin. Either that or thier effects are being overridden. This is what I have in my main plugin.php file:
function load_pc_scripts() {
    wp_register_style('plugin-style', plugin_dir_url(__FILE__) . 'plugin-style.css');
    wp_enqueue_style('plugin-style');
  }
  add_action('wp_enqueue_scripts', 'load_pc_scripts');

The style sheet is in the same directory but console shows this:
plugin-style.css:1 Failed to load resource: the server responded with a status of 404 (Not Found)
load-scripts.php?c=0&load[]=jquery-core,jquery-migrate,utils&ver=5.1.1:8 JQMIGRATE: Migrate is installed, version 1.4.1
plugin-style.css:1 Failed to load resource: the server responded with a status of 404 (Not Found)
options-general.php?page=price-compare-settings:1 Unchecked runtime.lastError: The message port closed before a response was received.
plugin-style.css:1 Failed to load resource: the server responded with a status of 404 (Not Found)

A: If the console is showing a 404 then enqueue is working, you likely have a typo in the file name or party in one place or another