text:
Q: How to pass parameter to an API get request in react.js I wonder is there a way to pass a parameter from the client to the back-end API get Request. At this moment I hard coded the needed argument (name:"newName").
back-end route:
app.get('/api/get/beerWithComments', (req,res,next) =>{

    Beer.findOne({name:'newName'}) //I want to pass the correct name, now it's hard coded.
        .populate('comments').exec((err,beer) =>{
            if(err) return next(err);
            res.json(beer);
        });

});

My action method:
  export const fetchBeerWithComments =() => async dispatch => {
    const res= await axios.get('/api/get/beerWithComments');
    dispatch({type: FETCH_BEER_WITH_COMMENTS, payload : res.data });

}

I thought to pass the parameter here in. But I don't know if I can pass the argument to my back-end.
export const fetchBeerWithComments =(parameter) => async dispatch => {...

A: You can pass the parameter name in the query string and read the parameter value in handler using req.query like
app.get('/api/get/beerWithComments', (req, res, next) =>{
  var qname = req.query.name || "";
  if(!qname.length) {
    res.status(404).json({"msg": 'Invalid name in query string'});
    res.end();
    return;
  }
  Beer.findOne({name: qname}) //I want to pass the correct name, now it's hard coded.
    .populate('comments').exec((err,beer) =>{
        if(err) return next(err);
        res.json(beer);
    });
});

And while calling GET API from the client side just add query string param name with respective value and it should work as you expected.
for eg URL will be like
export const fetchBeerWithComments =(parameter) => async dispatch => {
  const res= await axios.get('/api/get/beerWithComments?name=' + parameter);
  dispatch({type: FETCH_BEER_WITH_COMMENTS, payload : res.data });
}

A: If you need to pass it back you could just change the api endpoint to have a dynamic parameter e.g change the get endpoint to:
/api/get/beerWithComments/:beerName
So on the front end you can have
 export const fetchBeerWithComments = (beerName) => async dispatch => {
    const res= await axios.get(`/api/get/beerWithComments/${ beerName }`);
    dispatch({type: FETCH_BEER_WITH_COMMENTS, payload : res.data });
 }

And then on the backend
app.get('/api/get/beerWithComments/:beerName', (req,res,next) =>{
    Beer.findOne({name: req.params.beerName})
        .populate('comments').exec((err,beer) => {
            if(err) return next(err);
            res.json(beer);
     });
});


text:
Q: Rest Service to read a zip file in a client I am trying to implement a rest service that reads a zip file. A client calls this service, and builds the zip file from the response. I have this for my service:
@Produces({ "application/zip" })
@GET
@Path("/fetchZip")
public Response getZip() {
try {
    InputStream theFile = new FileInputStream("test.zip");
    ZipInputStream zis = new ZipInputStream(theFile);
    return Response.ok(zis).build();
} catch (Exception e) {
    e.printStackTrace();
}
return null;
}

Can anyone let me know if this is the right way to do it?

A: Try something like this, reading from the InputStream of the response and writing into FileOutputstream for the file:
     URL url = new URL("YOUR_URL");
     HttpURLConnection conn = (HttpURLConnection) url.openConnection();
     conn.setDoOutput(true);
     conn.setRequestMethod("GET");
     conn.setRequestProperty("Content-Type", "application/json");
     if (conn.getResponseCode() == 200) {
        InputStream inputStream = conn.getInputStream();
        OutputStream output = new FileOutputStream("C:/yourFile.zip");
        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
           output.write(buffer, 0, bytesRead);
        }
        output.close();
     }
     conn.disconnect();

redpajama_set_name: RedPajamaStackExchange


text:
Q: Java / Android: from string to decimal or int Thousand separator: "." (dot)
Decimal separator: "," (comma).
I live in Italy.
I'm getting from API this value (it's a string):
"balance":"1254.00".

In a case I need to convert it in an integer value:
1.254

without the decimal part (also if it is not zero, without round up or down).
In another case I could have (it's a string):
"balance":"1234.56"

And in that case I need
1.234,56

Going crazy with several functions, not getting my goal.
E.g. I tried:
NumberFormat numberFormat = new DecimalFormat("#,##");
BigDecimal balance_numeric = new BigDecimal(this.raw_balance.replaceAll(",", ""));
balance = String.valueOf(numberFormat.format(balance_numeric));

And getting for first case (1254) an 12,54 , no sense for me.
Thank you very much.

A: The code is pretty much self-explanatory. Do comment if you need help.  :)
DecimalFormat format = new DecimalFormat();
DecimalFormatSymbols sm = DecimalFormatSymbols.getInstance();
sm.setDecimalSeparator(',');
sm.setGroupingSeparator('.');
format.setDecimalFormatSymbols(sm);
System.out.println(format.format(1254.02));

EDIT 1
There is an alternative which I didn't know about.
NumberFormat nf = NumberFormat.getNumberInstance(Locale.ITALIAN);
DecimalFormat df = (DecimalFormat)nf;

You can use the Locale to do awesome stuff!

A: If I understand right, the API always returns a decimal number. If the decimal part is zero you want the integer part of the number. If not, you wants the whole decimal number.
    String s = "1234.00";
    Double d = new Double(s);

    double f = d - d.longValue();
    if (f == .0) {
        // format d.longValue() as int
    } else {
        // format d as double
    }


text:
Q: Scatter plot with ggplot2 I am trying to make scatter plot with ggplot2. Below you can see data and my code.
 data=data.frame(
      gross_i.2019=seq(1,101),
      Prediction=seq(21,121))

   ggplot(data=data, aes(x=gross_i.2019, y=Prediction, group=1)) +
      geom_point()

This code produce chart below

So now I want to have values on scatter plot with different two different colors, first for gross_i.2019 and second for Prediction. I try with this code below with different color but this code this lines of code only change previous color into new color.
sccater <- ggplot(data=data, aes(x=gross_i.2019, y=Prediction))
sccater + geom_point(color = "#00AFBB")

So can anybody help me how to make this plot with two different color (e.g black and red) one for gross_i.2019 and second for Prediction?

