text:
Q: Drawbacks of using preload? Why isn't it included by default? I would like to know what are the drawbacks of using preload? If there would be no downside, preload would be enabled by default, so I guess there are some.
Okay you need a bit more RAM, but most people have by far more RAM then Ubuntu needs - so what are the downsides of using preload?

A: Simply put, Preload isn't for everyone. It is great if you open applications or libraries a lot. It is harmful if you load applications or libraries only occasionally. I will use two examples from my actual usage (and yes I use preload).
First, Google Chrome. Now a browser is opened only once per boot, maybe twice (for me, I am a web developer). Chrome and its related libraries stay in memory because I am always using it. Even when I close all the chrome windows it's still in the background doing its thing. Thus all the ram dedicated to holding a preload copy of Chrome is a total and utter waste. It's never (or rarely) unloaded. For the average user this is true for a great number of applications. A Office user will almost always have their email app open. So the small savings in startup time is completely wasted because they only open their email app once a day, and leave it open.
The Second example is rake. As a ruby developer that believes in testing I run rake a TON. rake runs, executes for a couple of seconds - minutes then exits. Preload helps me speed up my daily work because it loads rake and its needed libraries (which can be very extensive) ahead of time. So there are a lot of starts and stops to the running of rake. The extra ram used to speed up the 400 or 500 launches of rake over the span of a few hours is totally worth it.
So the reason it's not enabled by default is because its ability to actually improve performance is based largely on how you use your system. For some people it will be a negative and for others a positive.
Lastly, having preload on, even if you're not using it, consumes ram. So if you're not launching applications frequently, you could actually make your entire system fractionally slower by not having that ram available for other types of caching. Remember, even if you have 32 Gigs of ram Linux will try to use as much of it as it can to cache data to make your interaction faster. By using preload you reduce that free memory some. Even if it is just a little tiny bit, the 2 seconds you saved launching chrome 1 time could cost you 60 seconds over the month it stays running.

A:
Question asked by bountier Saeed Zarinfam on September 5, 2012:
Hi all, I want to know, Is it a myth? Does [preload] really improve my performance? What are drawbacks of using it? I have a laptop with this specification (Core i5 CPU, 4GB RAM, 128GB SSD Hard). Thank you so much.

*

*There's no real need for preload if you have an SSD

*

*This is because SSDs provide much faster random access times than hard disks, so "pre-loading" binaries/dependencies in memory is a waste, IMO

*The basic downside then is that preload is "using" additional memory without providing a tangible benefit.

A:
Preload is an "adaptive readahead daemon" that runs in the background
of your system, and observes what programs you use most often, caching
them in order to speed up application load time. By using Preload, you
can put unused RAM to good work, and improve the overall performance
of your desktop system.
Don't expect to see a drastic change in performance
right away. Also, if you're just opening/closing applications
repetitively, your computer will store those files in cache anyway
(this is called a "warm" load), so you won't see any difference in
speed there. You will, however, see a speed improvement if, for
example, you use a program intermittently; these programs will start up
faster than without Preload.
Preload can provide a great improvement in application start up time;
since most modern machines have a good deal of memory to spare,
Preload puts this RAM to good use.1

Now that being said, it seems that preload is a great utility, and it might be.
I think that the reason its not preloaded with the OS, is because the user has to know exactly what there doing, and have enough experience to be able to use it, and the system has to have enough RAM.
On a more technical aspect, preload works by moving data from the hard disk to RAM, which makes most hard disk to go to sleep mode if not used, and then have to spin back up when needed.  So spinning up/down the drive, would cause the Load/Unload Cycle count, and the Power-On time count rise, and that will shorten the life of the drive.

We designed and implemented preload, a Markov-based adaptive
prefetching scheme that works on application-level predictions.
Moreover, preload is implemented in the userspace and does not change
the application run-time environment in any sense. This is the first
work experimenting with file-system prefetching at this level as far as
we know.
Our experimental results show promising improvements on application
start-up time compared to cold caches, and a decent hit rate compared
to a na¨ıve prediction algorithm.
However, being in user-space introduces major obstacles into making
preload a competitive solution to the startup-time problem. In
particular, not having full information about applications' I/O
requests, and lack of strong communication channels with the
page-cache subsystem degrades preload's effectiveness drastically,
especially under tight memory conditions.
Another inherent problem with the preload design is high variance and
low prediction confidence caused by the relatively loose correlation of
application start-ups. While we successfully build a model to track
application correlations, the fact that application launches are very
rare events compared to the timescale that computers work on, an
application-level prefetching scheme is condemned to consume huge
prefetching memory over practically infinite periods of time. This
memory can be used to improve short-term cache behavior.
Finally, we come up with a set of recommendations for system
developers on how to improve boot-time, login-time, and application
startup-time without falling back to a prefetcher integrated with the
cache subsystem in the kernel. Of course, a file-based prefetcher in
the kernel can improve on top of that.2

1Source:techthrob
2Source:Preload - An Adaptive Prefetching Daemon by Behdad Esfahbod - A thesis submitted in conformity with the requirements for the degree of Master of Science - Graduate Department of Computer Science - University of Toronto Copyright (c) 2006 by Behdad Esfahbod.

A: Drawbacks? There are NONE!
Increased performance opening applications by the user. I have used it for years on my systems as well as "read-ahead" and have no issues. The bug page for preload doesn't suggest any drawbacks either.
Preload monitors applications that users run, and by analysing this data, predicts what applications users might run, and fetches those binaries and their dependencies into memory for faster startup times.
It does increase the boot time slightly however the speed decrease fetching time of applications far exceeds this little issue.
see article
If you're constantly using common apps like Firefox or Gimp you'll notice some greatly improved load times. Preload is a daemon that runs discretely in the background and will not disrupt your desktop in anyway. Ubuntu users can install preload with:
sudo apt-get install preload

Results:

ref

A: I think that preload does almost nothing. What it seems to do is to load all frequently accessed pages into RAM and locks them there so they stay there.
The kernel does almost the same. It keeps dirty pages which are files that were used by a program (or are the program itself). If the program doesn't need those pages anymore, so it closes the file.... python:
file=open('file.txt') # open the file
....
file.close            # close the file

.... then the kernel will still keep them in the RAM and only overwrite those dirty pages if the RAM is ...% full.
Preload only enhances the process but may even slow down the system. It loads applications into RAM but locks them so the kernel cannot release them if the RAM is full. Preload automatically releases them, too, but the kernel has to release the dirty pages before the pages locked by preload are released. Preload has to decide when the locked pages are released and so it can be a waste because if you have the browser opened all the time preload will lock it. Now you close the browser - preload will still lock it. You use all the RAM - preload will still lock it - and the kernel has to release the pages that are required at the moment. Because you don't want to browse anymore, you want to play a game. The game files have to be reloaded all the time because the kernel has to free it's dirty pages.
I don't know how exactly preload works, how it is learning and how efficient it is, but it would bloat the system for not really anything. Preload can waste RAM. It can waste HDD resources (especially slow down boot I read). The user shall decide if he wants it or not. Preload can help a lot if you're rebooting your system a lot, but if it's in suspend-to-ram often you wont need it. There is no noticeable difference.
One thing:
The kernel releases the oldest page if the threshold has been reached
Preload releases the file/page that's the most unnecessary.
But as I said: if you don't do what you usually do preload can waste your RAM a lot. Like.. You are not gaming much but coding often. Preload will be a waste when you're gaming but not really when you're coding.
That's my view. It may be wrong or correct, keep what you think is good, ignore what you don't like.

A: Here are some drawbacks of Preload and why it is not that effective for everyone
    I do have a decent specification system with 8GB RAM. So my system is generally fast. Also, I will open heavy memory-consuming applications, such as Firefox, Chrome, VirtualBox, Gimp etc., one or two times per day. They remain open all the time, hence their binaries and libraries are preloaded into memory and occupying the RAM all day. I rarely close and open those applications, so the RAM usage is simply waste.
    If you're using modern systems with SSD, Preload is obviously useless. Because SSDs access time is much faster than normal hard drives, so using Preload is pointless.
    Preload significantly affects the boot time. Because the more applications are preloaded into RAM, the longer it takes to get your system up and running.
You will only the see the real difference only if you're reloading applications a LOT of time per day. So Preload will be ideal for the developers and testers who open and close the applications several times every day.


text:
Q: What is the best method of starting/ stoping js anime timeline on input I'm attempting to create an animation (using anime.js) that plays an animation timeline once when the users starts typing and will loop for the duration that the user is typing in the input box. When the user stops typing the animation will complete its current loop and stop playing.
Here's my progress at the moment, you can observe the animation working incorrectly: https://codepen.io/andrewbentley/full/XqMrze
Here's what my anime.js code timeline:
var basicTimeline = anime.timeline({
  loop: true,
  autoplay: false,
  duration: 700
});

basicTimeline
  .add({
    targets: '#circ1',
    duration: 100,
    translateY: -10,
    easing: 'easeInQuad'
  })
  .add({
    targets: '#circ1',
    duration: 100,
    translateY: 0,
    easing: 'easeInQuad'
  })
  .add({
    targets: '#circ2',
    duration: 100,
    translateY: -10,
    easing: 'easeInQuad'
  })
  .add({
    targets: '#circ2',
    duration: 100,
    translateY: 0,
    easing: 'easeInQuad'
  })
  .add({
    targets: '#circ3',
    duration: 100,
    translateY: -10,
    easing: 'easeInQuad'
  })
  .add({
    targets: '#circ3',
    duration: 100,
    translateY: 0,
    easing: 'easeInQuad'
   })
  .add({
    targets: '#circ3',
    delay: 100
});

document.querySelector('#email').onkeypress = basicTimeline.play;
document.querySelector('#email').onkeyup = basicTimeline.pause;

Is anyone able to advise me as to the best way of achieving the desired effect whilst using anime.js timeline utility and the use of event listeners such as onkeypress, onkeyup etc.