A: I may be confused by what you are trying to accomplish, but it doesn't seem like you have two groups of data to plot two different colors for. You have one dependent(Prediction) and one independent (gross_i.2019) variable that you are plotting a relationship for. If Prediction and gross_i.2019 are both supposed to be dependent variables of different groups, you need a common independent variable to plot them separately, against (like time for example). Then you can do something like geompoint(color=groups)
Edit1: If you wanted the index (count of the dataset to be your independent x axis then you could do the following:
library(tidyverse)

data=data.frame(gross_i.2019=seq(1,101),Prediction=seq(21,121))

#create a column for the index numbers
data$index <- c(1:101)

#using tidyr pivot your dataset to a tidy dataset (long not wide)
data <- data %>% pivot_longer(!index, names_to="group",values_to="count")

#asign the groups to colors
p<- ggplot(data=data, aes(x=index, y=count, color=group))
p1<- p + geom_point()
p1

A: This type of problems generally has to do with reshaping the data. The format should be the long format and the data is in wide format. See this post on how to reshape the data from wide to long format.
long <- reshape(data,
                ids = row.names(data),
                varying = c("gross_i.2019", "Prediction"),
                v.names = "line",
                direction = "long")
long$time <- names(data)[long$time]
long$id <- as.numeric(long$id)

library(ggplot2)
ggplot(long, aes(id, line, color = time)) +
  geom_point() +
  scale_color_manual(values = c("#000000", "#00AFBB"))


text:
Q: Saving multiple dictionaries-of-lists from multiple files to a dictionary, then writing to file N files of with dictionaries-of-lists, saved as a.json, b.json...
{
"ELEC.GEN.OOG-AK-99.A": [
    ["2013", null],
    ["2012", 2.65844],
    ["2011", 2.7383]
],
"ELEC.GEN.AOR-AK-99.A": [
    ["2015", 217.30239],
    ["2014", 214.46868],
    ["2013", 197.32097]
],
"ELEC.GEN.HYC-AK-99.A": [
    ["2015", 1542.29841],
    ["2014", 1538.738],
    ["2013", 1345.665]
]}

I am unclear how to save them all to one large dictionary/json file, like so:
{
"a":
    {
    "ELEC.GEN.OOG-AK-99.A": [
        ["2013", null],
        ["2012", 2.65844],
        ["2011", 2.7383]
    ],
    "ELEC.GEN.AOR-AK-99.A": [
        ["2015", 217.30239],
        ["2014", 214.46868],
        ["2013", 197.32097]
    ],
    "ELEC.GEN.HYC-AK-99.A": [
        ["2015", 1542.29841],
        ["2014", 1538.738],
        ["2001", 1345.665]
    ]},
"b": {...},
...
}

This is data I requested that will be used in a javascript graph, and it is theoretically possible to preprocess it even more when streaming the requested data from its source, as well as maybe possible to work around the fact there are so many data files I need to request to get my graph working, but both those options seem very difficult.
I don't understand the best way to parse json-that-is-meant-for-javascript in python.
====
I have tried:
from collections import defaultdict

# load into memory
data = defaultdict(dict)
filelist = ["a.json", "b.json", ...]
for fn in filelist:
    with open(fn, 'rb') as f:
        # this brings up TypeError
        data[fn] = json.loads(f)

# write
out = "out.json"
with open(out, 'wb') as f:
    json.dump(data, f)

===
For json.loads() I get TypeError: expected string or buffer. For json.load() it works!

A: you are using json.loads instead of json.load to load a file, you also need to open it for reading for string instead of bytes, so change this:
with open(fn, 'rb') as f:
    data[fn] = json.loads(f)

to this:
with open(f, 'r') as f: #only r instead of rb
    data[fn] = json.load(f) #load instead of loads

And again further down when writing open for w instead of wb

A: Loading from string:
>>> with open("a.json", "r") as f:
...     json.loads(f.read())
...
{u'Player2': 4, u'Player3': 10, u'Player1': 3}
>>>

Loading from file object:
>>> with open("a.json", "r") as f:
...     json.load(f)
...
{u'Player2': 4, u'Player3': 10, u'Player1': 3}
>>>


text:
Q: Pandas DataFrame multplication with missing values I have 2 dataframes
                 Value
Location Time
Hawai    2000  1.764052
         2002  0.400157
Torino   2000  0.978738
         2002  2.240893
Paris    2000  1.867558
         2002 -0.977278
                       2000  2002
Country Unit Location
US      USD  Hawai        2     8
IT      EUR  Torino       4    10
FR      EUR  Paris        6    12

Created with
np.random.seed(0)
tuples = list(zip(*[['Hawai', 'Hawai', 'Torino', 'Torino',
                     'Paris', 'Paris'],
                      [2000, 2002, 2000, 2002, 2000,2002]]))

idx = pd.MultiIndex.from_tuples(tuples, names=['Location', 'Time'])

df = pd.DataFrame(np.random.randn(6, 1), index=idx, columns=['Value'])

df2 = pd.DataFrame({'Country': [ 'US', 'IT', 'FR'],
                'Unit': [ 'USD', 'EUR', 'EUR'],
                  'Location': [ 'Hawai', 'Torino', 'Paris'],
                  '2000': [2, 4,6],
                    '2002': [8,10,12]
                   })
df2.set_index(['Country','Unit','Location'],inplace=True)

I want to multiply each column from df2 with the corresponding Value from df1
This code does well
df2.columns=df2.columns.astype(int)
s=df.Value.unstack(fill_value=1)
df2 = df2.mul(s)

and produces
              2000       2002
Country Unit Location
US      USD  Hawai      3.528105   3.201258
IT      EUR  Torino     3.914952  22.408932
FR      EUR  Paris     11.205348 -11.727335

Now I want to handle case where df2 has missing value represented as '..' so multiplying the numerical values and skip the others
    2000  2002
Country Unit Location
US      USD  Hawai       2     8
IT      EUR  Torino     ..    10
FR      EUR  Paris       6    12

running the code above give error TypeError: can't multiply sequence by non-int of type 'float'
Any idea how to achieve this result ?
2000       2002
    Country Unit Location
    US      USD  Hawai      3.528105   3.201258
    IT      EUR  Torino     ..  22.408932
    FR      EUR  Paris     11.205348 -11.727335

A: I think better here is use missing values instead .. by to_numeric with errors='coerce', so divide working very nice:
df2 = pd.DataFrame({'Country': [ 'US', 'IT', 'FR'],
                'Unit': [ 'USD', 'EUR', 'EUR'],
                  'Location': [ 'Hawai', 'Torino', 'Paris'],
                  '2000': [2, '..',6],
                    '2002': [8,10,12]
                   })
df2.set_index(['Country','Unit','Location'],inplace=True)

df2.columns=df2.columns.astype(int)
s= df.Value.unstack(fill_value=1)
df2 = df2.apply(lambda x: pd.to_numeric(x, errors='coerce')).mul(s)
print (df2)
                            2000       2002
Country Unit Location
US      USD  Hawai      3.528105   3.201258
IT      EUR  Torino          NaN  22.408932
FR      EUR  Paris     11.205348 -11.727335

If only non numeric values are .. another solution is use replace:
df2 = df2.replace('..', np.nan).mul(s)


text:
Q: Creating a 3D Matrix in R based on the presence of some specific values in groups of data in a data set I am working with a data set in R, suppose mtcars:
                   mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Mazda RX4         21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag     21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
Datsun 710        22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive    21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout 18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2
Valiant           18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
Duster 360        14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4
Merc 240D         24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2
Merc 230          22.8   4 140.8  95 3.92 3.150 22.90  1  0    4    2
Merc 280          19.2   6 167.6 123 3.92 3.440 18.30  1  0    4    4

Now I want to create a matrix for each type of transmission am: (0 = automatic, 1 = manual) that shows if any of the levels of variable carb is present in any of the levels of variable cyl. Put it differently, if cyl can have the values of 4 , 6 and 8 and 1, 2, 3, 4, 6 and 8 are the possible values for variable carb, I want a 3x6 matrix for each transmission type whose elements are 1 if each combination of cyl-carb is present in our data and 0 otherwise. Thus, the resulting matrix should be of dimension 2x3x6. e.g. :
(These matrices are here only for illustrative purposes and their elements are chosen arbitrarily by myself in order to better explain what kind of output I expect)
for am == 0
  1 2 3 4 6 8
4 0 0 1 0 1 0
6 1 0 0 1 1 1
8 0 1 0 0 1 0

for am == 1
  1 2 3 4 6 8
4 1 0 0 0 1 0
6 0 1 0 1 0 0
8 0 1 1 0 1 1

I know that dplyr is quite handy for such data manipulation, but I do not know how to use it in this case where I want to create a matrix based on the groups of variables in another data frame?!
Any help is greatly appreciated.

A: Here's a not-quite-elegant brute force approach:
mtcars

res <- with(mtcars, array(
    data = 0L,
    dim = c(
        length(unique(cyl )),
        length(unique(carb)),
        length(unique(am  ))
    ),
    dimnames = list(
        paste("cyl",  sort(unique(cyl )), sep = "_"),
        paste("carb", sort(unique(carb)), sep = "_"),
        paste("am",   sort(unique(am  )), sep = "_")
    )
))

for(x in seq_len(dim(res)[1])) {
    for(y in seq_len(dim(res)[2])) {
        for(z in seq_len(dim(res)[3])) {
            if (any(
                mtcars$cyl  == readr::parse_number(dimnames(res)[[1]][x]) &
                mtcars$carb == readr::parse_number(dimnames(res)[[2]][y]) &
                mtcars$am   == readr::parse_number(dimnames(res)[[3]][z])
            )) {
                res[x, y, z] <- 1L
            }
        }
    }
}

res

A: We can split the subset of data by the 'am' column and get the table
# convert the 'carb' column to `factor` with `levels` specified
# inorder to get all the combinations
mtcars$carb <- factor(mtcars$carb, levels = sort(unique(mtcars$carb)))
lapply(split(mtcars[c("cyl", "carb")], mtcars$am), function(x) +(table(x) > 0))


text:
Q: MySql - Change return value if value exists in another table I m using the selectSellerID function to retrieve a user's id.
public function selectSellerID($item_id)
{
    if($q = $this->db->mysqli->prepare("SELECT user_id FROM items WHERE id = ?"))
    {
        $q->bind_param("i", $item_id);
        $q->execute();
        $q->bind_result($id);
        $q->fetch();
        $q->close();

        return $id;
    }
        return false;
}

The item_id can also appear in another table which is the resell table. In this case the user_id will change. Below is the resell table.
+----+---------+---------+-------+------+
| id | user_id | item_id | price | date |
+----+---------+---------+-------+------+
|  2 |      18 |      27 |    91 | NULL |
|  3 |       1 |      27 |    90 | NULL |
|  4 |       1 |      27 |    75 | NULL |
+----+---------+---------+-------+------+

So I need to change the function to check if the item_id is presend in the resell table, then only grab the latest user_id, as it may be resold multiple times. What is the best way to change the function other than doing a second query?

A: You can use MySQL JOINS.
Joining items table with resell table and then ordering the result set with highest id will give the desired results.
Try below query:
SELECT IF(r.user_id IS NULL, i.user_id, r.user_id) AS user_id
FROM items i
LEFT JOIN resell r
ON i.id = r.item_id
WHERE i.id = ?
ORDER BY r.id DESC
LIMIT 1

A: Use LEFT JOIN
$q = $this->db->mysqli->prepare("SELECT rsl.user_id FROM items itms LEFT JOIN resell rsl ON itms.id = rsl.item_id WHERE itms.id = ? ORDER BY rsl.id DESC LIMIT 1");


text:
Q: Wordpress admin menu messed Today I have a really strange problem. My WordPress admin menu is a mess and disappears on hover. I've tried deactivating all the plugins, changing the theme, but nothing works.
Has anyone any ideas? I cannot check in "Firebug", because if I open it, my menu reloads and everything appears fine. It's the same if I refresh the page, but without change url. You can see it in the print screen.
I don't use any custom admin style or scripts.
Wordpress 4.3

A: Which browser are you using? There is a known bug in chrome more info here: http://wptavern.com/a-bug-in-chrome-45-causes-wordpress-admin-menu-to-break

The source of the problem stems from Slimming Paint which is enabled
  by default in Chrome 45. Disabling slimming paint fixes the issue.
To disable this feature, visit chrome://flags/#disable-slimming-paint
  in Chrome and Enable the Disable slimming paint option, and make sure
  the other two Enable options are disabled because they will override
  the Disable option.

Also from the sounds of it looks like google will be fixing this as well soon

the Chrome Development bumped up the priority of the bug and a fix is
  likely come out before version 47
  https://code.google.com/p/chromium/issues/detail?id=509179

A: Add this to your functions.php to fix the bug not only in your browser but also in your client's. I tested it and worked well.
function admin_menu_fix() {
    echo '<style>
    #adminmenu { transform: translateZ(0); }
    </style>';
}
add_action('admin_head', 'admin_menu_fix');

Source: https://code.google.com/p/chromium/issues/detail?id=509179#c37 (page found by @NooBskie)

A: Chrome has a rendering bug. There is a ticket open on Chrome's bug tracker about this issue, hopefully they will fix it soon.
In the meantime, here is a solution to eliminate the issue in Chrome.

*

*Go chrome://flags/#disable-slimming-paint

*Enable the "Disable slimming paint" option.

*Ensure that the "Enable slimming paint" option below it is not turned on.

*Then Relaunch Chrome.

Hope the problem will fixed.
You can also try the solution:
https://code.google.com/p/chromium/issues/detail?id=509179#c37
This worked for me

A: I think this going to be a short-lived thing, but a very weird one (especially compounded with hunting plugin breakages related to WordPress 4.3 simultaneously).
I just updated Google Chrome to the latest version and it is resolved. Before attempting any unusual fixes, I would recommend going to Chrome -> About Google Chrome first to make sure you're running the latest.

A: Official Solution:
Disable slimmingPaint feature in chrome
1) In Chrome browser, navigate to: chrome://flags/#disable-slimming-paint (just enter the text into the address bar and hit enter)
2) You'll see a list of technical options, with the "Disable slimming paint" option at the top; enable it
3) Disable the "Enable slimming paint" option if it's enabled; just under the "Disable slimming paint" one
4) Relaunch Chrome

Other Solution:
If you or your clients don't want to disable the Slimming Paint feature, then you can get around the bug by adding the following code into your theme functions.php file:
add_action('admin_enqueue_scripts', 'chrome_adminmenu_fix');

function chrome_adminmenu_fix() {
    if ( strpos( $_SERVER['HTTP_USER_AGENT'], 'Chrome' ) !== false )
        wp_add_inline_style( 'wp-admin', '#adminmenu { transform: translateZ(0); }' );
}

A: I found the settings a little confusing at first, here's the simplification (possibly):

*

*Visit chrome://flags/#disable-slimming-paint in Chrome

*All the slimming paint options that have Disable keyword in their
hashtag/flag must be in Enable state

*All the slimming paint options that have Enable keyword in their
hashtag/flag must be in Disable state


text:
Q: Failure to boot Xen 4.1.2 kernel 2.6.32.40 with Ubuntu 10.04.4 After successful creation of the Xen kernel and entry into grub, whenever I try and boot into the Xen kernel I receive the following error:
Gave up waiting for root device. Common problems:
  — Boot args (cat /proc/cmdline)
    — Check rootdelay= (did the system wait long enough?)
    — Check root= (did the system wait for the right device?)
  — Missing modules (cat /proc/modules; ls /dev)
ALERT! /dev/sda6 does not exist.
Dropping to a shell!

Here is the entry in /boot/grub/menu.lst
title           Xen 4.1.2 / Ubuntu 10.04.4 kernel 2.6.32.40 (root=sda6)
uuid            8edf0e1b-5f9c-4ca0-8f88-77d35af87093
#root           (hd0,1)
kernel          /xen-4.1.2.gz dom0_mem=4096M,max:4096M loglvl=all guest_loglvl=all
module          /vmlinuz-2.6.32.40 dummy=dummy root=/dev/sda6 ro console=tty0 nomodeset rootdelay=50
module          /initrd.img-2.6.32.40

A section of the boot information file is provided below:
============================= Boot Info Summary: ==============================

 => Grub0.97 is installed in the MBR of /dev/sda and looks on the same drive
    in partition #2 for /grub/stage2 and /grub/menu.lst.

sda1: _________________________________________________________________________

    File system:       ext2
    Boot sector type:  Grub
    Boot sector info:  Grub0.97 is installed in the boot sector of sda1 and
                       looks at sector 4462688 of the same hard drive for the
                       stage2 file. A stage2 file is at this location on
                       /dev/sda. Stage2 looks on partition #2 for
                       /grub/menu.lst.
    Operating System:
    Boot files/dirs:

sda2: _________________________________________________________________________

    File system:       ext4
    Boot sector type:  Grub
    Boot sector info:  Grub0.97 is installed in the boot sector of sda2 and
                       looks at sector 4462688 of the same hard drive for the
                       stage2 file. A stage2 file is at this location on
                       /dev/sda. Stage2 looks on partition #2 for
                       /grub/menu.lst.
    Operating System:
    Boot files/dirs:   /grub/menu.lst /grub/grub.cfg /grub/core.img

sda3: _________________________________________________________________________

    File system:       Extended Partition
    Boot sector type:  -
    Boot sector info:

sda5: _________________________________________________________________________

    File system:       swap
    Boot sector type:  -
    Boot sector info:

sda6: _________________________________________________________________________

    File system:       ext4
    Boot sector type:  -
    Boot sector info:
    Operating System:  Ubuntu 10.04.4 LTS
    Boot files/dirs:   /boot/grub/menu.lst /boot/grub/grub.cfg /etc/fstab
                       /boot/grub/core.img