A: I think you need a timer which pauses your animation after some time of inactivity.
https://codepen.io/anon/pen/qYoPKQ
var timer = false;
document.querySelector('#email').onkeypress = function () {
  if(basicTimeline.paused) basicTimeline.play();
  if(timer) clearTimeout(timer);
  timer = setTimeout(function() {
    basicTimeline.pause();
    basicTimeline.reset();
  }, 500);
};

A: The issue of stopping an animation at the end of the current loop has been raised here:
on github There are some good suggestions there.
Perhaps the best one is from Edrees Jalili

function pausableLoopAnime({loopComplete, ...options}) {
  const instance = anime({
    ...options,
    loop: true,
    loopComplete: function(anim) {
        if(instance.shouldPause) anim.pause();
        if(typeof loopComplete === 'function') loopComplete(anim);
    }
  });
  instance.pauseOnLoopComplete = () => instance.shouldPause = true;
  return instance;
}

const animation= pausableLoopAnime({
  targets: '.polymorph',
  points: [
      { value: '215, 110 0, 110 0, 0 47.7, 0 67, 76' },
      { value: '215, 110 0, 110 0, 0 0, 0 67, 76' }
  ],
  easing: 'easeOutQuad',
  duration: 1200,
});

setTimeout(animation.pauseOnLoopComplete, 100)

redpajama_set_name: RedPajamaStackExchange


text:
Q: jQuery - Add element once the screen width is below 500px I would like to add an element to the body once the width of the screen is below 500px. I used the code below but the element does not appear. Hopefully somebody is able to help me out?
$(window).resize(function(){
if ($(window).width() <= 500){
  $("body").append("Home");
} });

A: $(window).resize(function(){
    if ($(window).width() <= 500){
        $("body").append("Home");
    }
});

Notice the single quotes around the hash tag (your code should now work).
If you want to use double-quotes inside a double-quoted string, your other option is to escape them, as such:
"Home"

Notice the backwards slashes?  That escapes a special character.  This method should work for you as well.  Same works the opposite way.  So, to conclude, all of these will work:
"Home"

"Home"

'Home'

'Home'

See this article, jQuery API Documentation: String Quoting, for more information.
IMPORTANT
If the user resizes their browser, say, 3 times, then your script will end up appending 3 different anchor elements, which I don't think is what you are wanting.
So, what you may consider doing is simply putting your link INSIDE the HTML page itself, and then using CSS to hide it.  Then, when the user goes below 500px, you can show the element, and when the user goes above 500px, you can hide it again, like so:
HTML:

Home

CSS:
.hidden-link {
    display: none;
}

jQuery:
$(window).resize(function(){
    if ($(window).width() <= 500) {
        $('.hidden-link').show();
    } else {
        $('.hidden-link').hide();
    }
});