sda7: _________________________________________________________________________

    File system:       ext4
    Boot sector type:  -
    Boot sector info:
    Operating System:  Ubuntu 10.04.4 LTS
    Boot files/dirs:   /boot/grub/grub.cfg /etc/fstab /boot/grub/core.img

sda8: _________________________________________________________________________

    File system:       ext4
    Boot sector type:  -
    Boot sector info:
    Operating System:
    Boot files/dirs:

sda9: _________________________________________________________________________

    File system:
    Boot sector type:  -
    Boot sector info:
    Mounting failed:
mount: unknown filesystem type ''

=========================== Drive/Partition Info: =============================

Drive: sda ___________________ _____________________________________________________

Disk /dev/sda: 1788.6 GB, 1788618997760 bytes
255 heads, 63 sectors/track, 217453 cylinders, total 3493396480 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes

Partition  Boot         Start           End          Size  Id System

/dev/sda1               2,048         4,095         2,048  83 Linux
/dev/sda2    *          4,096    19,535,871    19,531,776  83 Linux
/dev/sda3          19,537,918 3,493,394,431 3,473,856,514   5 Extended
/dev/sda5          19,537,920    39,067,647    19,529,728  82 Linux swap / Solaris
/dev/sda6          39,069,696   136,724,479    97,654,784  83 Linux
/dev/sda7         136,726,528   234,381,311    97,654,784  83 Linux
/dev/sda8         234,383,360   332,038,143    97,654,784  83 Linux
/dev/sda9         332,040,192 3,493,394,431 3,161,354,240  83 Linux

blkid -c /dev/null: ____________________________________________________________

/dev/sda1: UUID="1dd012ba-04e8-4c89-bd25-0e9f89e991eb" TYPE="ext2"
/dev/sda2: UUID="8edf0e1b-5f9c-4ca0-8f88-77d35af87093" TYPE="ext4"
/dev/sda5: UUID="b5e5c40e-193c-4c6d-9068-45cc033b66a9" TYPE="swap"
/dev/sda6: UUID="266e71af-e145-495b-b38f-2da1f444885d" TYPE="ext4"
/dev/sda7: UUID="52f32e5d-9b43-4972-bb2e-e97133dd2c80" TYPE="ext4"
/dev/sda8: UUID="015a40de-8f96-4c1b-8fb1-1a23575054a6" TYPE="ext4"

=============================== "mount" output: ===============================

/dev/sda6 on / type ext4 (rw,errors=remount-ro)
proc on /proc type proc (rw,noexec,nosuid,nodev)
none on /sys type sysfs (rw,noexec,nosuid,nodev)
none on /sys/fs/fuse/connections type fusectl (rw)
none on /sys/kernel/debug type debugfs (rw)
none on /sys/kernel/security type securityfs (rw)
none on /dev type devtmpfs (rw,mode=0755)
none on /dev/pts type devpts (rw,noexec,nosuid,gid=5,mode=0620)
none on /dev/shm type tmpfs (rw,nosuid,nodev)
none on /var/run type tmpfs (rw,nosuid,mode=0755)
none on /var/lock type tmpfs (rw,noexec,nosuid,nodev)
none on /lib/init/rw type tmpfs (rw,nosuid,mode=0755)
/dev/sda2 on /boot type ext4 (rw)
binfmt_misc on /proc/sys/fs/binfmt_misc type binfmt_misc (rw,noexec,nosuid,nodev)

=========================== sda6/boot/grub/menu.lst: ===========================

# menu.lst - See: grub(8), info grub, update-grub(8)
#            grub-install(8), grub-floppy(8),
#            grub-md5-crypt, /usr/share/doc/grub
#            and /usr/share/doc/grub-legacy-doc/.

## default num
# Set the default entry to the entry number NUM. Numbering starts from 0, and
# the entry number 0 is the default if the command is not used.
#
# You can specify 'saved' instead of a number. In this case, the default entry
# is the entry saved with the command 'savedefault'.
# WARNING: If you are using dmraid do not use 'savedefault' or your
# array will desync and will not let you boot your system.
default     0
fallback    2
## timeout sec
# Set a timeout, in SEC seconds, before automatically booting the default entry
# (normally the first entry defined).
timeout     10

## hiddenmenu
# Hides the menu by default (press ESC to see the menu)
#hiddenmenu

# Pretty colours
#color cyan/blue white/blue

## password ['--md5'] passwd
# If used in the first section of a menu file, disable all interactive editing
# control (menu entry editor and command-line)  and entries protected by the
# command 'lock'
# e.g. password topsecret
#      password --md5 $1$gLhU0/$aW78kHK1QfV3P2b2znUoe/
# password topsecret

#
# examples
#
# title     Windows 95/98/NT/2000
# root      (hd0,0)
# makeactive
# chainloader   +1
#
# title     Linux
# root      (hd0,1)
# kernel    /vmlinuz root=/dev/hda2 ro
#

#
# Put static boot stanzas before and/or after AUTOMAGIC KERNEL LIST

### BEGIN AUTOMAGIC KERNELS LIST
## lines between the AUTOMAGIC KERNELS LIST markers will be modified
## by the debian update-grub script except for the default options below

## DO NOT UNCOMMENT THEM, Just edit them to your needs

## ## Start Default Options ##
## default kernel options
## default kernel options for automagic boot options
## If you want special options for specific kernels use kopt_x_y_z
## where x.y.z is kernel version. Minor versions can be omitted.
## e.g. kopt=root=/dev/hda1 ro
##      kopt_2_6_8=root=/dev/hdc1 ro
##      kopt_2_6_8_2_686=root=/dev/hdc2 ro
# kopt=root=UUID=266e71af-e145-495b-b38f-2da1f444885d ro

## default grub root device
## e.g. groot=(hd0,0)
# groot=8edf0e1b-5f9c-4ca0-8f88-77d35af87093

## should update-grub create alternative automagic boot options
## e.g. alternative=true
##      alternative=false
# alternative=true

## should update-grub lock alternative automagic boot options
## e.g. lockalternative=true
##      lockalternative=false
# lockalternative=false

## additional options to use with the default boot option, but not with the
## alternatives
## e.g. defoptions=vga=791 resume=/dev/hda5
# defoptions=quiet splash

## should update-grub lock old automagic boot options
## e.g. lockold=false
##      lockold=true
# lockold=false

## Xen hypervisor options to use with the default Xen boot option
# xenhopt=

## Xen Linux kernel options to use with the default Xen boot option
# xenkopt=console=tty0

## altoption boot targets option
## multiple altoptions lines are allowed
## e.g. altoptions=(extra menu suffix) extra boot options
##      altoptions=(recovery) single
# altoptions=(recovery mode) single

## controls how many kernels should be put into the menu.lst
## only counts the first occurence of a kernel, not the
## alternative kernel options
## e.g. howmany=all
##      howmany=7
# howmany=all

## specify if running in Xen domU or have grub detect automatically
## update-grub will ignore non-xen kernels when running in domU and vice versa
## e.g. indomU=detect
##      indomU=true
##      indomU=false
# indomU=detect

## should update-grub create memtest86 boot option
## e.g. memtest86=true
##      memtest86=false
# memtest86=true

## should update-grub adjust the value of the default booted system
## can be true or false
# updatedefaultentry=false

## should update-grub add savedefault to the default options
## can be true or false
# savedefault=false

## ## End Default Options ##

title       Xen 4.1.2 / Ubuntu 10.04.4 kernel 2.6.32.40 (root=sda6)
uuid        8edf0e1b-5f9c-4ca0-8f88-77d35af87093
#root       (hd0,1)
kernel      /xen-4.1.2.gz dom0_mem=4096M,max:4096M loglvl=all guest_loglvl=all
module      /vmlinuz-2.6.32.40 dummy=dummy root=/dev/sda6 ro console=tty0 nomodeset rootdelay=50
module      /initrd.img-2.6.32.40

title       Xen 4.2.0-rc3 / Ubuntu 10.04.4 kernel 2.6.32.40 (root=sda6)
uuid        8edf0e1b-5f9c-4ca0-8f88-77d35af87093
#root       (hd0,1)
kernel      /xen-4.2.0-rc3-pre.gz dom0_mem=4096M,max:4096M loglvl=all guest_loglvl=all com1=9600,8n1 console=com1,vga
module      /vmlinuz-2.6.32.40 root=UUID=266e71af-e145-495b-b38f-2da1f444885d ro console=tty0 console=hvc0 earlyprintk=xen nomodeset
module      /initrd.img-2.6.32.40

title       Ubuntu 10.04.4 LTS, kernel 2.6.32-42-generic (sda6)
uuid        8edf0e1b-5f9c-4ca0-8f88-77d35af87093
kernel      /vmlinuz-2.6.32-42-generic root=/dev/sda6 ro quiet splash
initrd      /initrd.img-2.6.32-42-generic

title       Ubuntu 10.04.4 LTS, kernel 2.6.32-42-generic (sda7)
uuid        8edf0e1b-5f9c-4ca0-8f88-77d35af87093
kernel      /vmlinuz-2.6.32-42-generic root=/dev/sda7 ro quiet splash
initrd      /initrd.img-2.6.32-42-generic

title       Ubuntu 10.04.4 LTS, kernel 3.1.0-rc9+
uuid        8edf0e1b-5f9c-4ca0-8f88-77d35af87093
kernel      /vmlinuz-3.1.0-rc9+ root=UUID=266e71af-e145-495b-b38f-2da1f444885d ro quiet splash

title       Ubuntu 10.04.4 LTS, kernel 3.1.0-rc9+ (recovery mode)
uuid        8edf0e1b-5f9c-4ca0-8f88-77d35af87093
kernel      /vmlinuz-3.1.0-rc9+ root=UUID=266e71af-e145-495b-b38f-2da1f444885d ro  single

title       Ubuntu 10.04.4 LTS, kernel 2.6.32.40
uuid        8edf0e1b-5f9c-4ca0-8f88-77d35af87093
kernel      /vmlinuz-2.6.32.40 root=UUID=266e71af-e145-495b-b38f-2da1f444885d ro quiet splash
initrd      /initrd.img-2.6.32.40

title       Ubuntu 10.04.4 LTS, kernel 2.6.32.40 (recovery mode)
uuid        8edf0e1b-5f9c-4ca0-8f88-77d35af87093
kernel      /vmlinuz-2.6.32.40 root=UUID=266e71af-e145-495b-b38f-2da1f444885d ro  single
initrd      /initrd.img-2.6.32.40

title       Ubuntu 10.04.4 LTS, kernel 2.6.32-42-generic (recovery mode)
uuid        8edf0e1b-5f9c-4ca0-8f88-77d35af87093
kernel      /vmlinuz-2.6.32-42-generic root=UUID=266e71af-e145-495b-b38f-2da1f444885d ro  single
initrd      /initrd.img-2.6.32-42-generic

title       Ubuntu 10.04.4 LTS, kernel 2.6.32-38-generic
uuid        8edf0e1b-5f9c-4ca0-8f88-77d35af87093
kernel      /vmlinuz-2.6.32-38-generic root=UUID=266e71af-e145-495b-b38f-2da1f444885d ro quiet splash
initrd      /initrd.img-2.6.32-38-generic

title       Ubuntu 10.04.4 LTS, kernel 2.6.32-38-generic (recovery mode)
uuid        8edf0e1b-5f9c-4ca0-8f88-77d35af87093
kernel      /vmlinuz-2.6.32-38-generic root=UUID=266e71af-e145-495b-b38f-2da1f444885d ro  single
initrd      /initrd.img-2.6.32-38-generic

title       Chainload into GRUB 2
root        8edf0e1b-5f9c-4ca0-8f88-77d35af87093
kernel      /boot/grub/core.img

#title      Ubuntu 10.04.4 LTS, memtest86+
#uuid       8edf0e1b-5f9c-4ca0-8f88-77d35af87093
#kernel     /memtest86+.bin