Also, just as a side note, since I have not seen the rest of your code, ensure that you are putting everything inside $(function() { }); (if you haven't already), which executes everything once the browser has had a chance to parse all the HTML into the DOM.
CSS-only method
You could simply use media-queries, if you like:
.hidden-link {
    display: none;
}

@media only screen
and (max-width : 500px) {

    .hidden-link {
        display: inline;
    }

}

A: You have a syntax error in the string that contains the HTML code. If you use apostrophes to delimit the string, you can use quotation marks inside the string without escaping them.
Use a variable to keep track of wether you have already added the element. Put the code that checks the size in a function, so you can use it as an event handler, but also call it directly from the start, to check if the window already happens to be small enough.
$(function(){

    var added = false; // keep track of whether the element is added

    function checkSize() {
        if (!added && $(window).width() <= 500) {
            $("body").append('Home');
            added = true;
        }
    }

    $(window).resize(checkSize);

    checkSize(); // check from the start

});

Demo: http://jsfiddle.net/Guffa/EYeCV/


text:
Q: rendering JSON String as JSON Using JAXB within jersey Given a class like this:
@XmlRootElement
public class MyClass {
    private Boolean flag1;
    private String json;
    ...
}

Can I add an annotation that will cause the JSON to become part of the rendered JSON without being escaped as a string?
For example, if the object has flag1=true and json="{"a":5}" I want to get:
{"flag":true,"json":{"a":5}}

instead of:
{"flag":true,"json":"{\"a\":5}"}

A: You can write your own marshaller to do so.

A: You can use a Provider to change default behaviour of JSONJAXBContext. See http://jersey.java.net/nonav/documentation/latest/user-guide.html#d4e865
import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;

import com.sun.jersey.api.json.JSONConfiguration;
import com.sun.jersey.api.json.JSONJAXBContext;

@Provider
public class CustomWoodwingOutputJSONContextProvider implements ContextResolver<JAXBContext> {

private JAXBContext context;
private Class<?>[] types = { MyClass.class };

public CustomWoodwingOutputJSONContextProvider() throws JAXBException {
    this.context = new JSONJAXBContext(JSONConfiguration.natural().build(), types);
}

public JAXBContext getContext(Class<?> objectType) {
    for (int i = 0; i < this.types.length; i++)
        if (this.types[i].equals(objectType))
            return context;

    return null;
}

}


text:
Q: find url in html using regex I know there's plenty of stuff about it online but I'm trying to overcome a specific problem I've not encountered anyone asking about it.
So I have this regex I built for searching urls inside href/src attributes:
\s(?:href|src)\s*=\s*(["']??)\s*([^"']+)(?:\s*\1)[^>]*>

Problem is that it's matching things like this as well:
var a="";
a += "<a  href=\""+d.y+"\">";

I've tried to come up with a solution on how not get these false positives but I couldn't really so I'm asking for help here.
Note that I'm not looking for parsing the dom in-order to do it, only regex

A: I ended up rewriting the regex making it to expect 0 or more attributes followed by the src/href attribute so false positives like the one in my questions won't count.
Here's my new regex:
\s(?:src|href)\s*=\s*(?:["']?\s*([^"'>]+)\s*["']?)(?:\s+[^"'>\s]+(?:\s*=\s*["']?[^"'>]*["']?)?)*\s*\/?>


text:
Q: SQL Server Pattern Matching string - regex I need to select all columns in a table where value should be in below format
DIGITS_STRING_DIGITS.STRING

eg:
(123_tre_345.txt)

I am new to SQL Server. Is there a way to write query to read like this?

A: In order to exploit the full potential of regular expressions in SQL server, you have to implement CLR procedures.
The LIKE statement provides some of the commonest regular expression features and, despite not being very elegant because of the missing quantifiers, it should be enough to handle this case:
SELECT Field
FROM Table
WHERE Field LIKE '[0-9][0-9][0-9][_][a-z][a-z][a-z][_][0-9][0-9][0-9].txt'


text:
Q: disable SSL certification verification in axios i have a problem when call API.That display
"Error: unable to get local issuer certificate"
After that i tried add httpsAgent below.
var agent = new https.Agent({
    rejectUnauthorized: false
});

instance.defaults.httpsAgent = agent

i run this code. but display error "Agent option must be an Agent-like object, undefined, or false."
How it can solve this problem?

A: That's a Node v.8 known bug. You must to upgrade the Node.js version you are currently using. I would always recommend you to always update to the latest LTS version if possible.
Reference of the bug here.


text:
Q: How to add Object of JSON to an API Call I have x number of Objects in an array which are created dynamically.
I want to save those Object seperately by sending it through an API.
Issue is there can be x number of Objects.
What would be the best way to write a loop to read attribute name and its attribute value and hit the api,then read the second attribute and its values and hit the api.
So basically at one time the api will save only one object.
i.e
{
        "attributeName": "s1",
        "attributeValues": [
          "a",
          "b"
        ]
      }

My JSON Object looks like this:
[
  {
    "attributeName": "s1",
    "attributeValues": [
      "a",
      "b"
    ]
  },
  {
    "attributeName": "s2",
    "attributeValues": [
      "c",
      "d"
    ]
  },
  {
    "attributeName": "d1",
    "attributeValues": [
      "p",
      "q"
    ]
  },
  {
    "attributeName": "d2",
    "attributeValues": [
      "r",
      "s"
    ]
  },
  {
    "attributeName": "",
    "attributeValues": [
      ""
    ]
  },
  {
    "attributeName": "d2",
    "attributeValues": [
      "r",
      "s"
    ]
  }
]

I want to pick attribute name and its value and then send it to an API.
Alternatively say, I save the whole JSON to API,then how can I filter out individual Object if I don't know attribute name beforehand. What other approach can be there to get list of attribute names.

A: Check the frequency of data. If there is too much data on FrontEnd, then better to send in the chunk. Else can accumulate on FE and then send.
async function sendAll(data) {
  let results = [];
  for (let index = 0; index < data.length; index++) {
    const result = await axios.post('url', data[index].attributeValues);
    results.push(result);
  }
}

Sample with fake mock api.

// function* dataLake(data) {
//   for (let item of data) yield item;
// }
const getDataFake = data => {
  return new Promise(r => {
    setTimeout(() => {
      r(data);
    }, 100);
  });
};

async function sendAll(data) {
  let results = [];
  for (let index = 0; index < data.length; index++) {
    const result = await getDataFake(data[index].attributeValues);
    results.push(result);
  }
  return results;
}

const data = [
  {
    attributeName: "s1",
    attributeValues: ["a", "b"]
  },
  {
    attributeName: "s2",
    attributeValues: ["c", "d"]
  },
  {
    attributeName: "d1",
    attributeValues: ["p", "q"]
  },
  {
    attributeName: "d2",
    attributeValues: ["r", "s"]
  },
  {
    attributeName: "",
    attributeValues: [""]
  },
  {
    attributeName: "d2",
    attributeValues: ["r", "s"]
  }
];
sendAll(data).then(console.log)

A: if you want json in following format
[
  {'s1':['a','b']},
  {'s2':['c','d']},
  {'d1':['p','q']},
  {'d2':['r','s']},
  {'':['']},
  {'d2':['r','s']}
]

then you can have api call for individual child, or send the entire array.

var arr = [
  {
    "attributeName": "s1",
    "attributeValues": [
      "a",
      "b"
    ]
  },
  {
    "attributeName": "s2",
    "attributeValues": [
      "c",
      "d"
    ]
  },
  {
    "attributeName": "d1",
    "attributeValues": [
      "p",
      "q"
    ]
  },
  {
    "attributeName": "d2",
    "attributeValues": [
      "r",
      "s"
    ]
  },
  {
    "attributeName": "",
    "attributeValues": [
      ""
    ]
  },
  {
    "attributeName": "d2",
    "attributeValues": [
      "r",
      "s"
    ]
  }
];

var obj = arr.map((o1) => {
  var o = {};
  o[o1.attributeName] = o1.attributeValues;
  return o;
});

console.log(JSON.stringify(obj));


text:
Q: NodeJs,ExpressJS Running functions in background im asking this question because i dont know what to look for right now and my googling wasnt great so far.
I am making nodejs,express,sql app that scrape website. It takes 30 to 120 seconds to scrape whole category. How to make that function run in the background without blocking website. Frontend template engine is eJS. If its not possible to do with eJS which framework,library should i use then? I imagine it work like that

*

*User go to /scrape

*Choose category and send to server by clicking button

*Some container on /scrape gets greyed out with circle rotating or
other % or smth

*User can freely leave /scrape and click around webiste or just stay
on /scrape waiting for result

*When user cames back to /scrape the results are there or when he
stayed results shows up with or without reloading the page

Getting full respond to these questions will be very helpfull. But just keywords for me to look up also are very helpfull
Sorry for bad english

A: For your case here you could use redis, or just store the data you scrape on an data structrue that you like (in my opinion, because of the category, hashmaps (js objects) are the best here) directly in nodejs. The process would then look like this:

*

*User goes to /scrape and selects a category

*Backend checks if that category was already scraped (e.g. checks for the data in the hashmap with the category name as key)

*If the data exists (just check if the key is defined), then send the data to the user, else (if the data isn't stored, e.g. key == undefined), send the user a message that the data is beign scraped and just run the scrape funtion in the backround. The scrape function than scrapes the data, and if it is done, it pushes the data with the category key to the hashmap. To avoid the same categorys beign scraped at the same time, you could add a "pending" property to the hashmap. So if the user accesses the /scrape route, you check in the hashmap if the category key exsists, if yes and pending is false, send data, if yes and pending is true, send wait alert, if the key doesn't exists, start the scrape function and send a wait alter.

Additionally, to make the whole thing "live", you could use socket.io (https://socket.io/) to implement websockets. You could then send the scraped data to the user without the user having to reload the page to check if the scrape process is done.
I made a little exmaple, that doesn't implement scraping, but should make the whole logic here a little bit easier to understand. I also added some explenation to the code in form of comments.
const express = require("express");
const app = express()

// the data hashmap
const data = {};

// scrape function
const scrape = async (id) => {
  // set pending to true to prevent multiple scraped on same category
  data[id] = { pending: true, data: {} }
  // this would be your scrape functio, I used a promise here that
  // resolves after 5 seconds with an random number just for
  // simplicity
  const a = await new Promise((res, rej) => {
    setTimeout(() => { res(Math.floor(Math.random()*1000)) }, 5000)
  })

  // if the data was scraped, set pending to false and add the data
  data[id].pending = false;
  data[id].data = { id: a }
}

// "scrape" route
app.get("/:id", async (req, res) => {
  const { id } = req.params; // if would represent category

  // check if id (category) is not in hashmap, if not, then
  // start the scrape process and send a wait alert
  if (data[id] == undefined) {
    scrape(id);
    res.send("scraping...")

  // if the data is already beign scraped, send a wait alert
  // the pending property prvents that multiple people trigger
  // the scrape of the same category
  } else if (data[id].pending == true) {
    res.send("still scraping...")

  // lastly, if the data is defined, and is not pending, then
  // you could just send it
  } else {
    res.send(data[id].data)
  }
})

// to test this, go to the root with any id, could be string, number,
// whatever (e.g. /1337 or /helloworld), wait for 5 seceonds (or
// leave and come back after 5 seconds), refresh the page and you can
// see the random number. If you now go to an other route (e.g /test)
// and go back to the last one, you still can see the data, if you again
// wait for 5 seconds and then go back to /test, you can see the data.
// You can also open multiple tabs at the same time, which means the
// scraping is asynchronous, so you don't have to wait for the
// one category to be scraped to scrape the next

app.listen(5000)


text:
Q: Why aren't my reactive values initialised in the server function unique to each session? I'm deploying my app to shinyapps and I'm noticing some strange behaviour when I have multiple windows open. I have rendered a datatable and when I update the filters on a window, my table only updates on the last window that was opened.
I have moved my reactive values to be loaded in the server function after reading the scoping documentation.
app.R
source("helpers/load_data.R")

server <- function(input, output, session) {

source("helpers/load_session_data.R")

output$risk_table <- renderDataTable({
DT::datatable(riskData$data
              rownames = FALSE)
})

observeEvent(input$get_filtered_data, {
    # UpdateTable function takes my table_csv and filters by the date, and updates the riskData reactive value
    UpdateTable(table, input$date)
}

UpdateTable <- function(table, date) {
#... filter stuff
riskData$data <- filtered_table
}
}

load_session_data.R
#table is a data.frame loaded globally outside of the ui and server functions.
riskData <- reactiveValues(data = table_csv)

I thought that loading my reactive values in the server function meant that each session would have it's own reactive values? I want to be able to filter a table independently in different sessions.

A: You need to do two things
1) Set local=T during source call
source("helpers/load_data.R", local=T)
source("helpers/load_session_data.R", local=T)

"If you use the default value of local = FALSE, then the file will be sourced in the global environment."
Source
2) Put your source calls under the server function, otherwise even when enabling local=T the call will be shared across sessions
server <- function(input, output, session) {
source("helpers/load_data.R", local=T)
source("helpers/load_session_data.R", local=
...
}

A really good example in the shiny docs.. (Code can be found here)

# Objects in this file are shared across all sessions in the same R
# process
source('all_sessions.R', local = TRUE)

server <- function(input, output, session) {
  # Objects in this file are defined in each session
  source('each_session.R', local = TRUE)

  output$text <- renderText({
    # Objects in this file are defined each time this function is called
    source('each_call.R', local = TRUE)

    # ...
  })
}


text:
Q: What is the character code for enter? Consider this piece of code:
http://jsfiddle.net/YttKb/
I want my javascript to add a new line of text. I am using utf-8 coding. What character I need to insert to make a new line? Obviously \n doesn't create new line of text(creates only new line break). While \n\n creates a new line.
EDIT:
I have updated the fiddle. If you push enter manually at the end of the first line it does not create a new line as desired even though there is a line break(\n)

A: It's a bit platform-specific. It'll usually be \n or \r\n.
Of course, if you're talking about HTML, none of those will make a difference because in HTML (unless you're dealing with pre formatting, either the pre element or anything with the various pre-like values for white-space in their styles), whitespace is just a space. You'd need to use an element to break things up vertically (
, or something more appropriate to what you're doing).
Looking at your fiddle, you're dealing with HTML, so \n, \r\n, etc. are irrelevant. Here's an updated one doing this:
$("#test").append("
And hello from script");

Fiddle
...but
 is usually a last resort. There's usually something more semantically-appropriate you can do.


text:
Q: give node_exporter container access to network statistics from the host I would like to use prometheus's node_exporter in a container, but also have access to the host network's statistics.
As I'm using prometheus and the other modules such as alertmanager or mysql-exporter also in containers, I don't want to simply use the host network, because then I wouldn't be able to easily connect prometheus to the node-exporter in a consistent way, given that prometheus is also deployed as a container. I'd like to use the docker logic (identifying services by names).
This is the relevant part of the docker-compose:
             node_exporter:
                build: "/root/prometheus-stack/node_exporter"
                image: node_exporter:v0.18.1
                volumes:
                  - /proc:/host/proc:ro
                  - /sys:/host/sys:ro
                  - /:/rootfs:ro
                command:
                    - '--log.level=debug'
                    - '--path.procfs=/host/proc'
                    - '--path.sysfs=/host/sys'
                    - '--collector.filesystem.ignored-mount-points'
                    - '^/(sys|proc|dev|host|etc|rootfs/var/lib/docker/containers|rootfs/var/lib/docker/overlay2|rootfs/run/docker/netns|rootfs/var/lib/docker/aufs)($$|/)'
                networks:
                  - back-tier
                restart: always

As you can see I'm mounting the /proc pseudo file system, but unfortunately the statistics that I see are confined to the ones of the container, not the ones of the host. So I'll always going to see eth0, for instance, which is the interface of the container as seen from inside.
Is there any way I could get around this so that I have a fully containerised prometheus stack?
The other solution is cadvisor, which uses docker's socket, and I through that I can get network statistics for the server's main network interface, for instance. But that's not really nice.
On the server I also have containerised reverse-proxies, so it would make it even harder to install prometheus and its modules directly on the host.
So any ideas how I can smoothly give access to node-exporter to the host's network statistics?
Thank you!


text:
Q: What exactly do delta method estimates of moments for $1/\bar X_n$, $\bar X_n\sim\mathcal N(\mu,\sigma^2/n)$ approximate? (not as simple as you think) Let me start with the excerpt out of Casella & Berger's Statistical Inference (2nd edition, pg. 470) that inspired this question.

Definition 10.1.7 For an estimator $T_n$, if $\lim_{n\to\infty}k_n\mathrm{Var}T_n=\tau^2<\infty$, where $\{k_n\}$ is a sequence of constants, then $\tau^2$ is called the limiting variance or limit of the variances.
Example 10.1.8 (Limiting variances) For the mean $\bar X_n$ of $n$ iid normal observations with $\mathrm EX=\mu$ and $\mathrm{Var}\,X=\sigma^2$, if we take $T_n=\bar X_n$, then $\lim n\mathrm{Var}\bar X_n=\sigma^2$ is the limiting variance of $T_n$.
But a troubling thing happens if, for example, we are instead interested in estimating $1/\mu$ using $1/\bar X_n$. If we now take $T_n=1/\bar X_n$, we find that the variance is $\mathrm{Var}\,T_n=\infty$, so the limit of the variances is infinity. But recall Example 5.5.23, where we said that the "approximate" mean and variance of $1/\bar X_n$ are
$$
\mathrm E\left(\frac{1}{\bar X_n}\right)\approx\frac{1}{\mu},
$$
$$
\mathrm{Var}\left(\frac{1}{\bar X_n}\right)\approx\left(\frac{1}{\mu}\right)^4\mathrm{Var}\bar X_n,
$$
and thus by this second calculation the variance is $\mathrm{Var}\,T_n\approx\frac{\sigma^2}{n\mu^4}<\infty$.
This example points out the problems of using the limit of the variances as a large sample measure. Of course the exact finite sample variance of $1/\bar X$ is $\infty$. However, if $\mu\neq 0$, the region where $1/\bar X$ gets very large has probability going to $0$. So the second approximation in Example 10.1.8 is more realistic (as well as being much more useful). It is this second approach to calculating large sample variances that we adopt.

Now, I disagree that $\mathrm{Var}\left(1/\bar X_n\right)=\infty$. While I do agree that $\mathrm E\left(1/\bar X_n^2\right)=\infty$, the first negative moment $\mathrm E\left(1/\bar X_n\right)$ is clearly undefined and thus so is the variance. Given that both $\mathrm E\left(1/\bar X_n\right)$ and $\mathrm{Var}\left(1/\bar X_n\right)$ are strictly undefined, I have the following question.

Question: What exactly do the delta method approximations for $\mathrm E\left(1/\bar X_n\right)$ and $\mathrm{Var}\left(1/\bar X_n\right)$ approximate if the moments of $1/\bar X_n$ are undefined?

My thoughts:
Let $\bar X_n\sim\mathcal N(\mu,\sigma^2/n)$ and define for $t\in\Bbb R$
$$
\mathcal H[f_{\bar X_n}](t)=\lim_{\epsilon\to 0^+}\int_{\Bbb R\setminus(t-\epsilon,t+\epsilon)}\frac{f_{\bar X_n}(x)}{x-t}\,\mathrm dx,
$$
which is the Hilbert transform of the density function for $\bar X_n$. Since the Hilbert transform commutes with derivatives, i.e.
$$
\mathcal H[\partial_t^k u]=\partial_t^k\mathcal H[u],
$$
the expression $\mathcal H[f_{\bar X_n}](t)$ represents a sort of generating function for the negative moments of $\bar X_n$, which do not exist in the traditional sense.  We define
$$
\mathrm E\bar X_n^{-k}:=\frac{1}{(k-1)!}\partial_t^{k-1}\mathcal H[f_{\bar X_n}](t)\Big|_{t=0}.
$$
For our particular example
$$
\mathcal H[f_{\bar X_n}](t)=\frac{\sqrt 2}{\sigma/\sqrt n}\mathcal D\left(\frac{\mu-t}{\sqrt 2\,\sigma/\sqrt n}\right),
$$
with $\mathcal{D}(z)=e^{-z^{2}}\int_{0}^{z}e^{t^{2}}\,\mathrm{d}t$ being Dawson's integral; thus
$$
\mathrm E\bar X_n^{-1}=\frac{\sqrt 2}{\sigma/\sqrt n}\mathcal D\left(\frac{\mu}{\sqrt 2\,\sigma/\sqrt n}\right)
$$
and
$$
\mathrm{Var}\bar X_n^{-1}:=\mathrm E\bar X_n^{-2}-(\mathrm E\bar X_n^{-1})^2
$$
with
$$
\mathrm E\bar X_n^{-2}=\frac{\sqrt 2\,\mu}{(\sigma/\sqrt n)^3}\mathcal D\left(\frac{\mu}{\sqrt 2\,\sigma/\sqrt n}\right)-\frac{1}{(\sigma/\sqrt n)^2}.
$$
Now, the Dawson integral admits the following asymptotic expansion for $x\to\infty$
$$
\mathcal D(x/\sqrt 2)\sim\frac{1}{\sqrt 2\,x}\sum_{k=0}^\infty (2k-1)!!\frac{1}{x^{2k}},
$$
so letting $n\to\infty$ we have for the first moment
$$
\begin{align}
\mathrm E\bar X_n^{-1}
&\sim\frac{1}{\mu}\sum_{k=0}^\infty (2k-1)!!\left(\frac{\sigma/\sqrt n}{\mu}\right)^{2 k}\\
&=\frac{1}{\mu}+\mathcal O\left(\frac{1}{n}\right),
\end{align}
$$
which is the first-order delta method approximation for the mean of $1/\bar X_n$. Likewise, for the second moment we find
$$
\mathrm E\bar X_n^{-2}
\sim\frac{1}{(\sigma/\sqrt n)^2}\sum_{k=1}^\infty (2k-1)!!\left(\frac{\sigma/\sqrt n}{\mu}\right)^{2 k},
$$
which upon combining with the expansion for $\mathrm E\bar X_n^{-1}$ gives the asymptotic approximation for $n\to\infty$
$$
\begin{align}
\mathrm{Var}\bar X_n^{-1}
&=\frac{1}{\mu^2}+3\frac{(\sigma/\sqrt n)^2}{\mu^4}+\mathcal O\left(\frac{1}{n^2}\right)-\left(\frac{1}{\mu^2}+2\frac{(\sigma/\sqrt n)^2}{\mu^4}+\mathcal O\left(\frac{1}{n^2}\right)\right)\\
&=\frac{(\sigma/\sqrt n)^2}{\mu^4}+\mathcal O\left(\frac{1}{n^2}\right),
\end{align}
$$
which is the first-order delta method approximation for the variance of $1/\bar X_n$.
So in this context, the delta method moment "approximations" are equal to the first term in the asymptotic expansions for our exact generalized moments in the case $n\to\infty$.

To ask my question from a different perspective: If we are to assign any value to the moments of $1/\bar X_n$, should we instead assign these generalized values for $E\bar X_n^{-k}$ with the delta method moment estimates simply being an approximation of these "exact" moments?

Indeed, the generalized moments seem to provide a more accurate picture of the moments for $1/\bar X_n$ whenever $|\mu/(\sigma/\sqrt n)|\to\infty$ ($n$ does not necessarily have to be large), which implies $f_{\bar X_n}(0)$ is vanishingly small.
Consider the case $\mu=6$, $\sigma=1$, and $n=1$ so that $\bar X_n=X\sim\mathcal N(\mu,\sigma^2)$. I simulated $X$ in MATLAB with the following code:
mu = 6;
sigma = 1;
Y = 1./normrnd(mu,sigma,1e8,1);

EY = sqrt(2)/sigma*dawson(mu/(sqrt(2)*sigma));
[EY 1/mu mean(Y)]

EY2 = sqrt(2)*mu/sigma^3*dawson(mu/(sqrt(2)*sigma))-1/sigma^2;
[EY2 1/mu^2 mean(Y.^2)]

EY3 = (sqrt(2)*(mu^2-sigma^2)*dawson(mu/(sqrt(2)*sigma))-mu*sigma)/(2*sigma^5);
[EY3 1/mu^3 mean(Y.^3)]

VarY = EY2-(EY)^2;
[VarY sigma^2/mu^4 var(Y)]

fY = @(y) normpdf(1./y,mu,sigma)./y.^2;
ax = linspace(0.05,0.35,512);

figure
hold on;
histogram(Y,linspace(0.05,0.35,40),'Normalization','pdf')
plot(ax,fY(ax),'Color',[0 0 0],'LineWidth',2)

Here are the results showing that the generalized moments more accurately reflect the sample statistics.
$$
\begin{array}{cccc}
 &\text{generalized} &\text{delta} &\text{sample}\\
\mathrm EX^{-1} &0.1718 &0.1667 &0.1718 \\
\mathrm EX^{-2} &0.0305 &0.0278 &0.0305 \\
\mathrm EX^{-3} &0.0056 &0.0046 &0.0056 \\
\mathrm{Var}X^{-1} &0.0010 &0.0008 &0.0010
\end{array}
$$

A: Too long for comment.
The asymptotic variances are more useful than the variances because some estimators do not have variance for any finite sample and yet the do have asymptotic variance. Consider $Y_1$ and $Y_2$ two independent binomial distributions. The odds ratio is $\theta = \dfrac{\frac{P(Y_2=1)}{P(Y_2=0)}}{\frac{P(Y_1=1)}{P(Y_1=0)}}.$ Write now a (2,2) table of observations as $(n_{ij})$ with $i=1,2,$ denoting $Y_1$ or $Y_2,$ and $j = 1$ denotes failure, while $j = 2$ denotes success. The most natural estimate is $\hat\theta = \dfrac{n_{11}n_{22}}{n_{12}n_{21}}$ which takes the values $\infty$ if $n_{12}n_{21} = 0,$ so its variance does not exists. However, for very large samples, $n_{12}n_{21} = 0$ has an exponentially small probability and this event will not occur in practice and so for all intents and purposes we should be able to calculate the variance. In this sense, the sample variance (not as defined by Casella and Berger but by the "delta method") is the one that we use in practice. The odds ratio can also be written as $\theta = \dfrac{P(Y_2 = 1)}{P(Y_1 = 1)} \dfrac{P(Y_1 = 0)}{P(Y_2 = 0)}.$ When $Y_1$ and $Y_2$ model something rare (so that "success" is a rare event, as in effectiveness of new treatment and we are comparing two treatments, or number of people who use drugs and we are comparing two social factors or number of car accidents than result in death comparing seat-bealt use vs not) an estimator of interest is the relative risk $r = \dfrac{P(Y_2 = 1)}{P(Y_1 = 1)}$ which cannot be estimated usually due to ethical or cost contraints (it can be estimated in clinical trials but not in the social-factor/drug-use scenario or the fatal-accident/seat-belt use), since the probabilty of "failure" is rare for both $Y_1$ and $Y_2$ the odds ratio is very close to the relative risk since $\dfrac{P(Y_1 = 0)}{P(Y_2 = 0)} \approx 1$ and in practice it is not rare that this fraction is $\in [0.97, 1.3].$ (By the way, it can be shown that the odds ratio is an estimator that is invariant under changes of scales, swaping of columns and or of rows, so it is really invariant under retrospective or prospective analyses.)


text:
Q: Save xamlx on runtime I am working on a winform project which actually receive a BPMN file and translate it to a workflow .xaml file so it acts like a BPMN to Workflow Converter. So this conversion is done entirely programmatically and no designer is used. The activities should be assigned on run time so nothing is predifined. For example a bpmn file with a Start event connected to an exclusive gateway is implemented my application receive it and translate it to a start event in workflow connected to an IF Activity etc. And finally the workflow is saved as a xaml file. Thus nothing is predifined and my application design the workflow accoirding to the specifications of the bpmn file that receives. My problem is instead of a .xaml file i want .xamlx file because those workflows i will expose them from my server. I couldnt find any examples in the internet. Any ideas or approaches?

A: You could try using BPMN2WF which is a prototype application for transforming BPMN models into Workflow Foundation (WF) code. For more information visit http://bpmn2wf.codeplex.com/


text:
Q: How to get data from a Class class Beers:

    def __init__(beer, name):
        beer.name = name

    def beer_data(beer, type, price, size, packs):
        beer.type = type
        beer.price = price
        beer.size = size
        beer.packs = packs

    def beer_additional_data(beer):
        beer.data_List = []
        beer.data_List += beer.name, beer.size*beer.packs

hjnakken = Beers('Hjnakken')
bidwsr = Beers('Bidwsr')
cirona = Beers('Cirona')

hjnakken.beer_data('Pale lager', 2.3, 6, 12)
bidwsr.beer_data('American lager', 2.0, 8, 10)
cirona.beer_data('Pale lager', 2.6, 8, 6)

hjnakken.beer_additional_data()
bidwsr.beer_additional_data()
cirona.beer_additional_data()

which_beer = input('Enter beer name: ')

How to do this (below) without an if statement? What is the pythonic way?
print(which_beer.data_List)

I want to get the XYZ.data_List after a user input.

*

*so find if input is valid (match with beer.name)

*print or work further with the XYZ.data_List


text:
Q: Dynamically generated list Could anyone give me an idee on how could I generate dynamically this piece od code:

<button type="button" class="btn btn-default btn-lg dropdown-toggle" data-toggle="dropdown" runat="server">
</button>

         Text nr 1
        <asp:Image ID="Image1" ImageUrl="myImg.png" runat="server" onclick="fct2()"/>

         Text nr 2
        <asp:Image ID="Image2" ImageUrl="myImg.png" runat="server" onclick="fct2()"/>

The main idea of this code is to have some kind of dropdown list looking control that would have a span with text, and an image on each row.
This is basicly how my control shoud look when it's clicked:
Text1        img1
Text2 img2
If a user clicks TextN i get an event for that click, and i can update the page based on selected item.
If a user clicks imgN then TextN and imgN would disappear from the list.


text:
Q: JFrog Artifactory is not connecting to postgresql in AWS eks after pod restart. We are using Postgresql as an external database Background: devops artifactory is deployed as a statefulset pod on AWS eks cluster through Helm chart. And the PV is pointing to EFS.
The below is the snippet from values.yaml
postgresql:
enabled: false
database:
type: "postgresql"
host: "xxxxxxx.rds.amazonaws.com"
port: 5432
user: "xxxxxx"
password: "xxxxx"
It was working fine. But when the pod got restarted the status is 3/4 and Running mode. When we tried to access JFrogArtifactory URL, its showing "no healthy upstream".
Error:
Here is the details: NAMESPACE NAME READY STATUS
devops-artifactory dfdp-devops-euc1-artifactory-artifactory-0 3/4 Running
When described the pod below error:
Type Reason Age From Message ---- ------ ---- ---- ------- Warning Unhealthy 4m27s (x4736 over 13h) kubelet, ip-10-80-114-124.eu-central-1.compute.internal Readiness probe failed: Connecting to 127.0.0.1:8081 (127.0.0.1:8081) HTTP/1.1 302 Found Location: /artifactory/ HTTP/1.1 500 Internal Server Error wget: server returned error: HTTP/1.1 500 Internal Server Error
Here is the logs of pod:
2020-04-21T18:04:19.018Z [jfac ] [ERROR] [1f656079c9208e40] [GenericDBPrivilegesVerifier:43] [ocalhost-startStop-1] - Could not determine sufficient privileges java.sql.SQLException: Table/View 'T1ACCESS' already exists in Schema 'APP'
2020-04-21T18:04:19.019Z [jfac ] [ERROR] [1f656079c9208e40] [.s.d.u.AccessJdbcHelperImpl:66] [ocalhost-startStop-1] - Could not initialize database: java.lang.RuntimeException: java.sql.SQLException: Table/View 'T1ACCESS' already exists in Schema 'APP'. at org.jfrog.storage.priviledges.GenericDBPrivilegesVerifier.isSufficientPrivileges(GenericDBPrivilegesVerifier.java:44)
2020-04-21T18:04:19.051Z [jfac ] [ERROR] [1f656079c9208e40] [o.s.b.SpringApplication:822 ] [ocalhost-startStop-1] - Application run failed org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.boot.autoconfigure.jersey.JerseyAutoConfiguration':
Options tried
1)Logged into the pod. Provided the db properties in $Artifactory_Home/var/etc/system.yaml related to Postegresql details
2)Manually restarted the artifactoryctl from $Artifactory_Home/app/bin
Now we are getting the below error
**Error **
2020-04-21T17:33:55.091Z [jfmd ] [INFO ] [73cdd58a85c6c861] [database_bearer.go:71 ] [main ] - Connecting to (db config: {postgresql user='xxxxxxxxxxxx' password='xxxxxxxxxx' dbname=artifactory host=xxxxxxxxxxxxxxx.rds.amazonaws.com port=5432 sslmode=disable}) [database]
Tomcat started.
artifactory@xxxxxxxxxxxxxxxx:/opt/jfrog/artifactory/app/bin$ 2020-04-21T17:33:55.141Z [jfmd ] [INFO ] [73cdd58a85c6c861] [migrator.go:62 ] [main ] - Applying 36 migrations files [database]
2020-04-21T17:33:55.143Z [jfmd ] [INFO ] [73cdd58a85c6c861] [application.go:73 ] [main ] - Metadata (jfmd) service initialization started. Version: 2.4.3 Revision: 20403900 PID: 9619 Home: /opt/jfrog/artifactory/var [app_initializer]
2020-04-21T17:33:55.145Z [jfmd ] [INFO ] [73cdd58a85c6c861] [server_bearer.go:153 ] [main ] - Got service_id from datastore: xxxxxxxxxxxxxxxxxxxxxxxxxxxx [ServerInit]
2020-04-21T17:33:55.336Z [jffe ] [INFO ] [ ] [ ] [main ] - frontend (jffe) service initialization started. Version: 1.4.1 Revision: 0.0.0 PID: 9425 Home: /opt/jfrog/artifactory
2020-04-21T17:33:56.900Z [jfrou] [INFO ] [3155325b3a2e8c70] [config_holder.go:107 ] [main ] - configuration update detected
2020-04-21T17:33:59.087Z [jfrou] [INFO ] [3155325b3a2e8c70] [join_executor.go:148 ] [main ] - Cluster join: Retry 5: Service registry ping failed, will retry. Error: Could not parse error from service registry, status code: 404, raw body: HTTP Status 404 – Not Foundh1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} h2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} h3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} body {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} b {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} p {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;} a {color:black;} a.name {color:black;} .line {height:1px;background-color:#525D76;border:none;}

A: Assuming you are using latest helm (7.x Appversion ) charts , Artifactory uses internal postgresql (postgresql.enabled=true),which is enabled by default (for non production purposes)
For production deployments,

*

*Use an  external postgresql,(use --set postgresql.enabled=false) and

*Please set these values
Note: For faster responses for your issues , Feel free to raise issues directly here


text:
Q: CharacterData ignoring non escaped characters I'm using the following method to read in a line of text from an XML document via the web:
public static String getCharacterDataFromElement(Element e) {
    Node child = ((Node) e).getFirstChild();
    if (child instanceof CharacterData) {
        CharacterData cd = (CharacterData) child;
        return cd.getData();
    }
    return "";
}

It works fine, but if it comes across a character such as an ampersand which are not written like & etc it will then completely ignore that character and the rest of the line. What can I do to rectify this?

A: The only proper solution ist to correct the XML, so that the & is written as &, or the texts are wrapped in <![CDATA[ ... ]]>.
It's not actually XML unless you escape ampersands or use CDATA.

A: I suspect the talk of the input not being well-formed is a red herring. If the source document contains entity references then an element may contain multiple text node children, and your code is only reading the first of them. It needs to read them all.
(I think there are easier ways of getting the text content of a Node in DOM. But I'm not sure, I never use the DOM if I can avoid it because it makes everything so difficult. You're much better off with JDOM or XOM.)


text:
Q: Android In App Billing v3 Server Verification I have in Google in app billing set up in my app using the IabHelper classes from the trivialdrive sample app. I can successfully purchase items, and now I'm trying to implement server side verification.
I see in Security.java that there is a verifyPurchase method.
https://code.google.com/p/marketbilling/source/browse/v3/src/com/example/android/trivialdrivesample/util/Security.java
I want to replace that with a call to my server that will do the verification on the server vs on the client device. I have my endpoint set up and working.
I'm stuck at how to call my endpoint and have verifyPurchase return true or false based on the response. I currently use Volley which makes async calls. I can get my endpoint's response in Volley's success callback. But since that network call is async, I'm not sure how to return true or false in verifyPurchase based on that call's response. I'm a java n00b :)

A: Create an interface call that in response of the async call of volley use that. Implement that interface in that class where you need your verifyPurchase() return. Override that interface and process the response.


text:
Q: Javascript random generator I created a random number generator in javascript whose values are in an array.
The code is that one

function GetValue()
{
    var names= new Array(1,2,3,4,5);
    var random = names[Math.floor(Math.random() * names.length)];
    //alert(random);
    document.getElementById("message").innerHTML=random;
}

number generator

<form class="form">

        <input type="button" id="btnSearch" value="Generatore" onclick="GetValue();" class="btn btn-default" />

</form>

I'd like to know if it is possible to give a different text in the p tag according to the number generated by the button.
Thanks very much and sorry if there is any english error

A: Just give the element an identifier, select it in your code and change the value according to your 'random' value:

function GetValue() {
    var names = [1,2,3,4,5];
    var random = names[Math.floor(Math.random() * names.length)];
    var messageContainer = document.getElementById("message");
    var headline = document.getElementById("headline");

    if (random <= 2) {
        headline.innerHTML = 'Hamburger (' + random + ')';
    } else {
        headline.innerHTML = 'Fish (' + random + ')';
    }
}

number generator

<form class="form">

        <input type="button" id="btnSearch" value="Generatore" onclick="GetValue();" class="btn btn-default"/>

</form>

A: I'm not sure of what you want, but If you want to randomly select from a string:
function GetValue(){
  var names= new Array(1,2,3,4,5);
  var texts = ["foo", "bar", "baz", "foo2", "barbaz"];
  var random = names[Math.floor(Math.random() * names.length)];
  //alert(random);
  document.getElementById("message").innerHTML = texts[random - 1];
};

here is the fiddle: https://jsfiddle.net/x2zkph3x/

A: If your question is "How to display a randomly selected text when clicking a button", this is the answer:

var generator = document.getElementById('generator'),
    message = document.getElementById('message'),
    strings = ['first', 'second', 'third'];

generator.addEventListener('click', function(event) {
  message.textContent = strings[Math.random() * strings.length | 0];
});
<input type="button" id="generator" value="Generate">


text:
Q: When would I get online flag as true for a user? I want to know when would I get the "online" flag as true for a user? I am logged in to my soundcloud account through the browser as well as through the mobile app, but I still get online flag as false. I am using the API endpoint http://api.soundcloud.com/users/{id}.json?client_id=YOUR_CLIENT_ID to get the user details.

A: I believe this flag is no longer used due to it having inaccurate information.  See the post Where did 'Who's Online' go? from SoundCloud Help.


text:
Q: How to set Java HOME for multiple Java versions on Mac I use Java 8 and Java 17 versions in several projects and I want to set default Java HOME as Java 8. For this purpose, I add .zshenv file to my user folder and make its content like this:
# Java 8
export PATH=/usr/local/opt/openjdk@8/bin:$PATH
# sudo ln -sfn /usr/local/opt/openjdk@8/libexec/openjdk.jdk /Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk

# Java 17
# export PATH=/usr/local/opt/openjdk@17/bin:$PATH

# Maven
export PATH=~/apache-maven-3.8.6/bin:$PATH

export JAVA_HOME=$(/usr/libexec/java_home -v1.8)
# export JAVA_HOME=$(/usr/libexec/java_home -v 17)

export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8
export LANGUAGE=en_US.UTF-8

However, I get some problems related to not being able to set Java Home properly. So, could you please clarify me on how can I set Java paths and set Java8 default path using .zsh way8 ?
I use MacOS Monterey.


text:
Q: Randomly place images around the text programatically Here in the MWE:
\documentclass[table]{standalone}
\usepackage{lipsum, graphicx, polyglossia, enumitem, amssymb, pifont, booktabs, cancel, animate, ulem, ragged2e}
\usepackage[most]{tcolorbox}
\graphicspath{ {/home/sandip/Downloads/} {images/} }
\linespread{2}

\newtcolorbox{highlightbox}{%
  enhanced,
  colframe=black,
  boxrule=2mm,
  coltext=white,
  colback=black}

\newtcolorbox{mybox}[2][]{%
  enhanced,
  before upper=\setlength{\parskip}{\bigskipamount},
  colframe=black,
  boxrule=2mm,
  bottomrule=8mm,
  colbacktitle=black,
  fonttitle=\bfseries\centering,
  coltitle=white,
  colback=yellow!10!white,
  coltext=black,
  watermark zoom=1,
  watermark color=black,
  watermark opacity=.05,
  clip watermark,
  watermark text={\rotatebox{65}{Watermark}},
  title=#2,#1}

\newcommand{\xxbody}{
  \lipsum[2,4]
}

\newcommand{\xxheading}{%
  Heading
}

\begin{document}

\begin{mybox}{\LARGE \xxheading{}}

  \xxbody{}

\end{mybox}

\end{document}

In folder ./images, I have several image files.
I want to place all of them around the text randomly with random rotations. But at the same time, I do not want them cluttered around together.
The images are tiny icons and placing them around the text randomly improves the visual appeal of the document, at least, in my view :)
How do I do that?
The question here and here have something similar. But there is no text involved.

A: The following places up to 10 pictures (random how many) per page on random spots. The pictures are randomly pulled from a list of valid pictures.
New code
Places anywhere in the margin, no collision protection (but depending on the size of your images very unlikely, just change the seed).
\documentclass[]{article}

\usepackage[]{graphicx}

\ExplSyntaxOn
\sys_gset_rand_seed:n { \int_from_alph:n { desh } + \int_from_alph:n { mukh } }

% list of image files here
\seq_const_from_clist:Nn \c_deshmukh_pictures_seq
  {
    example-image,
    example-image-a,
    example-image-b,
    example-image-c,
    example-image-duck
  }
\int_const:Nn \c_deshmukh_max_pictures_per_page_int { 10 }

\dim_new:N \l__deshmukh_x_dim
\dim_new:N \l__deshmukh_y_dim

\cs_new_protected:Npn \__deshmukh_put_picture:
  {
    \put
      ( \l__deshmukh_x_dim , -\l__deshmukh_y_dim )
      {
        \includegraphics
          [ angle=\fp_eval:n{360*rand()}, width=10pt ]
          { \seq_rand_item:N \c_deshmukh_pictures_seq }
      }
  }
\cs_new_protected:Npn \__deshmukh_set_rand_left:
  {
    \dim_set:Nn \l__deshmukh_x_dim
      { \fp_eval:n { rand() * (1in + \hoffset + \oddsidemargin) } pt }
    \dim_set:Nn \l__deshmukh_y_dim
      { \fp_eval:n { rand() } \paperheight }
  }
\cs_new_protected:Npn \__deshmukh_set_rand_bottom:
  {
    \dim_set:Nn \l__deshmukh_x_dim
      { \fp_eval:n { rand() * \textwidth + 1in + \hoffset + \oddsidemargin } pt }
    \dim_set:Nn \l__deshmukh_y_dim
      {
        \fp_eval:n
          {
            rand() *
            (
              \paperheight
                - 1in - \voffset - \topmargin - \headheight - \headsep
                - \textheight - \footskip
            )
            + 1in + \voffset + \topmargin + \headheight + \headsep
            + \textheight + \footskip
          } pt
      }
  }
\cs_new_protected:Npn \__deshmukh_set_rand_right:
  {
    \dim_set:Nn \l__deshmukh_x_dim
      {
        \fp_eval:n
          {
            rand() *
            ( \paperwidth - 1in - \hoffset - \oddsidemargin - \textwidth )
            + 1in + \hoffset + \oddsidemargin + \textwidth
          } pt
      }
    \dim_set:Nn \l__deshmukh_y_dim { \fp_eval:n { rand() } \paperheight }
  }
\cs_new_protected:Npn \__deshmukh_set_rand_top:
  {
    \dim_set:Nn \l__deshmukh_x_dim
      { \fp_eval:n { rand() * \textwidth + 1in + \hoffset + \oddsidemargin } pt }
    \dim_set:Nn \l__deshmukh_y_dim
      { \fp_eval:n { rand() * (1in + \voffset + \topmargin) } pt }
  }

\AddToHook{shipout/background}
  {
    \int_step_inline:nn
      { \int_rand:n { \c_deshmukh_max_pictures_per_page_int } }
      {
        \int_case:nn { \int_rand:n { 4 } }
          {
            { 1 } { \__deshmukh_set_rand_left: }
            { 2 } { \__deshmukh_set_rand_bottom: }
            { 3 } { \__deshmukh_set_rand_right: }
            { 4 } { \__deshmukh_set_rand_top: }
          }
        \__deshmukh_put_picture:
      }
  }
\ExplSyntaxOff

\usepackage{duckuments}% <- dummy content, also random example-image-duck

\begin{document}
\duckument
\end{document}

Old code
Places anywhere on the page.
\documentclass[]{article}

\usepackage[]{graphicx}

\ExplSyntaxOn
% list of image files here
\seq_const_from_clist:Nn \c_deshmukh_pictures_seq
  {
    example-image,
    example-image-a,
    example-image-b,
    example-image-c,
    example-image-duck
  }
\int_const:Nn \c_deshmukh_max_pictures_per_page_int { 10 }
\AddToHook{shipout/background}
  {
    \int_step_inline:nn
      { \int_rand:n { \c_deshmukh_max_pictures_per_page_int } }
      {
        \put
          ( {\fp_eval:n{rand()}\paperwidth}, {-\fp_eval:n{rand()}\paperheight} )
          { \includegraphics { \seq_rand_item:N \c_deshmukh_pictures_seq } }
      }
  }
\ExplSyntaxOff

\usepackage{duckuments}% <- dummy context, also random example-image-duck

\begin{document}
\duckument
\end{document}


text:
Q: Will i get performance improvement in migration lucene index from v3 to latest v7 Our application is indexing books. When we index, the size on disk is around 1GB. When we search, it is taking around 12-18 seconds.
This application was built with Lucene 3.x.x. Will I get a performance improvement if I migrate to Lucene 7.x.x?
I am asking because the application is very big, and separating this piece of functionality is a very big task, so wanted help from experienced people.
I also see many classes which are used in the code that are not available in Lucene-7. How do I migrate? Do I need to do the incremental migration like v3 -> v4 -> v5 -> v6 ->v7?

A: Would I see a performance improvement moving to Lucene 7.0
Impossible to say with certainty, but it's likely you would. There have been considerable performance improvements since Lucene 3. You can browse the Lucene benchmarks, where, scrolling back, you will see improvements on most of them since v3.
Whether it would be enough of an improvement is another question. The first place you should look, is if you are using queries that are generally poor performers, and how you could do that better. If you are using a lot of leading wildcard queries, a newer version of Lucene isn't going to magically save you from yourself.
How do I migrate?
There is a lot that's changed in the 7 years since Lucene 3. Getting a reader or writer has changed, not even the Documents and Fields work quite the same!  Best thing to do is acquaint yourself with the Migration Guides, which calls out the changes that are likely to break your code, and what to do about them:

*

*4.0 Migration Guide

*5.0 Migration Guide

*6.0 Migration Guide

*7.0 Migration Guide
Do I need to do the incremental migration
With this many versions to go through, I would rather reindex if possible, but if that's not an option, yes, you will need to upgrade your index one major version at a time. The command line IndexUpgrader tool is what you will need to do that, and it only upgrades from the last major version. So, yes, you will need to download lucene 4, run IndexUpgrader to get a 4.0 index, then repeat with Lucene 5, etc.


text:
Q: JS library that provides simple utilities for browsers and the nodejs environment? I'm looking for a javascript library that attempts to provide the same simple utilities in both the browser environment AND nodejs (iteration, mapping, maybe control-flow) so that code can more easily be re-used across server and client.  I know you can hack out parts of any JS library (YUI, jQuery, ...) and get them to work in both environments, I'm just wondering if it's already been done or standardized.
The closest I've seen is this: https://github.com/kof/sharedjs
But it's incomplete and has some odd stuff.  I'm wondering if there is something more polished before I fork and hack.

A: The underscore library was built to add more functional programming to jquery, things like mapping, and also templating.
Because it doesn't rely on the DOM (it leaves that to jquery) it functions well in node.

A: The RightJS  link library has a server build  link that has node.js in mind.
From the download page:

RightJS is also available as a server-side library. In this case it contains only the native JavaScript unit extensions and the Class, Observer, Options units along with all the non-DOM utility functions from the Util module.
Our server-side build follows the CommonJS principles and is ready for use with the node.js framework.

A: Node's GitHub wiki has a list of CommonJS-compatible modules which will run in Node and browsers.
Some of the other modules on that page may also run in a browser environment.  For example, the excellent DateJS works fine in Node.  (It is available as a NPM.)

A: Btw, RightJS is also available on NPM


text:
Q: Riak cluster backup 10 nodes to 6 nodes I'm wondering how we can backup a cluster of 10 nodes and restore on a cluster of 6 nodes. No matter the technique used for the backup (fsync, riakmanager, ...).
Any help you can give would be greatly appreciated.

A: I would recommend using the riak admin control panel. i am not sure if you are simply moving to 6 new servers or removing 4 current servers.
If you are removing 4 current servers use the control panel to remove the 4 servers and let it move the data over for you. Once your data is on 4 nodes you can take backups i would recommend taking xfs snapshots or stopping riak and backing up the file system you have riak data.
You are moving to 6 new nodes I would recommend adding 6 nodes to the current cluster letting them sync up and then removing the 10 old nodes. If the new nodes have xfs or LVM that would make snapshots very easy.


text:
Q: How to send a MMS with arduino GSM shield (v2) Hello Stackoverflow community!
I recently received my 'GSM Shield 2' ([url=http://arduino.org/products/arduino-gsm-shield-2]http://arduino.org/products/arduino-gsm-shield-2[/url]).
I've done some research concerning telecommunication and how it all works, but I'm still new at this so bear with me.
I'm using AT commands, not the GSM library.
I can send/receive sms/phone calls. Yet I'm having some trouble with MMS.
How do I exactly send one with a file? There is no SD-card, so I can't use the File Class from the SD-Library. How do I send my file data?
Any examples, pretty please?
Thank you!
AT MMS documentation: http://www.quectel.com/UploadImage/Downlad/Quectel_GSM_MMS_AT_Commands_Manual_V1.1.pdf


text:
Q: SELECT DISTINCT showing duplicate dates per customer email I am trying to retrieve information for the past ten months, but am having a couple of errors.  First, my query is getting data from as far back as 2013.  Secondly, I am seeing duplicates in my results based on the PolEffDate field, like this:
EntityID | PolEffDate | EMail | CustNo | Producer | BusinessPhone
abcde-12345-fghij-67890 | 2013-09-24 | somewhere@email.com | 31000 | Bob Builder | 123-456-7890
abcde-12345-fghij-67890 | 2013-12-01 | somewhere@email.com | 31000 | Bob Builder | 123-456-7890
abcde-12345-fghij-67890 | 2014-09-24 | somewhere@email.com | 31000 | Bob Builder | 123-456-7890

Here is my SQL Query:
SELECT DISTINCT
     CONVERT(VarChar(36), Customer.CustId) AS EntityID
     , BasicPolInfo.PolEffDate, Customer.EMail, Customer.CustNo
     , (isnull(Employee.Firstname + ' ','') + isnull(Employee.LastName,''))
     AS Producer, Employee.BusFullPhone
FROM
     Customer INNER JOIN BasicPolInfo ON Customer.CustId = BasicPolInfo.CustId INNER JOIN
    Transaction ON BasicPolInfo.PolId = Transaction.PolId INNER JOIN
    GeneralBranch ON Customer.GLBrnchCode = GeneralBranch.GLBrnchCode INNER JOIN
    GeneralDepartment ON Customer.GLDeptCode = GeneralDepartment.GLDeptCode INNER JOIN
    GeneralDivision ON Customer.GLDivCode = GeneralDivision.GLDivCode INNER JOIN
    Employee ON BasicPolInfo.ExecCode = Employee.EmpCode
WHERE
     BasicPolInfo.PolExpDate >= DATEADD(MONTH, -10,CONVERT(VARCHAR(11),GETDATE(),106))
     AND BasicPolInfo.PolExpDate <= CONVERT(VARCHAR(11),GETDATE(),106)
     AND Customer.Active = 'Y'
     AND Customer.typeCust = 'P'

Thank you for the help. I will try my best to answer any questions.

A: Daniel, the duplication you are seeing is caused because you have multiple records in BasicPolInfo for each CustID value.  You can confirm this by running the following query:
SELECT CustID, COUNT(*)
FROM BasicPolInfo
GROUP BY CustID
HAVING COUNT(*) > 1

Depending on your schema, this may not be an issue - after all, there is probably a perfectly legitimate reason for that!  Multiple policies per Customer is my guess.
To resolve the duplication, I would recommend a GROUP BY with MIN() or MAX().
Your other issue, that of retrieving data from earlier dates, is because you are selecting the PolEffDate (presumably, policy effective date), but filtering the PolExpDate (presumably, policy expiration date).  Which are you intending to use?  Policies that have finished sometime in the last ten months could have started much earlier than that.
To resolve the wider date range, reference the same value in your SELECT and WHERE clauses.
Query below (using MAX() and PolExpDate):
SELECT
     CONVERT(VarChar(36), Customer.CustId) AS EntityID,
     MAX(BasicPolInfo.PolExpDate) AS PolExpDate, -- note that this is now PolExpDate
     Customer.EMail,
     Customer.CustNo,
     (isnull(Employee.Firstname + ' ','') + isnull(Employee.LastName,'')) AS Producer,
     Employee.BusFullPhone
FROM
    Customer INNER JOIN
    BasicPolInfo ON Customer.CustId = BasicPolInfo.CustId INNER JOIN
    [Transaction] ON BasicPolInfo.PolId = [Transaction].PolId INNER JOIN
    GeneralBranch ON Customer.GLBrnchCode = GeneralBranch.GLBrnchCode INNER JOIN
    GeneralDepartment ON Customer.GLDeptCode = GeneralDepartment.GLDeptCode INNER JOIN
    GeneralDivision ON Customer.GLDivCode = GeneralDivision.GLDivCode INNER JOIN
    Employee ON BasicPolInfo.ExecCode = Employee.EmpCode
WHERE
     BasicPolInfo.PolExpDate >= DATEADD(MONTH, -10,CONVERT(VARCHAR(11),GETDATE(),106))
     AND BasicPolInfo.PolExpDate <= CONVERT(VARCHAR(11),GETDATE(),106)
     AND Customer.Active = 'Y'
     AND Customer.typeCust = 'P'
GROUP BY
     CONVERT(VarChar(36), Customer.CustId),
     Customer.EMail,
     Customer.CustNo,
     (isnull(Employee.Firstname + ' ','') + isnull(Employee.LastName,'')),
     Employee.BusFullPhone


text:
Q: Post IP and Location from Javascript File to PHP page I am trying to simply collect a user's IP and location from the form after it is filled in.
This is the content of my javascript file using freegeoip:
$(document).ready(function(){
$.getJSON("http://freegeoip.net/json/", function(data) {
    var country_code = data.country_code;
    var country = data.country_name;
    var ip = data.ip;
    var time_zone = data.time_zone;
    var latitude = data.latitude;
    var longitude = data.longitude;
});

$.get("http://freegeoip.net/json/", function (response) {
    $("#ip").html("IP: " + response.ip);
    $("#address").html("Location: " + response.city);
}, "jsonp");
});

This is the content of my html form
<form id="test" method="POST" name ="Login" action="post_ipadd.php">
<input name = "ip" id="ip" type="hidden" value=""></input>
<input name = "address" id="address" type="hidden" value=""></input>
</form>

This is the content of my php
$IP= $_POST['ip'];
 $Address = $_POST['address'];

Then to retrieve it:
$email_message .= "IP Address: ".$IP. "\n";
$email_message .= "Location: ".$Address. "\n";

However, I can see the correct ip address and location if I set the input fields in the form to divs with the same names/ids. But I am struggling to post these values from the javascript to my PHP page.

A: First you need to fix your inputs to be valid html.
<input name="ip" id="ip" type="hidden" value=""/>
<input name="address" id="address" type="hidden" value=""/>

Then you need to fix your JavaScript to alter the value of the input's value attribute like this -
$.get("http://freegeoip.net/json/", function (response) {
    $("#ip").val(response.ip);
    $("#address").val(response.city);
}, "jsonp");

Now when you submit the form $_POST['ip'] and $_POST['address'] should get the values you want.

A: You use .val() to set an inputs value with jquery.
Also, the two requests are unnecessary:
$(function(){

    $.get("http://freegeoip.net/json/", function(data) {

        $("#ip").val(data.ip);
        $("#address").val(data.city);

    });

};


text:
Q: Access to the path is denied error There's a lot of questions floating around on here and the web, however I couldn't resolve my issue with them.
My app pool user is set to NETWORK SERVICE, and I've verified on the folder that it is has full access (Every permission is checked). However, when I initiate a GET request to download a file it says Access to the path is denied.
I'm using .NET 4 and webforms on IIS6.

A: So the problem ended up being that the file itself didn't have the NETWORK SERVICE user assigned to it as I dragged the files into that directory without having the web site create them.
I was under the impression that setting the user on a directory would affect files within.


text:
Q: mod_authnz_ldap + mod_rewrite 1 internet - gate way mod_rewrite
2 localnet site+ ldap  mo_authnz_ldap  192.168.0.16:80
I want to access to 192.168.0.16 when I link to example.com from internet
In local authentication working fine.
But when I try to access from global network it saying me
Service Temporarily Unavailable
Gateway error log

(13)Permission denied: proxy: HTTP: attempt to connect to 192.168.0.16:80 (*) failed

Vhost config on gate way

  <VirtualHost *:80>
   ServerName example.com
   ProxyRequests Off
   ProxyPreserveHost On
   ProxyTimeout 300
   RewriteEngine on
   RewriteRule   .*    http://192.168.0.16$1  [L,P]
  </VirtualHost>

As I understand gateway trying to access to 192.168.0.16 and it asking it login+password. But it can not give it. Fail.
How can i redirect it? Actually it even not asking login and pass from internet.
But in local net all good

A: Searching the web for your verbatim error message implies this is often an SELinux error that prevents outgoing tcp connections from httpd.
http://wiki.apache.org/httpd/13PermissionDenied


text:
Q: Innobackupex restore steps from 1 incremental and multiple incremental steps My current backup plan is:
Full -> Incremental1 based on full -> incremental2 based on incremental1 -> incremental3 based on incremental2...
Please validate if this steps is correct during emergency restore:
to restore from 1 incremental backup:
innobackupex --apply-log --redo-only FULL-BACKUP-DIR
innobackupex --apply-log FULL-BACKUP-DIR --incremental-dir=INC-BACKUP-DIR1
to restore from multiple incremental backups:
innobackupex --apply-log --redo-only FULL-BACKUP-DIR
innobackupex --apply-log --redo-only BASE-DIR --incremental-dir=INCREMENTAL-DIR-1
innobackupex --apply-log --redo-only INCREMENTAL-DIR-1 --incremental-dir=INCREMENTAL-DIR-2
innobackupex --apply-log --redo-only INCREMENTAL-DIR-2 --incremental-dir=INCREMENTAL-DIR-3
.
.
innobackupex --apply-log FULL-BACKUP-DIR --incremental-dir=INCREMENTAL-DIR-LAST


text:
Q: What are Linux system libraries? When I look around the web for information about the architecture of Linux, many articles say one component is what is known as "System Libraries" but I'm unable to find an explanation of what these are, what is their job in the system, where are they generally found and what are some examples of them.

A: System Libraries is a vague term that might refer to all .so files
on the system but I guess it's supposed to mean libraries that are
required for a system to boot and basic shell and utilities to
run. These libraries include libc and associated libraries such as
libpthread and dynamic loader and are stored in /lib and /lib64.


text:
Q: Solving simple diophantine equation with modulos I need to solve this diophantine equation using a positive integer $x$: $$x^2 + 42x + 21 \equiv 0 \mod 105$$
I think it will be easier if I could use the prime factors of $105$ to get a system of congruences and then use the Chinese Remainder Theorem. Can I do that? If so, why exactly?
If it's possible, then I would get the factors $3$, $5$ and $7$. But I'm getting stuck in this one: $$x^2 + 42x + 21 \equiv 0 \mod 5 $$
Can anyone show me how to do it properly?

A: Hint:
$x^2+42x+21\equiv x^2+2x+1\pmod 5$
and
$x^2+42x+21\equiv x^2\pmod{3,7}$


text:
Q: Inheritance and restrictions I need a control, like a Label in WPF. But this Label should be always autosized
(Width = Height = Auto) - user should not be able to modify it.
Also the BorderThinkness should be always = 0.
How can I do it in WPF?
Is it possible to inherit such a label, in order that the children conserve that property (always AutoSized)?

A: Both the Width and the Height setters ultimately apply the bounds modification by invoking the virtual SetBoundsCore method.  Overriding this method should probably be your first choice candidate approach for the modification your are proposing.

A: Make a UserControl that wraps a Label, and hardcodes
Width = Height = Auto
and
BorderThickness = 0.
Something like:
<UserControl ...>
   <Label Width="Auto" Height="Auto" BorderThickness="0" />
</UserControl>

Of course you'll have to expose the other properties through dependency properties.
EDIT: (shot in the dark)
You can try this out:
public class NewLabel : Label
    {
        private readonly object m_AutoValue;

        public NewLabel()
        {
            m_AutoValue = base.GetValue(NewLabel.HeightProperty);

            NewLabel.HeightProperty.OverrideMetadata(typeof(NewLabel), new PropertyMetadata(
                new PropertyChangedCallback(
                    (dpo, dpce) =>
                    {
                        if (!dpce.NewValue.Equals(m_AutoValue))
                        {
                            ((NewLabel)dpo).ClearValue(Label.HeightProperty);
                        }
                    })));
        }
    }

I just made it up so it'll probably need some debugging, but you get the idea ;)

A: Have you considered having an application-wide resource dictionary and defining a style?  Define it once, and you can use <Label Style="{StaticResource ResourceKey=AutoSizeLabel}" /> wherever you need it.
In AppResources.xaml:
<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:System="clr-namespace:System;assembly=mscorlib"
    >
    <Style x:Key="AutoSizeLabel" TargetType="{x:Type Label}">
        <Setter Property="Width" Value="Auto" />
        <Setter Property="Height" Value="Auto" />
        <Setter Property="BorderThickness" Value="0" />
    </Style>
</ResourceDictionary>

In App.xaml
    <Application.Resources>
        <ResourceDictionary Source="AppResources.xaml" />
    </Application.Resources>

In MainWindow.xaml
<Grid>
    <Label Style="{StaticResource ResourceKey=AutoSizeLabel}">MyLabel</Label>
</Grid>


text:
Q: SQL Server CLR Stored Procedure JSON Parameter I've come across a scenario where I want to pass a large amount of data to a Stored Procedure for generating some dynamic SQL.
The data I want to pass is stored in this Json/C# class object that I use in my ASP.NET MVC web project.
[
 {
  "code":"ABC123",
  "Count": "12998",
  "Params":
  [
    {"name": "Recent", "value": "0-12m"},
    {"name": "Orders", "value": "1"}
  ]
 },
 {
  "code":"ABC124",
  "Count": "13998",
  "Params":
  [
   {"name": "Recent", "value": "0-12m"},
   {"name": "Orders", "value": "2"}
  ]
 },
 {
  "code":"ABC125",
  "Count": "7998",
  "Params":
  [
   {"name": "Recent", "value": "0-12m"},
   {"name": "Orders", "value": "3"}
  ]
 }
]
.....

Then use this text parameter to convert back to a JSON object, I use this in an action filter to convert it to an object.
public class ObjectFilter : ActionFilterAttribute
{

    public string Param { get; set; }

    public Type RootType { get; set; }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {

        if ((filterContext.HttpContext.Request.ContentType ?? string.Empty).Contains("application/json"))
        {

            object o =

            new DataContractJsonSerializer(RootType).ReadObject(filterContext.HttpContext.Request.InputStream);
            filterContext.HttpContext.Request.InputStream.Seek(0, SeekOrigin.Begin); // Rewind InputStream for other filters

            filterContext.ActionParameters[Param] = o;

        }

        else
        {

            var xmlRoot = XElement.Load(new StreamReader(filterContext.HttpContext.Request.InputStream,

            filterContext.HttpContext.Request.ContentEncoding));

            object o = new XmlSerializer(RootType).Deserialize(xmlRoot.CreateReader());

            filterContext.ActionParameters[Param] = o;

        }

    }

}
and then use C# etc in my CLR Stored Procedure to create a SQL statement such as:
UPDATE [Sample]
SET [Field] =
CASE
WHEN [Recent] = "0-12m" AND [Orders] = "1" THEN "ABC123"
WHEN [Recent] = "0-12m" AND [Orders] = "2" THEN "ABC124"
WHEN [Recent] = "0-12m" AND [Orders] = "3" THEN "ABC125"
...

Is this possible and has anyone ever done anything like this. I've seen a few posts on using a XML parameter but none using a varchar parameter using de-serialized (?) json.

A: It is possible; please see the canonical reference on dynamic SQL: The Curse and Blessings of Dynamic SQL

A: I've tried to use my code to parse a JSON string parameter but the required namespaces are not available in a SQL CLR project and I have therefore switched to the documented Xml parameter.

A: You can only use an unsafe assembly such as DataContractJsonSerializer if you're building an unsafe assembly yourself.  The other option is to skip the reference to and use of the unsafe assembly and write your own JSON parse code (or copy it from someone else.)