### END DEBIAN AUTOMAGIC KERNELS LIST

=========================== sda6/boot/grub/grub.cfg: ===========================

#
# DO NOT EDIT THIS FILE
#
# It is automatically generated by /usr/sbin/grub-mkconfig using templates
# from /etc/grub.d and settings from /etc/default/grub
#

### BEGIN /etc/grub.d/00_header ###
if [ -s $prefix/grubenv ]; then
  load_env
fi
set default="0"
if [ ${prev_saved_entry} ]; then
  set saved_entry=${prev_saved_entry}
  save_env saved_entry
  set prev_saved_entry=
  save_env prev_saved_entry
  set boot_once=true
fi

function savedefault {
  if [ -z ${boot_once} ]; then
    saved_entry=${chosen}
    save_env saved_entry
  fi
}

function recordfail {
  set recordfail=1
  if [ -n ${have_grubenv} ]; then if [ -z ${boot_once} ]; then save_env recordfail; fi; fi
}
insmod ext2
set root='(hd0,6)'
search --no-floppy --fs-uuid --set 266e71af-e145-495b-b38f-2da1f444885d
if loadfont /usr/share/grub/unicode.pf2 ; then
  set gfxmode=640x480
  insmod gfxterm
  insmod vbe
  if terminal_output gfxterm ; then true ; else
    # For backward compatibility with versions of terminal.mod that don't
    # understand terminal_output
    terminal gfxterm
  fi
fi
insmod ext2
set root='(hd0,2)'
search --no-floppy --fs-uuid --set 8edf0e1b-5f9c-4ca0-8f88-77d35af87093
set locale_dir=($root)/grub/locale
set lang=en
insmod gettext
if [ ${recordfail} = 1 ]; then
  set timeout=-1
else
  set timeout=10
fi
### END /etc/grub.d/00_header ###

### BEGIN /etc/grub.d/05_debian_theme ###
set menu_color_normal=white/black
set menu_color_highlight=black/light-gray
### END /etc/grub.d/05_debian_theme ###

### BEGIN /etc/grub.d/08_xen ###
menuentry "Xen Unstable 4.2 RC3 / Debian Squeeze kernel 2.6.32.40" {
        insmod ext2
        set root='(hd0,4)'
        multiboot (hd0,1)/xen-4.2.0-rc3-pre.gz dummy
        module (hd0,1)/vmlinuz-2.6.32.40 dummy root=UUID=266e71af-e145-495b-b38f-2da1f444885d ro quiet console=tty0 nomodeset rootdelay=130
        module (hd0,1)/initrd.img-2.6.32.40
}
### END /etc/grub.d/08_xen ###

### BEGIN /etc/grub.d/10_linux ###
menuentry 'Ubuntu, with Linux 3.1.0-rc9+' --class ubuntu --class gnu-linux --class gnu --class os {
    recordfail
    insmod ext2
    set root='(hd0,2)'
    search --no-floppy --fs-uuid --set 8edf0e1b-5f9c-4ca0-8f88-77d35af87093
    linux   /vmlinuz-3.1.0-rc9+ root=/dev/sda6 ro   quiet splash
}
menuentry 'Ubuntu, with Linux 2.6.32.40' --class ubuntu --class gnu-linux --class gnu --class os {
    recordfail
    insmod ext2
    set root='(hd0,2)'
    search --no-floppy --fs-uuid --set 8edf0e1b-5f9c-4ca0-8f88-77d35af87093
    linux   /vmlinuz-2.6.32.40 root=UUID=266e71af-e145-495b-b38f-2da1f444885d ro   quiet splash
    initrd  /initrd.img-2.6.32.40
}
menuentry 'Ubuntu, with Linux 2.6.32-42-generic' --class ubuntu --class gnu-linux --class gnu --class os {
    recordfail
    insmod ext2
    set root='(hd0,2)'
    search --no-floppy --fs-uuid --set 8edf0e1b-5f9c-4ca0-8f88-77d35af87093
    linux   /vmlinuz-2.6.32-42-generic root=UUID=266e71af-e145-495b-b38f-2da1f444885d ro   quiet splash
    initrd  /initrd.img-2.6.32-42-generic
}
menuentry 'Ubuntu, with Linux 2.6.32-38-generic' --class ubuntu --class gnu-linux --class gnu --class os {
    recordfail
    insmod ext2
    set root='(hd0,2)'
    search --no-floppy --fs-uuid --set 8edf0e1b-5f9c-4ca0-8f88-77d35af87093
    linux   /vmlinuz-2.6.32-38-generic root=UUID=266e71af-e145-495b-b38f-2da1f444885d ro   quiet splash
    initrd  /initrd.img-2.6.32-38-generic
}
### END /etc/grub.d/10_linux ###

### BEGIN /etc/grub.d/20_memtest86+ ###
menuentry "Memory test (memtest86+)" {
    insmod ext2
    set root='(hd0,2)'
    search --no-floppy --fs-uuid --set 8edf0e1b-5f9c-4ca0-8f88-77d35af87093
    linux16 /memtest86+.bin
}
menuentry "Memory test (memtest86+, serial console 115200)" {
    insmod ext2
    set root='(hd0,2)'
    search --no-floppy --fs-uuid --set 8edf0e1b-5f9c-4ca0-8f88-77d35af87093
    linux16 /memtest86+.bin console=ttyS0,115200n8
}
### END /etc/grub.d/20_memtest86+ ###

### BEGIN /etc/grub.d/30_os-prober ###
### END /etc/grub.d/30_os-prober ###

### BEGIN /etc/grub.d/40_custom ###
# This file provides an easy way to add custom menu entries.  Simply type the
# menu entries you want to add after this comment.  Be careful not to change
# the 'exec tail' line above.
### END /etc/grub.d/40_custom ###

=============================== sda6/etc/fstab: ===============================

# /etc/fstab: static file system information.
#
# Use 'blkid -o value -s UUID' to print the universally unique identifier
# for a device; this may be used with UUID= as a more robust way to name
# devices that works even if disks are added and removed. See fstab(5).
#
# <file system> <mount point>   <type>  <options>       <dump>  <pass>
proc            /proc           proc    nodev,noexec,nosuid 0       0
# / was on /dev/sda6 during installation
UUID=266e71af-e145-495b-b38f-2da1f444885d /               ext4    errors=remount-ro 0       1
# /boot was on /dev/sda2 during installation
UUID=8edf0e1b-5f9c-4ca0-8f88-77d35af87093 /boot           ext4    defaults        0       2
# swap was on /dev/sda5 during installation
UUID=b5e5c40e-193c-4c6d-9068-45cc033b66a9 none            swap    sw              0       0

nas-1g:/export/utils/scratch    /sapmnt/scratch     nfs     defaults 0 0
nas-1g:/export/virtual_machines     /sapmnt/virtual_machines    nfs     defaults 0 0

=================== sda6: Location of files loaded by Grub: ===================

  20.0GB: boot/grub/grub.cfg
  20.0GB: boot/grub/menu.lst
  20.0GB: boot/grub/stage2
  20.0GB: boot/initrd.img-2.6.32-38-generic
  20.0GB: boot/initrd.img-2.6.32.40
  20.0GB: boot/initrd.img-2.6.32-42-generic
  20.0GB: boot/vmlinuz-2.6.32-38-generic
  20.0GB: boot/vmlinuz-2.6.32.40
  20.0GB: boot/vmlinuz-2.6.32-42-generic
  20.0GB: boot/vmlinuz-3.1.0-rc9+
  20.0GB: initrd.img
  20.0GB: initrd.img.old
  20.0GB: vmlinuz
  20.0GB: vmlinuz.old

I have already attempted to use rootdelay=50 to increase the chance of detecting the root device, but have had no luck so far

A: Why have you commented the root entry in menu.lst? Have you tried this:
title       Xen 4.1.2 / Ubuntu 10.04.4 kernel 2.6.32.40 (root=sda6)
uuid        8edf0e1b-5f9c-4ca0-8f88-77d35af87093
root       (hd0,6)
kernel      /xen-4.1.2.gz dom0_mem=4096M,max:4096M loglvl=all guest_loglvl=all
module      /vmlinuz-2.6.32.40 dummy=dummy root=/dev/sda6 ro console=tty0 nomodeset rootdelay=50
module      /initrd.img-2.6.32.40

NOTE: It's been a while since I've used the old GRUB, check that hd0,6 actually corresponds to sda6. It should since sda6 is the 2nd logical partition of your extended partition, but check anyway.

I see you also have a grub.cfg file. I assume, therefore, that you have GRUB2 installed. Does that fare any better? Will it not properly detect and configure everything if you run
$ sudo update-grub
$ sudo grub-install /dev/sda


text:
Q: Can't figure out why I get TypeError while fetching JSON with JS To be fair, I'm a bit stumped how to even research on such case. 'Functions are not running but manually works?' I've been trying to implenet async/await functions yesterday but i couldn't even make it work either. Sorry for asking such basic question but I've been stuck here for days and can't move on forward. Hope I'd get some reply this time.
On this scenario I have a external JSON file where I store objects in an array with every object has it's own provider, id, category, description
I'm trying to implement this scenario;
1) fetch the json and assign it to archive as an array with fetchArchive()
2) pick a random json  and assign it to upNext randomiser()
3) set up the dom attribute values depending on the upNext's values with setUpDOM()
But when I ran the code I get an type error saying that upNext on Firefox, provider on chrome is undefined.
I can see that functions are not running for some reason. But if I ran the codes manually from console they do work as I intended.
let upNext
let archive = []

function fetchArchive() {
   fetch('./js/archive.json')
  .then(response => response.json())
  .then(data => { archive = data; })
};

// == Randomiser ==
fetchArchive();

function randomiser() {
  upNext = archive[Math.floor(Math.random()*archive.length)]
}

randomiser();

// == DOM Setup ==

function setUpDOM() {
  document.getElementById('player').setAttribute('data-plyr-provider', upNext.provider)
  document.getElementById('player').setAttribute('data-plyr-embed-id', upNext.id)
  let titles = document.getElementsByClassName('videoTitle');
  Array.prototype.forEach.call(titles, function(element) {
    element.innerHTML = upNext.title;
  });
}
setUpDOM();

and the JSON that I'm fetching
[
    {
      "provider": "youtube",
      "id": "RYpqE0_VpWA",
      "category": "Music",
      "title": "Ratatat - Party With Children",
      "descrtiption": "Ipsum Lorem Consectetur adipisicing elit."
    },
    {
      "provider": "vimeo",
      "id": "420049165",
      "category": "Music",
      "title": "Boy I Never Knew",
      "descrtiption": "Lorem ipsum Consectetur adipisicing"
    }
]

Just to note this json file probably going to have thousand objects. I'm not if this type of randomization would work on such long array objects.
I'm open for any kind of different approaches as this is my personal project. Can share the full code as well.

A: The functions are running, but fetch is asynchronous, so archive is empty when you run the Randomizer and so it puts nothing in the upNext variable.
You will need to wait for the fetch to complete before calling the rest.

let upNext
let archive = []

function fetchArchive() {
  fetch('./js/archive.json')
    .then(response => response.json())
    .then(data => {
      archive = data;
      randomiser();
      setUpDOM();
    })
};

// == Randomiser ==
function randomiser() {
  upNext = archive[Math.floor(Math.random() * archive.length)]
}

// == DOM Setup ==
function setUpDOM() {
  document.getElementById('player').setAttribute('data-plyr-provider', upNext.provider)
  document.getElementById('player').setAttribute('data-plyr-embed-id', upNext.id)
  let titles = document.getElementsByClassName('videoTitle');
  Array.prototype.forEach.call(titles, function(element) {
    element.innerHTML = upNext.title;
  });
}

fetchArchive();

A: when you invokerandomiser, the fetchArchive is still fetching, you should chain the randomiser call to the the end of  fetchArchive
ie
let upNext
let archive = []

function fetchArchive() {
   return fetch('./js/archive.json') // returns
  .then(response => response.json())
  .then(data => { archive = data; }) // this Promise
};

// == Randomiser ==

function randomiser() {
  upNext = archive[Math.floor(Math.random()*archive.length)]
}

// == DOM Setup ==

function setUpDOM() {
  document.getElementById('player').setAttribute('data-plyr-provider', upNext.provider)
  document.getElementById('player').setAttribute('data-plyr-embed-id', upNext.id)
  let titles = document.getElementsByClassName('videoTitle');
  Array.prototype.forEach.call(titles, function(element) {
    element.innerHTML = upNext.title;
  });
}

fetchArchive().then(randomiser).then(setUpDOM)


text:
Q: Vue js / javascript array of objects - how to detect if any of the objects has been changed and which one I'm working on a Vuejs project. On some point I have an array of objects (data taken from the server) like this:
[
    {
        name: "Book one",
        price: 12,
        active: true
    },
    {
        name: "Small drone X12",
        price: 54,
        active: false
    },
    {
        name: "something else",
        price: 32,
        active: true
    }
]

The data is used to generate dynamic form on the page so the user can edit the data.
How can I check if any of the objects has been changed by the user and which one (can be changed one, two or any number of them) so I can show the user a button to update the changed data.
I'd like to update only the data from the object(s) that actually has been changed - not all of them.

A: You can keep around a calculated JSON string of the objects in a mapped array
const comparison = data.map(JSON.stringify); // in order string based values for direct comparison

Later in code you can compare to those values
data.forEach((obj, index) => {
  // if they do match, skip
  if (JSON.stringify(obj) === comparison[index]) return;

  // they don't match, update comparison value
  comparison[index] = JSON.stringify(obj);

  // update VUE state and other things here
})

This way you only need to update the updated values, and only ever need to calculate comparison values. This works even if the object has certain field updated but is still the same object(which would pass an equality test of object === object even though a value has updated).
Another more involved example revolves around proxying or watching every setter on the objects to fire a change whenever they are updated in place, but for the life of me I still don't understand proxies right...
What about if the Array of Field changes size?
While this works if the data is never changing in size, if the data array changes in size... it will still work because there will be an undefined in the matching index, causing the string comparison to return false. However it would be best to add it to the form then at the end with a simple modification to the above code:
if (comparison[index] === undefined) {
  // add the form to the field, it'll add in order
}
// they don't match, update comparison value
...

A: One approach is to listen for change events on pass the object's array index and property name for the modified field. Then assign the value to another array holding the changes.

new Vue({
  el: '#app',
  data: () => ({
    items: [
      {
        name: "Book one",
        price: 12,
        active: true
      },
      {
        name: "Small drone X12",
        price: 54,
        active: false
      },
      {
        name: "something else",
        price: 32,
        active: true
      }
    ],
    changed: []
  }),
  mounted () {
    this.changed = Array(this.items.length).fill({})
  },
  methods: {
    onPropertyChanged (index, prop) {
      this.changed.splice(index, 1, Object.assign({}, this.changed[index], { [prop]: this.items[index][prop] }))
    }
  }
})

    Name
    <input v-model="item.name" @change="onPropertyChanged(index, 'name')">
    Price
    <input v-model="item.price" type="number" min="0" @change="onPropertyChanged(index, 'price')">
    Active
    <input v-model="item.active" type="checkbox" @change="onPropertyChanged(index, 'active')">

Changes

  <pre v-for="(item, index) in changed" :key="`change-${index}`">{{ item }}


text:
Q: Change the Description of my Windows Service According to this answer  it seems that there is no official way to set a version for a Windows Service. However this can be done by inserting it into its Description or DisplayName.
I would like to be able to change that version number without needing to delete and reinstall the service. But I couldn't find a way to set the Description except for in the installation itself.
So, is there a way, and what is it, to change a Service's Description without reinstalling it?
Preferably using .Net. The Service itself is also .Net if that matters.

A: This can be accomplished using the SC.exe utility with the command:
sc description <ServiceName> "Any Description you like."

This command could be called from a command window opened as administrator or from a .Net application provided that the service has already been created.

A: If what you need is the version number of the executable for the Windows service, and the executable is a .NET assembly, then retrieve the path to the service executable, and then retrieve the version from that executable/assembly.

A: Though this is not a pure .NET solution, it can be implemented in .NET, and it is one of the only MS-supported methods of reconfiguring a service. Plus, it doesn't require direct registry manipulation (best avoided if possible).
You can change the description of a Windows service by using the Windows command-line service controller utility, SC.exe.
You can exec the command you need to execute from your .NET code, or call it from a shell or script, such as CMD.exe or PowerShell.
sc.exe config YourServiceName displayName= "Your service description..."

Note:

*

*Detailed information on the SC config command can be found here: MS Docs SC Config man page

*YourServiceName is the actual service name of your application, not it's current DisplayName (unless, of course, they're identical)

*If your DisplayName is more than one word, it needs to be wrapped in quotes

*There must be no space between the word "displayName" and the equals sign

*There must be one or more spaces between equals sign and the beginning of your desired service description


text:
Q: editable table cell using angularJS Is there a way to show data inside td and allow user to edit it in a way that the change will take place in the sql (MySQL in my case) table?
im creating a table from database using angularJS:
Creating The json file from the table:
$result = mysql_query("select * from `user script settings`");
//Create an array
$json_response = array();

while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    $row_array['user_id'] = $row['user id'];
    $row_array['script_id'] = $row['script id'];
    $row_array['cron_format'] = $row['cron format'];
    $row_array['schedule_last_update'] = $row['schedule last update'];
    $row_array['next_execution_time'] = $row['next execution time'];
    $row_array['script_exec'] = $row['script_exec'];

    //push the values in the array
    array_push($json_response,$row_array);
}
echo json_encode($json_response);

showing it in the table:

        user name
        script name
        cron format
        schedule last update
        next execution time
        script exec

            {{x.user_id}}
            {{x.script_id}}
            {{x.cron_format}}
            {{x.schedule_last_update}}
            {{x.next_execution_time}}
            {{x.script_exec}}

I want to allow user to change the cron format value and to update the table ...is there "angularish" way to due that?? if not i'll appreciate guidance for a php solution, thx!


text:
Q: iOS 10 custome remote notifications sound not playing the whole file length I am aware of the bug in iOS 10 that will prevent custom remote notifications sound from playing.  The current solution seemed to be restart the device.  That seemed to temporary fix.  But this problem will reoccur again.
But my problem is that when it did play the custom sound, it did not play the whole file (30 seconds or less).  It only plays 2-3 seconds and the notification view disappears.
It works fine under iOS 9.
Have you encountered this issue?  Any suggestions?


text:
Q: issue with positioning css divider lines in menu I have a CSS problem that I've been unable to figure out. Basically, I have a menu which is a fixed width and height. The background of the menu is simply a graphic, with a gray bar, and a drop shadow beneath. Here is the css for that menu:
  #menu
   {
       width:1024px;
       height:63px;
       background: url(../images/menuholder.jpg);
       margin:0px;
   }

I have a CMS controlling the menu options, however for this example, I have them hardcoded. I am using CSS to position the elements in the correct place vertically, over the gray bar, centered vertically, which is fine. Here is the issue: I am trying to place a 1px wide white (#fff) line in between each menu option. I would prefer to do this via CSS entirely, rather than with a saved image. I was able to do it (sort of) using this code:

Option 1

Option 2

Option 3

Option 4

Option 5

The css behind it is:
#upperNavLinks
{
    float:left;
    padding-top:0px;
    padding-left:0px;
}

#upperNavLinks ul
{
    list-style-type:none;
}

#upperNavLinks ul li
{
    float:left;
}

#upperNavLinks ul a {
    padding-right: 18px;
    padding-left: 18px;
    display: block;
    text-decoration: none;
    font-family:PT Sans, Arial, Helvetica, sans-serif;
    font-size: 11pt;
    font-weight:bold;
    color: #333333;
}

#upperNavLinks ul a:hover
{
    font-weight:bold;
    color: #a31624;
}

The problem is, it generates a white line where I want it to, however I need it to start at the top of the gray bar, and proceed down to the bottom of the gray bar, but not over the drop shadow. The size (vertically) of the gray bar is : 44px.
So, the question I have is: How do I make the white line lock to the top of the gray bar, and cover 44px (and not over) of vertical space over the gray bar, while leaving the actual menu options floating in the center of the graphic as they are now?
If this doesnt make any sense I could post the actual graphic and code somewhere.

A: Between each li with an anchor, place another li, now with a class (I named it border). Give that class a display: block;, a width: 1px; and a height: 20px;.Now you can play with the height to get the effect you looking for.
http://jsfiddle.net/skeurentjes/4hJrb/1/

A: What's the semantic implications of placing empty
*'s? Personaly I would use background image for something like this rather than creating empty tags.


text:
Q: jQuery Nav's anchor click not working with AngularJS I have a Home.html screen and its corresponding Angularjs controller(HomeController.js). I am using  jQuery Navigation sidebar on home screen. This navigation sidebar has a logout list item (li). I have given ng-click="logout()" to this li (list item), and I have defined logout() in HomeController.js.
When I click on logout, It doesn't give alert, probably it's not going to this controller.
Home.html

                        Logout

HomeController.js
app.controller("HomeController", function ($scope, $location, $window, $compile) {
$scope.logout = function(){
    alert("Click");
    $location.path("/Login");
}});

config.js
var tkitApp = angular.module('tkit', ['ngRoute']);tkitApp.config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/', {
    templateUrl: 'views/LaunchScreen.html',
    controller: 'LaunchScreenController'
}).when('/Login', {
    templateUrl: 'views/Login.html',
    controller: 'LoginScreenController'
}).when('/Home', {
    templateUrl: 'views/Home.html',
    controller: 'HomeController'
 }).otherwise({ redirectTo: '/' });}]);

I am not even getting alert on click of logout list item.
Logcat when Home.html gets loaded
03-11 17:34:37.530: I/chromium(29156): [INFO:CONSOLE(2)] "HomeController loaded", source: file:///android_asset/www/js/controller/HomeScreenController.js (2)

A: Your controller name is different in routing
$routeProvider.when('/', {
    templateUrl: 'views/LaunchScreen.html',
    controller: 'LaunchScreenController'
}).when('/Login', {
    templateUrl: 'views/Login.html',
    controller: 'LoginScreenController'
}).when('/Home', {
    templateUrl: 'views/Home.html',
    controller: 'HomeController'
 }).otherwise({ redirectTo: '/' });}]);

And Controller is
app.controller("HomeController", function ($scope, $location, $window, $compile) {
$scope.logout = function(){
    alert("Click");
    $location.path("/Login");
}});

Please change your controller name like this
app.controller("HomeScreenController", function ($scope, $location, $window, $compile) {
    $scope.logout = function(){
        alert("Click");
        $location.path("/Login");
    }});

It will work


text:
Q: How to reduce visible part (or mask) of mapbox style layer? I have hexagonal tileset added as a layer to mapbox style though mapbox studio.
Trying to find possibility to reduce layer visible area. For example to show only 100m radius (or square with side equal to 100m) area around map center (current point marker).
Is this possible?

A: You can create a bounding box and use fitBounds method of the map, for example:
const boundingBox = [
   [minX,  minY],
   [maxX, maxY]
];

map.fitBounds(boundingBox);

More about fitBounds and other examples you can find here.
For creating bounding box you can use Turf.js library.
This code uses buffer and bbox methods to create bounding box with 100m side and given point in the center:
const pointBuffer = turf.buffer(point /* - your point GeoJSON */, 0.1, 'kilometers');
const boundingBox = turf.bbox(pointBuffer);


text:
Q: Rails - sql commands not working with datetime I have a strange problem with my web app.
I am trying to build a simple reservation system for a game like "Escape the room". For now I made my own calendar looking a railscast (Calendars revised) for having the dates.
For the possible hours I made a new model and a new table in the database
t.integer "id"
t.datetime "start_time"
t.datetime "end_time"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false

In the view I have something like this:
<%= calendar @date do |date| %>
<%= date.day %>

  <% @hours.each_slice(2) do |hour| %>

    <% hour.each do |h| %>

      <%= link_to h.start_time.strftime('%H:%M'), new_escape_path(date: date, start_time: h.start_time.strftime('%H:%M'), end_time: h.end_time.strftime('%H:%M')) %>

    <% end %>

<% end %>

<% end %>

And I write these parameters into the database passing them in a form where user can complete other fields manually:
<%= text_field_tag :date, params[:date] %>

<%= text_field_tag :start_time, params[:start_time] %> do
<%= text_field_tag :end_time, params[:end_time] %>

The problem is that in the view I want to show only the hours which are not reserved yet, which means that they are not in the escapes table.
When in the console I write
Escape.all

I have something like:
#<Escape id: 1, date: "2015-08-11 00:00:00", start_time: "2015-08-10 08:30:00", end_time: nil, user_id: nil, created_at: "2015-08-10 15:26:14", updated_at: "2015-08-10 15:26:14">

but when I write
Escape.all.where(date: "2015-08-11 00:00:00")

it returns an empty record
#<ActiveRecord::Relation []>

I tried also to insert something like this in the view, but it's not working:
 <% if Escape.where(["date = ? and start_time = ?", "#{date}", "#{h}"])%>
      <%= h.start_time.strftime('%H:%M') %>
 <% else %>
      <%= link_to h.start_time.strftime('%H:%M'), new_escape_path(date: date, start_time: h.start_time.strftime('%H:%M'), end_time: h.end_time.strftime('%H:%M')) %>
 <% end %>

Do you have any ideas? What am I doing wrong?


text:
Q: How to store multi connected waypoints I am trying to create a basic 2D road system on a grid. Currently I have a list of staight lines but they are not connected to each other.
The part I am stuck on is how I construct the data and store my data so I know which waypoint points to which ever waypoint (more than one way point can connect to any other way point).
So currently if you image i have this as my data:
var point      = [];
    point[0]   = {'x':2,'y':6};
    point[1]   = {'x':2,'y':8};
    point[2]   = {'x':6,'y':9};
    point[3]   = {'x':7,'y':2};

Now suppose point 0 connects to points 2 and 3. And point 1 connects to point 3.
What would be the best way to store the information that these points are linked, also allowing me then to look up and obtain properties of the object relating to a connected waypoint (which would mainly be useful for pathfinding in the future).
For example I may need to find a waypoint at a given x or y position. Or i may want to obtain relevant waypoint data that are connected to for example point 1, such as their x and y position and what ever waypoints may connect to them too.

A: The road network can be represented by an adjacency list. Basically, each point will be given a list (which could be implemented by an array) containing the indices which can be reached from it. In your example, this can be expressed as follows.
var point      = [];
point[0]   = {'x':2,'y':6, 'neighbors':[2,3]};
point[1]   = {'x':2,'y':8, 'neighbors':[3]};
point[2]   = {'x':6,'y':9, 'neighbors':[0]};
point[3]   = {'x':7,'y':2, 'neighbors':[0,1]};


text:
Q: Angular for Rails Developers Book: Deploying Angular on Rails on Heroku- Uglifier Gem I'm doing the walkthrough in this book, building a Rails API app with Angular 2 on top. Github
Using two buildpacks as instructed in Angular For Rails Developer book.
heroku buildpacks:add https://github.com/jasonswett/heroku-buildpack-nodejs
heroku buildpacks:add heroku/ruby

All of my updates have been checked in.  When I git push heroku master, I get the following error printout
remote:        Running heroku-postbuild
remote:
remote:        > author-wizard@0.0.0 heroku-postbuild /tmp/build_6cac525cd409f823d4d8849a2cb7eba2/client
remote:        > ng build
remote:
remote:        Could not start watchman; falling back to NodeWatcher for file system events.
remote:        Visit http://ember-cli.com/user-guide/#watchman for more info.
 33% building modules 19events.js:160
remote:       throw er; // Unhandled 'error' event
remote:       ^
remote:
remote: Error: This socket is closed
remote:     at Socket._writeGeneric (net.js:673:19)
remote:     at Socket._write (net.js:724:8)
remote:     at doWrite (_stream_writable.js:307:12)
remote:     at writeOrBuffer (_stream_writable.js:293:5)
remote:     at Socket.Writable.write (_stream_writable.js:220:11)
remote:     at Socket.write (net.js:651:40)
remote:     at Socket.process.stderr.write (/tmp/build_6cac525cd409f823d4d8849a2cb7eba2/client/node_modules/angular-c
li/lib/cli/index.js:30:27)
remote:     at Console.warn (console.js:51:16)
remote:     at printErrorAndExit (/tmp/build_6cac525cd409f823d4d8849a2cb7eba2/client/node_modules/awesome-typescript-
loader/node_modules/source-map-support/source-map-support.js:406:11)
remote:     at process.emit (/tmp/build_6cac525cd409f823d4d8849a2cb7eba2/client/node_modules/awesome-typescript-loade
r/node_modules/source-map-support/source-map-support.js:419:16)
remote:     at process._fatalException (bootstrap_node.js:296:26)
remote:
remote: npm ERR! Linux 3.13.0-100-generic
remote: npm ERR! argv "/tmp/build_6cac525cd409f823d4d8849a2cb7eba2/client/.heroku/node/bin/node" "/tmp/build_6cac525c
d409f823d4d8849a2cb7eba2/client/.heroku/node/bin/npm" "run" "heroku-postbuild" "--if-present"
remote: npm ERR! node v6.6.0
remote: npm ERR! npm  v3.10.3
remote: npm ERR! code ELIFECYCLE
remote: npm ERR! author-wizard@0.0.0 heroku-postbuild: `ng build`
remote: npm ERR! Exit status 7
remote: npm ERR!
remote: npm ERR! Failed at the author-wizard@0.0.0 heroku-postbuild script 'ng build'.
remote: npm ERR! Make sure you have the latest version of node.js and npm installed.
remote: npm ERR! If you do, this is most likely a problem with the author-wizard package,
remote: npm ERR! not with npm itself.
remote: npm ERR! Tell the author that this fails on your system:
remote: npm ERR!     ng build
remote: npm ERR! You can get information on how to open an issue for this project with:
remote: npm ERR!     npm bugs author-wizard
remote: npm ERR! Or if that isn't available, you can get their info via:
remote: npm ERR!     npm owner ls author-wizard
remote: npm ERR! There is likely additional logging output above.
remote:
remote: npm ERR! Please include the following file with any support request:
remote: npm ERR!     /tmp/build_6cac525cd409f823d4d8849a2cb7eba2/client/npm-debug.log
remote:
remote: -----> Build failed
remote:
remote:        We're sorry this build is failing! You can troubleshoot common issues here:
remote:        https://devcenter.heroku.com/articles/troubleshooting-node-deploys
remote:
remote:        If you're stuck, please submit a ticket so we can help:
remote:        https://help.heroku.com/
remote:
remote:        Love,
remote:        Heroku
remote:
remote:  !     Push rejected, failed to compile Node.js app.
remote:
remote:  !     Push failed
remote: Verifying deploy....
remote:
remote: !       Push rejected to evening-castle-95407.
remote:
To https://git.heroku.com/evening-castle-95407.git
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'https://git.heroku.com/evening-castle-95407.git'

My package.json looks like this:
{
  "name": "author-wizard",
  "version": "0.0.0",
  "engines": {
    "node": "6.6.0",
    "npm": "3.10.3"
  },
  "license": "MIT",
  "angular-cli": {},
  "scripts": {
    "lint": "tslint \"src/**/*.ts\"",
    "test": "ng test",
    "pree2e": "webdriver-manager update",
    "e2e": "protractor",
    "preinstall": "npm install -g node-gyp",
    "heroku-postbuild": "ng build"
  },
  "private": true,
  "dependencies": {
    "@angular/common": "~2.0.0",
    "@angular/compiler": "~2.0.0",
    "@angular/core": "~2.0.0",
    "@angular/forms": "~2.0.0",
    "@angular/http": "~2.0.0",
    "@angular/platform-browser": "~2.0.0",
    "@angular/platform-browser-dynamic": "~2.0.0",
    "@angular/router": "~3.0.0",
    "core-js": "^2.4.1",
    "rxjs": "5.0.0-beta.12",
    "ts-helpers": "^1.1.1",
    "zone.js": "^0.6.23",
    "@types/jasmine": "^2.2.30",
    "@types/node": "^6.0.42",
    "angular-cli": "1.0.0-beta.17",
    "codelyzer": "~0.0.26",
    "jasmine-core": "2.4.1",
    "jasmine-spec-reporter": "2.5.0",
    "karma": "1.2.0",
    "karma-chrome-launcher": "^2.0.0",
    "karma-cli": "^1.0.1",
    "karma-jasmine": "^1.0.2",
    "karma-remap-istanbul": "^0.2.1",
    "protractor": "4.0.9",
    "ts-node": "1.2.1",
    "tslint": "3.13.0",
    "typescript": "2.0.2"
  },
  "devDependencies": {
  }
}

The only thing I added that wasn't in the tutorial was the engine definitions, but Heroku was saying to put that in (to match my local versions) if I had problems deploying.

"engines": {
      "node": "6.6.0",
      "npm": "3.10.3"
    },

Any tips on how to move forward with deployment would be awesome.  Thanks!
Update
changed package.json from
"heroku-postbuild": "ng build"

to
"heroku-postbuild": "ng build -prod"

And it deployed fine.  Still having other issues w Uglifier gem but this issue is addressed.  Thanks @jasonswett


text:
Q: Local Degree of smooth map vs Degree of a Covering Consider any two oriented connected closed smooth manifolds
$M, N$ of same dimension $n \ge 1$. Let $f : M \to N$ be a smooth map. Recall that a regular value of $f$ is a point $y \in Y$ such that the differential $D_xf^*$ of $f$ is invertible at each point of
$x \in f^{−1}(y)$. It is a basic result due to Sard that the complement in $N$ of the set of regular values has Lebesgue measure zero; in particular, the set of regular values of $f$ is dense , and so non-empty.
If $y \in N$ is a regular value of $f$, then $f$ is a local diffeomorphism around every $x \in f^{−1}(y)$; it follows that $f^{−1}(y)$ is discrete in $M$; since this fiber is also compact, it is
therefore finite. For $x \in f^{−1}(y)$ define $\epsilon_x(f)$ to be $1$ if $f$ is orientation preserving at $x$ and $−1$ if f is orientation reversing at $x$.
Definition: The local degree of $f$ at a regular value $y$ is the integer
$$\text{deg}(y)(f) = \sum_{x \in f^{−1}(y)} \epsilon_x(f) $$
In other words it's the difference of the number of points in the fiber at $y$ where $f$ in a neighbourhood of $x$ is orientation preserving minus the number of points where $f$ is locally orientation reversing.
Non assume that $f: M \to N$ is in addition a finite covering in topological sense. Then one can also define purely topologically the degree of $f$ to be  the number of elements in the fiber: $ \vert f^{−1}(y) \vert $
Question: Do these two definition coincide (up to $\pm 1 $ sign)? Or in equivalent terms, is a honest covering map (ie without any ramificational defects) always locally orientation preserving?

A: After having fixed orientations on $M$ and $N$ the correct statement becomes for every $y \in N$:  $$ \vert \text{deg}(y)(f) \vert  = \vert f^{−1}(y) \vert  $$
That's because the function $M \to \{\pm1 \}$ which associates to every $x \in M$ the sign of the determinant of derivative $D_x f$ (-which is nowhere zero, because a covering is a local diffeomeorphism) is a locally constant function and because $M$ was assumed to be connected, this function is even constant.


text:
Q: how to set a UI that easily span to any ios device? This might be generic question, wanted to know if theres way to set an unique UI or the view for an ios device using swift that can be easily span to any ios device without being broken. I have read through couple of articles and saw few videos but no one gives a proper answer of what are the basics of setting the UI element that makes it easier to be spanned across devices

A: There are several ways to do this. You could use auto-layout or you can do the plumbing yourself by implementing layoutSubviews for each of your custom views (you can think of auto-layout as a layer above layoutSubviews). If you'd implement layoutSubviews directly you might also want to override methods like sizeThatFits.


text:
Q: How to use IGrouping enumeration in C# I have a code in C# that uses IGrouping, but I didn't do it and I don't know how to fix the error that is occurring. Here's the code:
public static class ListExtensions
{
   public static List<List<T>> ChunkBy<T>(this List<T> source, int chunkSize) => source.Select((x, i) => new
   {
          Index = i,
          Value = x
   })
   .GroupBy(x => x.Index / chunkSize)
   .Select<IGrouping<int, \u003C\u003Ef__AnonymousType0<int, T>>, List<T>>(x => x.Select(v => v.Value).ToList<T>()).ToList<List<T>>();

A: If you are on .Net 6 you should use the built in Enumerable.Chunk method. If you are on an older version I would suggest an implementation that uses avoids using GroupBy to chunk the list, something like:
public static IEnumerable<List<T>> Chunk<T>(this IEnumerable<T> self, int chunkSize)
{
    var list = new List<T>(chunkSize);
    foreach (var item in self)
    {
        list.Add(item);
        if (list.Count >= chunkSize)
        {
            yield return list;
            list = new List<T>(chunkSize);
        }
    }
    if (list.Count > 0)
    {
        yield return list;
    }
}

While this is a little bit more code, it works with any IEnumerable, not just List. It will also be evaluated lazily, so will work fine even if the source sequence is infinite.


text:
Q: Hyperledger Fabric: 'Orderer' has invalid keys: EtcdRaft while using the configtx.yaml from official Hyperledger repo we get below error when trying to create a genesis block:
root@774983db9864:/home# configtxgen -profile OrgsOrdererGenesis -outputBlock genesis.block -channelID 4chan
2019-03-05 19:25:44.240 UTC [common/tools/configtxgen] main -> INFO 001 Loading configuration
2019-03-05 19:25:44.261 UTC [common/tools/configtxgen/localconfig] Load -> CRIT 002 Error unmarshaling config into struct:  2 error(s) decoding:

* 'Orderer' has invalid keys: EtcdRaft
* 'Profiles[OrgsOrdererGenesis].Orderer' has invalid keys: EtcdRaft
2019-03-05 19:25:44.262 UTC [common/tools/configtxgen] func1 -> CRIT 003 Error unmarshaling config into struct: 2 error(s) decoding:

* 'Orderer' has invalid keys: EtcdRaft
* 'Profiles[OrgsOrdererGenesis].Orderer' has invalid keys: EtcdRaft
panic: Error unmarshaling config into struct: 2 error(s) decoding:

* 'Orderer' has invalid keys: EtcdRaft
* 'Profiles[OrgsOrdererGenesis].Orderer' has invalid keys: EtcdRaft [recovered]
    panic: Error unmarshaling config into struct: 2 error(s) decoding:

* 'Orderer' has invalid keys: EtcdRaft
* 'Profiles[OrgsOrdererGenesis].Orderer' has invalid keys: EtcdRaft

goroutine 1 [running]:
github.com/hyperledger/fabric/vendor/github.com/op/go-logging.(*Logger).Panic(0xc420195e00, 0xc420523560, 0x1, 0x1)
    /opt/gopath/src/github.com/hyperledger/fabric/vendor/github.com/op/go-logging/logger.go:188 +0xbd
main.main.func1()
    /opt/gopath/src/github.com/hyperledger/fabric/common/tools/configtxgen/main.go:254 +0x1ae
panic(0xc6ea00, 0xc420523550)
    /opt/go/src/runtime/panic.go:505 +0x229
github.com/hyperledger/fabric/vendor/github.com/op/go-logging.(*Logger).Panic(0xc420195c50, 0xc42054e120, 0x2, 0x2)
    /opt/gopath/src/github.com/hyperledger/fabric/vendor/github.com/op/go-logging/logger.go:188 +0xbd
github.com/hyperledger/fabric/common/tools/configtxgen/localconfig.Load(0x7fffbcd538da, 0x12, 0x0, 0x0, 0x0, 0xc4201b3540)
    /opt/gopath/src/github.com/hyperledger/fabric/common/tools/configtxgen/localconfig/config.go:284 +0x607
main.main()
    /opt/gopath/src/github.com/hyperledger/fabric/common/tools/configtxgen/main.go:265 +0xce7

How can we fix this please?

A: Solution is to delete the EtcdRaft section as the Raft based consensus is not yet implemented in Hyperledger Fabric v1.3 or 1.4. The configtx.yaml in the repo should not be having this section.

A: SampleMultiNodeEtcdRaft:
    <<: *ChannelDefaults
    Capabilities:
        <<: *ChannelCapabilities
    Orderer:
        <<: *OrdererDefaults
        OrdererType: etcdraft
        EtcdRaft:
            Options:
              TickInterval: 500ms
              ElectionTick: 10
              HeartbeatTick: 1
              MaxInflightBlocks: 5
              SnapshotIntervalSize: 20971520
            Consenters:

...


text:
Q: Comma seperated list using brackets in query string I have a query string being sent to a php file as so: participants[]=111111111,22222222,333333333 etc....
If I remove the [] it functions fine, however, if I leave it in it ignores the array for each. How can I make PHP iterate through the comma seperated values with [] on the variable name? I tried explode which also failed unless I removed the []. I need to create a for each statement for the number of values returned for that var.
I have the following PHP code:
$participants = $_REQUEST["participants"];
foreach($participants as $i=>$value) {
    if($value > 1) {
        // define each variable
        $id = $_REQUEST['participants'][$i];
        print "$id
";
    }

}

A: I suggest using explode() in your code.
Since you can't remove the brackets in your query string, you may test the following code:
$participants = explode(',', $_REQUEST["participants"][0]);
foreach($participants as $i=>$value)
{
    if(intval($value) > 1) {
        // define each variable
        $id = $participants[$i];
        print "$id
";
    }
}

The output now is:
111111111
22222222
333333333


text:
Q: Formula that return the date when the checkbox was selected I am trying to make a formula which will return the date when the checkbox was clicked. This is what I got now and it's not working since it gives the value for all fields as same date.
if(Call_Attempts__c = True , NOW(), NULL )

I know that the code NOW() gives all values for current date for all fields and I need a return date for last modified specific field.
Thanks,
Darko

A: Instead of a formula, create a new Date or Datetime field, and update it to NOW() via a Workflow Field Update or via a trigger, whenever you detect that the Checkbox value has been changed from False to True.


text:
Q: How to select data between two dates using only the start date? I have problem select data between two dates if the only start_date is available.
The example I want to see is what discount_nr was active between 2020-07-01 and 2020-07-15 or only one day 2020-07-14. I tried different solutions, date range, generate series, and so on, but was still not able to get it to work.
Table only have start dates, no end dates
Example:
discount_nr, start_date
1, 2020-06-30
2, 2020-07-03
3, 2020-07-10
4, 2020-07-15

A: You can get the end dates by looking at the start date of the next row. This is done with lead. lead(start_date) over(order by start_date asc) will get you the start_date of the next row. If we take 1 day from that we'll get the inclusive end date.
Rather than separate start/end columns, a single daterange column is easier to work with. You can use that as a CTE or create a view.
create view discount_durations as
select
  id,
  daterange(
    start_date,
    lead(start_date) over(order by start_date asc)
  ) as duration
from discounts

Now querying it is easy using range operators. @> to check if the range contains a date.
select *
from discount_durations
where duration @> '2020-07-14'::date

And use && to see if they have any overlap.
select *
from discount_durations
where duration && daterange('2020-07-01', '2020-07-15');

Demonstration


text:
Q: How can I obtain a conditional distribution from a joint distribution using a MCMC sample? Suppose that $\theta = (\theta_1,\theta_2) \in{\mathbb R}^2$ are the parameters of a model, and that I can obtain a MCMC sample from the posterior distribution of $\theta \mid {\bf x}$.
Using the MCMC sample, how can I obtain the conditional posterior distribution
$$\theta_2 \mid \theta_1, {\bf x}\,?$$

A: If one is using a Gibbs sampler, which is a specific type of MCMC algorithm, the conditional distributions of $θ_1$ given $θ_2,x$ and of $θ_2$ given $θ_1,\mathbf x$ are a requirement for running the algorithm. Hence $\pi( θ_2|θ^0_1,\mathbf x)$ is available as a generative model, if not necessarily in closed form.
Otherwise, in the general case, a sample from $$\pi(\theta_1,\theta_2|\mathbf x)\propto p(\mathbf x|θ_1,θ_2)π(θ_1,θ_2)$$ does not provide direct information about $\pi( θ_2|θ^0_1,\mathbf x)$, except by using a non-parametric estimator of the conditional density. Except for special cases, one need run a new MCMC algorithm with target $$\pi( θ_2|θ^0_1,\mathbf x)\propto p(\mathbf x|θ^0_1,θ_2)π(θ^0_1,θ_2)$$where $θ^0_1$ is the value of $θ_1$ one wants to condition upon.


text:
Q: Refresh a table without refreshing entire page to show updated data I wish to show newly added data to a listing page, which listed on the same page. My problem is that after adding data to my database I needed to reload entire page to see the new data. How can I view without reloading entire page?

A: If you only want to refresh the table, you can use this jQuery plugin: http://datatables.net
You can call table refresh functions whenever you want. The plugin works using AJAX. To work with you need to have little javascript knowledge as well.
You can find sort of example/demo from here.
http://editor.datatables.net/tutorials/api_manipulation
However if you really want to do this get the concept and you also can develop same thing. You just require to learn some AJAX.

A: in Button click after data saved to database you need to use following script. no need to go round trips to server to client instead manipulate client side.
$("#btnSubmit").click(function () {
$('#myForm').ajaxForm({
    success:   function(){
       $('#myTable tr:first').after('
' + $("#Name").val() + '
');
    }
});
});


text:
Q: Resources for 2d game physics I'm looking for some good references for learning how to model 2d physics in games. I am not looking for a library to do it for me - I want to think and learn, not blindly use someone else's work.
I've done a good bit of Googling, and while I've found a few tutorials on GameDev, etc., I find their tutorials hard to understand because they are either written poorly, or assume a level of mathematical understanding that I don't yet possess.
For specifics - I'm looking for how to model a top-down 2d game, sort of like a tank combat game - and I want to accurately model (among other things) acceleration and speed, heat buildup of 'components,' collisions between models and level boundaries, and missile-type weapons.
Websites, recommended books, blogs, code examples - all are welcome if they will aid understanding. I'm considering using C# and F# to build my game, so code examples in either of those languages would be great - but don't let language stop you from posting a good link. =)
Edit: I don't mean that I don't understand math - it's more the case that I don't know what I need to know in order to understand the systems involved, and don't really know how to find the resources that will teach me in an understandable way.

A:
(source: oreilly.com)
Physics for Game Developers by O'Reilly

A: Speaking from experience, implementing a 2D physics engine is pretty difficult. I'll detail the several steps I took when creating my engine.

*

*Collision detection. Collision detection can be a difficult problem, even when you're not dealing with 3D worlds or networked simulations. For 2D physics, you definitely want to use the Separating Axis Theorem. Once you've implement SAT, you're half-way done making the dynamics portion of your engine.

*Kinematics/Dynamics. Chris Hecker has written an excellent online resource which walked me through collision response step-by-step.

*Everything Else. Once you've got the collision detection/response finished, its a matter of implementing everything else you want in the engine. This can include friction, contact forces, joints, along with whatever else you can think of.
Have fun! Creating your own physics simulation is an incredibly rewarding experience.

A: This is a great tutorial that demonstrates 2D physics concepts using flash and is not specific to flash.
http://www.rodedev.com/tutorials/gamephysics/game_physics.swf

A: Even if you want to learn it all from the bottom up, an open source physics library that is well coded and documented contains far more information than a book. How do I deal with situation x... find in files can be faster than a paper index.
Original response:
What, no mention of Box2D?  Its an open source side project of a blizzard employee, has a good community, and well, works great.
In my (brief) experience with Box2D, integrating it with Torque Game Builder, I found the API clean to use, documentation was clear, it supported all the physics objects I expected (joints in particular were a requirement), and the community looked friendly and active (sometime around early 2010).
Judging by forum posters, it also appeared that managers were receptive to source contributions (that did not carry license baggage).
It's island based solver seemed quite fast, as I expected from its reputation, not that I did any major performance testing.

A: Here are some resources I assembled a few years ago.  Of note is the Verlet Integration.
I am also including links to some open source and commercial physics engines I found at that time.  There is a stackoverflow article on this subject here: 2d game physics?
Physics Methods

*

*Verlet Integration (Wikipedia Article)

*Advanced Character Physics (Great article! Includes movement, collisions, joints, and other constraints.)

Books

*

*"Game Physics Engine Development", Ian Millington -- I own this book and highly recommend it.  The book builds a physics engine in C++ from scratch.  The Author starts with basic particle physics and then adds "laws of motion", constraints, rigid-body physics and on and on.  He includes well documented source code all the way through.

Physics Engines

*

*Tokamak (Open source physics API)

*APE (Actionscript Physics Engine)

*FLADE (Flash Dynamics Engine)

*Fisix Engine (another Flash Actionscript engine)

*Simple Physics Engine (commercial)

A: F# has a feature called Units of Measure which does dimensional analysis for you, providing errors if you get it wrong. For example if you say:
let distance : float<meters> = gravity * 3.0<seconds>

That would yield a compile-error, since gravity is < meters/seconds^2 > and not < meters >. Also, since F# is just .NET you can write your math/physics code in a class library and reference that from your C#.
I'd reccomend you check out these blog posts for more information:

*

*Simple WPF game in F# using Units of Measure

*Andew Kennedy's blog

A: This is a great resource for writing your first engine. It's in 3D but it's very easy to convert down to 2D. I know at least one big company that followed this tutorial for their internal engine, and i personally have followed his steps for my own engine. He explains all the basic physics concepts in spring/impulse based physics, and shows you how to write your own intergrater.

A: The F#.NET Journal has published two articles about this:

*

*Real-time Finite Element Materials simulation (15th June 2008).

*Rigid body dynamics (15th January 2010)


text:
Q: Getting error while building a mule 4 project in jenkin I'm doing setup of jenkin pipeline with the GitHub. setup has been done. Deployed mule 4 project in Git.
Jenkin checkout process is working properly but for build process i'm getting below mentioned error.
Running as SYSTEM
Building in workspace E:\IDFC\github_checkoutCode
[github_checkoutCode] $ cmd /c call C:\WINDOWS\TEMP\jenkins8773003533490857843.bat
** E:\IDFC\github_checkoutCode>mvn clean install
'mvn' is not recognized as an internal or external command,
operable program or batch file.
E:\IDFC\github_checkoutCode>exit 9009
Build step 'Execute Windows batch command' marked build as failure
Finished: FAILURE **
i have done environment variable setup MAVEN_HOME.
How can i Fix this error.

A: The error indicates that Jenkins can not find the Maven command (mvn.bat in Windows). Probably you need to add the %MAVEN_HOME%/bin directory to the path.
I don't see any Mule related issues.


text:
Q: Spring Boot 2 - availableProcessors() returning 1 always Java 8, Spring Boot 2.
I was testing performance using multiple threads and CompletableFuture when I realized that only 1 core in choking and rest of them are basically not doing much work.
high load on only 1 core
Some load on other cores is probably caused by other processes running on the machine.
I tried to figure out what is the issue and than realized that
Runtime.getRuntime().availableProcessors()

is always returning 1 in runtime. It doesn't matter if I started multiple threads or not, number is always 1 (should be 8).
Then I created simple Unit test class and run availableProcessors() code and got 8. Cleary, something connected to Spring context is making runtime not to see all available cores.
Help?

A: Problem was not connected to Hibernate, Spring or any other container. We have jni4net Bridge registering DLL file (3rd party library) during startup. When first Service class from the DLL was instantiated we got reduction from 8 to 1 core... Obviously something to do with dll or the bridge. Since that is the issue of completely other kind I think thats enough for this post.


text:
Q: Disabling asp.net button on click and show loading image I am working on an asp.net page. Page as a button which redirects user to another page using response.redirect. I want to disable the button and show a loading icon.
I used this jquery
$('.rbutton').on('click', function () {
$(this).prop("disabled", true);

It disables the button but then server side code is not fired.
button is not surrounded with ajax update panel. I don't want to use ajax toolkit.
How can I show loading image on click of search button and then disable the button until user is redirected to new page ?

A: ASP.Net won't execute server code for a disabled button. In the past, I've simply hidden the button and replaced it with another button that is disabled... has worked well for me.
<asp:Button ID="_pay" OnClick="SomeGreatCode" Text="Pay Up!" runat="server" />
<asp:Button ID="_process" Enabled="false" Text="Processing..." runat="server" />

<script>
$(document).ready(function () {
    $("#<%= _process.ClientID %>").hide();
    $('#<%= _pay.ClientID %>').on('click', function () {
        if (Page_IsValid) {
            $(this).hide();
            $("#<%= _process.ClientID %>").show();
        }
    });
});
</script>


text:
Q: Listview in TabActivity hide layout This is the context: I have a TabActivity with three tabs,|Contacts|History|Caller| in the tab on contacts, I have another TabActivity. In this TacActvity I have set the tabwidget invisible and I use a personal layout on the top to change among tabs: |Server|Agenda|Directory| basically i use the onClick event to setCurrentTab in the TabHost. If I set a normal Activity on a TabContent its OK, the problem is when I set a ListActivity with a ListView as the TabContent,in that case the lisview hide the 3 buttons on the on the top, and I can no longer interact with those buttons. As you can see on the image
Any ideas of why or how to solve this?

A: Is the android:layout_height set to fill_parent for the ListActivity?
Changing it to wrap_content might help


text:
Q: What happens to multiple parallel tasks running on a server when CPU hits 100% usage? I am running 10 instances of the same executable where each executable is accessing a different 1/10 chunk of the total data that needs to be processed on a Windows Server 2012 R2. (Intel(R) Xeon(R) 2.4GHz (2 processors), 64GB RAM)
My question is if the CPU hits 100% usage, are the 10 instances still being parallel processed? Or Does the CPU start sequencing them instead of parallel processing them? Am I better off simply reducing the number of instances till the CPU usage is less than 100%?

A: What a weird question.
"Parallel processing" does not imply that threads execute in any particular order, or at any particular rate of completion, or in lockstep with regards to their individual steps, or anything like that at all.  There is no guarantee as to order of beginning or ending of execution.
If you need to synchronize your threads so that they finish at the same time, the best way to do that it to write synchronization logic in your code that waits for all threads to finish before moving on to the next task.  There are a variety of ways to do this depending on your programming language.

A:
My question is if the CPU hits 100% usage, are the 10 instances still being parallel processed?

Yes.

Or Does the CPU start sequencing them instead of parallel processing them?

Your processor probably doesn't have 10 CPU cores, so yes, it is doing swapping of them in some sequence, too.  But it does not suddenly run one thread to completion when it gets to 100%.  It is using swapping to give each thread a time slice; and it is doing this whether it is at 100% or not.

Am I better off simply reducing the number of instances till the CPU usage is less than 100%?

No, you want 100% CPU usage, or else you're wasting cycles!
However, that is not even close to the whole story, and, 100% CPU is not a great measurement of the efficiency of the CPU cycles that are being used.
You should probably run as many threads as your processor has CPU cores.  (If you are using single threaded processes, then count those as threads.)  When you run more than that, then the operating system swaps the threads into and out of the CPU cores in a balance of fairness and other policies that gives each thread a time slice here and there.
Swapping causes various kinds of overheads: direct overhead as cycles are wasted doing swapping instead of your work, and indirect overhead, which has to do with the operation of the caches — the highest speed memories that are directly on the processor die.  Caches form one level of the memory hierarchy, which also includes main memory (your 16+ GB of RAM) and ultimately also includes the disc as a form of memory.  Using the memory hierarchy well is the key to performance throughput.
As each thread runs for a while, it will take over part of the cache for it's own purposes.  In some sense, the cache is warming up to that thread, and this is good.
When the operating system can, it will give consecutive time slice to the same thread on the same processor, and the that thread will have a warm cache to start.
Too many threads at once will cause undo cache pollution as due to their being swapped in: when a thread is first swapped in, the cache will be cold for it, and it will have to warm up before you're getting to best performance.

Yet still, processing a large data set efficiently requires not just keeping the cores busy but also broadly getting better use of the memory hierarchy.
One approach to finding a good way to slice the work, which you can tweak and refine by timing, is something like this:
Divide the whole work into chunk size that are about the size of the large processor cache (L3, maybe).
Then divide each chunk of work into sections of as many processor cores as the processor has (e.g. 2, 4), and run those.  Then as those sections complete, run  subsequent sections of the next chunk.
A lot has to do with the workload, and the cache architecture.  Smaller L1 caches are likely to be replicated and each dedicated to a particular CPU core; larger L2 and L3 caches may be shared by all cores, though potentially with restriction such that one CPU core doesn't starve the others.
It goes to how your specific workload runs on the specific cache architecture on the machine in question.  So, subdividing the chunks by the L3 size may work well, but chunks of the L2 size may work better.
One application/workload may access its section over and over in a more or less random way, while a different application/workload may only run serially thru the section start to finish.  These different workloads have different efficiency aspects in the memory hierarchy, so breaking them up in some different way might help or hurt one or the other workload.
There are also better measurements you might want to take using various tooling.

A: Here's a more simple-minded answer. Ignoring some power management stuff (which mostly won't be relevant in this situation anyway), a CPU core is either going full out or it's idling. So why isn't the CPU usage always at 100%? Aren't you always doing something? Why would a CPU core be idling? A CPU core idles when there is no work to do. There are two reasons there could be no work to do.
First, there could literally be nothing that needs to be done. For example, if you run a single instance of a single-threaded program and you have multiple cores, say 2, then the core that isn't running the program has nothing to do. In this case, the overall CPU usage can only be 50% at best. This is why you typically want to have at least as many threads as cores.
Second, and more common, the CPU is waiting for something. If you want to read in a file and process it, the CPU has to wait until the file is read in before it can move on to processing. Nowadays reading a file mostly doesn't involve the CPU but hard drives (including SSDs) can be many orders of magnitude slower than the CPU (depending on access patterns). In the meantime, the CPU looks for other things to do. If it can find something else to do, it switches to that, otherwise it idles.
So, a 100% CPU usage regime, means whenever the CPU looks for new work, it finds it. Anything less than 100% CPU (assuming you have at least as many threads as cores) means the CPU is often finding itself in the situation that all threads are blocked waiting for something. All other things equal, anything less than 100% CPU usage means you are wasting cycles. In practice, the bottleneck is often I/O bandwidth or memory. We talk of CPU-bound, I/O-bound, and memory-bound processes. If one of these other resources are the bottleneck, then forking more threads/processes to try to get 100% CPU usage is either not going to succeed or it's not going to make the work complete any sooner. In fact, it's likely to be harmful. If I fork two memory-bound processes, then when I switch between them, I'm going to have to swap out the memory of one to swap in the memory of the other, at which point the CPU idles waiting for the memory to swap in. High performance applications typically carefully manage scheduling to get the best disk access patterns and make sure everything relevant always fits in memory (and caches).