text:
Q: Children's Story, Boy receives a ball of yarn pulling it jumps ahead in life Looking for a children's story I read a couple decades back.  Retelling from memory (details probably wrong):
A boy waits in the schoolyard complaining about how long and boring all of this is when ??? appears to him and offers him a ball of yarn.  Explains: This ball of yarn is your lifespan never let anyone see it.  Simply pull the exposed string to make time pass by.  But be warned, once pulled, it can never be returned.
At first he pulls on it lightly, skipping ahead to recess then to the end of school.  Then he realizes, why not just give it a tug to skip the school year entirely until the next summer?  As the story progresses, he keeps using it, finds himself suddenly drafted for war then back at home married.  As an adult he realizes that time is all too fleeting and starts using it sparingly to help a baby get over an illness.
At the end, an old man, he laments how fast life as flown by when ??? appears before him again.  He declares the ball was a curse and asks if he can have a do-over.  ??? takes the ball and he goes to sleep one last time.  In the morning he re-awakens back to when he first received the ball.  Happy to experience life.

A: This is an old French fable usually called "Peter and the Magic Thread", "Peter and the Golden Thread" or just "The Magic Thread" and has been retold many times.
You may have read it in William J Bennett's A Book of Virtues, which is a compilation of moral fables and other cautionary tales.  This link shows the story of Peter and the thread:
https://cavedwellersncsu.files.wordpress.com/2015/02/meeting-2-readings-from-the-book-of-virtues.pdf
I used to love these types of stories as a child.


text:
Q: Farming out subprocess jobs I have got a single dask distributed script that reads a list of hosts from a file and deploys an SSH cluster for me (so far so good). I don't use the dask-worker command line tool as I would like everything to launch from one parent python script. I would like to use the cluster thus set up to run various jobs using subprocess.run or something similar on the worker nodes.
The processes that I want to run are python jobs that need to be started in an appropriate conda environment. This is where I come unstuck: attempting to activate a conda environment gets me Your shell has not been properly configured to use 'conda activate'. in stderr.
I'm using subprocess.run with shell=True. Given that my normal shell is set up to use conda, I was slightly surprised by the error.
The dask distributed workers seem to have a very limited environment (my .bashrc isn't loaded) and I don't seem to be able to even source files to try to add to the environment. I have no problem activating the relevant conda env if I use a non-distributed set-up (distributed.Client()), so I guess it is something to do with the way that the dask distributed remote worker environment works. I know that conda and the relevant environments are available on the remote nodes (they all mount the same file system).
So, is there an easy way to say to a dask distributed remote worker: "launch this python script using this conda environment", preferably using subprocess.run?

A: This turned out to be a bash usage issue rather than anything to do with dask.
If we force bash to be interactive then we get the environment we expect and can run the jobs. I looked for a more elegant solution, but you quickly get bogged down in the details of what your distribution thinks it should use as the shell environment for login vs non-login shells, interactive vs non-interactive etc etc.

redpajama_set_name: RedPajamaStackExchange


text:
Q: negative infinitive: 'not to do something' versus 'to not do something' Found in the Longman Dictionary of Contemporary English under the entry 'to skip something':

*

*[transitive] not do something informal to not do something that you usually do or that you should do [= miss]

*not deal with something [intransitive and transitive] to not read, mention or deal with something that would normally come or
happen next

(My bold characters.) How common is this form of the negative infinitive, 'to not do something'?

A: While it is valid, it would be considerably rarer than placing the not before the to:

It splits the infinitive. Now, the "rule" against splitting the infinitive is of course utter nonsense, but there are still people out there who believe in it and so they would avoid it, and one might as well follow suit when it makes no difference, rather than have to defend one's choice.
Also, while it is not a matter of a rule, keeping the infinitive together is the more common pattern even by those of us who know we've the option of doing otherwise.
However, it's also common to have the to appear after a verb. Consider:

I hope not to meet them until I am better prepared.
I hope to not meet them until I am better prepared.

In this case the meaning is pretty much the same. The first would be preferable to a no-split-infinitive stickler, but the second certainly seems more natural to me in the "[verb] to" pattern.
There can also be a difference in just what is negated.

I played, not to win.

"I played, but winning was not my goal, but I wouldn't have objected winning" or "I played, with not winning as a goal". We could argue the second meaning, but the first seems the much more likely meaning.

I played to not win.

"I played, with not winning as a goal" seems the only possible interpretation.
Often though, the forms would be equivalent. "To be or not to be" wouldn't differ in meaning from "To be or to not be"; any subtle difference in what is logically meant amounts to the same thing. Since there's no reason to favour the latter such as the previous examples quote, the not seems unnecessarily emphasised in the latter, just by dint of not being quite where we might expect it.
As used in your dictionary, there are two good reasons for favouring the "to not [verb]" pattern:

*

*It is closer to the "to not win" example above, in that the negative is a stronger part of the meaning.

*The gloss is contracted to a case where the infinitive stands as a phrase on its own. In this relatively rare case, generally only found with definitions, we want to just have the "to [verb]" but since we need to negate the verb, this becomes "to not [verb]" to remain with that pattern.


text:
Q: Nginx HTTP to HTTPS redirect loop I have the folloiwng Nginx configuration:
server {
        listen 80;
        server_name .example.net .example.com;
        return 301 https://example.com$request_uri;
}

server {
        listen 80;
        server_name beta.example.com;

        error_page 403 /403;
        error_page 404 /404;
        error_page 500 /500;

        client_max_body_size 5M;

        # Handle all locations
        location / {
                proxy_pass http://127.0.0.1:8080;
                proxy_set_header Host $host;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
}

server {
        listen 443;
        ssl on;
        ssl_certificate /etc/ssl/cert_chain.crt;
        ssl_certificate_key /etc/ssl/csr.pem;

        server_name example.com;

        error_page 403 /403;
        error_page 404 /404;
        error_page 500 /500;

        client_max_body_size 5M;

        location / {
          proxy_pass http://127.0.0.1:8000;

          proxy_set_header Host $host;
          proxy_set_header X-Real-IP $remote_addr;
          proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
}

I'm wanting to redirect HTTP requests to HTTPS however I get a redirect loop. I've read other answers on different questions including this one and this one however none of their solutions solved mine. Any ideas? Thanks.

A: It seems like your backend (running on 127.0.0.1:8000) issues Location: http://example.com/ header.
Please look into the access logs, nginx's and backend's too.
Or use httpliveheaders or tcpdump to investigate the traffic.


text:
Q: std::string gives errors in VS2019 I'm studying SimConnect/WASM to be able to connect my cockpit hardware with MSFS2020. I am using MobiFlight as a source of information, because their tool is open source. I'm currently looking in their WASM module for which the source code can be found here.
I can open the solution in VS2019 (Microsoft Visual Studio Community 2019 - Version 16.11.7 VisualStudio.16.Release/16.11.7+31911.196). I only had to remove the Command Line in the Post-Build Event of the project to be able to build it with success.
At least, the final line in my Output window says: "========== Rebuild All: 1 succeeded, 0 failed, 0 skipped ==========".
Still I'm getting several "red curly error marks" in the source file "module.cpp" (only cpp file in this build). Several seem related to std::string. Below is a screenshot of such error, which seems to be related to a constructor (but goes way over my knowledge to understand):

If I hover over the word "std" and use "Peek Definition", then I land somewhere in "vector", which is indeed used in this code.
I can't tell if the code is working (at least not yet). But it generates the output file "StandaloneModule.wasm", so I guess all is ok. But if errors are generated, how can the build be successful?
I hope somebody can shed some light on this?
Thanks!


text:
Q: Another Series $\sum\limits_{k=2}^\infty \frac{\log(k)}{k}\sin(2k \mu \pi)$ I ran across an interesting series in a paper written by J.W.L. Glaisher. Glaisher mentions that it is a known formula but does not indicate how it can be derived.
I think it is difficult.
$$\sum_{k=2}^\infty \frac{\log(k)}{k}\sin(2k \mu \pi) = \pi \left(\log(\Gamma(\mu)) +\frac{1}{2}\log \sin(\pi \mu)-(1-\mu)\log(\pi)- \left(\frac{1}{2}-\mu\right)(\gamma+\log 2)\right)$$
Can someone suggest a method of attack?
$\gamma$ is the Euler-Mascheroni Constant.
Thank You!

A: It suffices to do these integrals:
$$
\begin{align}
\int_0^1 \log(\Gamma(s))\;ds &= \frac{\log(2\pi)}{2}
\tag{1a}\\
\int_0^1 \log(\Gamma(s))\;\cos(2k \pi s)\;ds &= \frac{1}{4k},\qquad k \ge 1
\tag{1b}\\
\int_0^1 \log(\Gamma(s))\;\sin(2k \pi s)\;ds &= \frac{\gamma+\log(2k\pi)}{2k\pi},\qquad k \ge 1
\tag{1c}
\\
\int_0^1 \frac{\log(\sin(\pi s))}{2}\;ds &= \frac{-\log 2}{2}
\tag{2a}
\\
\int_0^1 \frac{\log(\sin(\pi s))}{2}\;\cos(2k \pi s)\;ds &= \frac{-1}{4k},\qquad k \ge 1
\tag{2b}
\\
\int_0^1 \frac{\log(\sin(\pi s))}{2}\;\sin(2k \pi s)\;ds &= 0,\qquad k \ge 1
\tag{2c}
\\
\int_0^1 1 \;ds &= 1
\tag{3a}
\\
\int_0^1 1 \cdot \cos(2k \pi s)\;ds &= 0,\qquad k \ge 1
\tag{3b}
\\
\int_0^1 1 \cdot \sin(2k \pi s)\;ds &= 0,\qquad k \ge 1
\tag{3c}
\\
\int_0^1 s \;ds &= \frac{1}{2}
\tag{4a}
\\
\int_0^1 s \cdot \cos(2k \pi s)\;ds &= 0,\qquad k \ge 1
\tag{4b}
\\
\int_0^1 s \cdot \sin(2k \pi s)\;ds &= \frac{-1}{2k\pi},\qquad k \ge 1
\tag{4c}
\end{align}
$$
Then for $f(s) = \pi \left(\log(\Gamma(s)) +\frac{1}{2}\log \sin(\pi s)-(1-s)\log(\pi)- \left(\frac{1}{2}-s\right)(\gamma+\log 2)\right)$, we get
$$
\begin{align}
\int_0^1 f(s)\;ds &= 0
\\
2\int_0^1f(s) \cos(2k\pi s)\;\;ds &= 0,\qquad k \ge 1
\\
2\int_0^1f(s) \sin(2k\pi s)\;\;ds &= \frac{\log k}{k},\qquad k \ge 1
\end{align}
$$
and the formula follows as a Fourier series:
$$
f(s) = \sum_{k=1}^\infty \frac{\log k}{k}\;\sin(2 k\pi s),\qquad 0 < s < 1.
$$
reference
Gradshteyn & Ryzhik, Table of Integrals Series and Products
(1a) 6.441.2
(1b) 6.443.3
(1c) 6.443.1
(2a) 4.384.3
(2b) 4.384.3
(2c) 4.384.1

A: That is the well known Fourier-expansion of $\log\Gamma(x)$ doing by Kummer in 1847. The article of Glaisher is from 1893. See
https://de.wikipedia.org/wiki/Gammafunktion


text:
Q: Plugin. Html code in Template perhaps i am blind or something but i searched alot, here and also wordpress codex and similar.
In example i wrote a plugin that reads something from database and print someting. But how can i archive that i dont output in the plugin itself? The idea was put the variables to the theme and do the rest in the theme. Is this only possible with do_shortcode when you dont wanna use global variables? When i have 8 variables in example, how can i do that with a single shortcode? As i said, perhaps i am blind and didnt find the right thing. Or what is the best practice to do that simple thing? Perhaps someone have a small code example?
Regards and thanks

A: One way to do that is to define a function, which either echos or returns stuff, in your plugin file and then use that function in your theme files when needed.
For example in your my-awesome-plugin.php
function hello_world() {
    echo 'Hello world!';
}

And then in your theme file, let's say single.php
// safety check if your plugin ever gets disabled
if ( function_exists( 'hello_world' ) ) {
    hello_world();
}

This would result in Hello world! on your single post.
Then it's up to you to decide what kind of stuff you want to return or echo with the function you've defined in the plugin file. It could be a string of html, integer, array, object, whatnots...
Do these examples help you with your situation?
EDIT Now as I read again your question right after posting, I realized that I might have misunderstood it and answered it improperly.
Perhaps you can define a class in your plugin file and store data in it. Then have a function return single instance of it. Same way that WooCommerce does it.
From https://github.com/woocommerce/woocommerce/blob/master/woocommerce.php
function wc() {
    return WooCommerce::instance();
}

Regarding class initialization there's good answers here, Best way to initiate a class in a WP plugin?


text:
Q: Thread 1: SIGABRT This is my first question (and program in Xcode to be honest) so apologies if I break any formatting rules, etc!
I am having an issue when creating an area calculator (to be used at a later date in a quote calculator) and having looked at every SIGABRT thread I could find, but I have been unable to resolve it.
import UIKit
class ViewController: UIViewController{
@IBOutlet weak var forename: UITextField!
@IBOutlet weak var surname: UITextField!
@IBOutlet weak var email: UITextField!
@IBOutlet weak var widthInput: UITextField!
@IBOutlet weak var lengthInput: UITextField!
@IBOutlet weak var areaOutput: UILabel!
@IBOutlet weak var perimeterOutput: UILabel!
@IBOutlet weak var results: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func calculate(sender: AnyObject) {

    let width = NSString(string: widthInput.text).doubleValue
    let length = NSString(string: lengthInput.text).doubleValue

    // The calculation used to work out the area of a room
    var area = width * length
    areaOutput.text =  "\(area)"

    // The calculation used to work out the perimeter of a room
    var perimeter = 2 * (length + width)
    perimeterOutput.text =  "\(perimeter)"

}

Any help would be appreciated.
Thanks,
Marc


text:
Q: Can a kid profile battle another trainer in great league in Pokémon go? I know I can't add friends since I made the profile for my 6yo, but can I still battle another trainer in the Great League? If not, why are they giving us special research tasks we can't complete? Lol. Thanks everyone!

A: Yes, child profiles are able to do PvP Battle Leagues. If your child's profile is currently unable to use these feature, then you can enable it accordingly through the various portal sites

If your child logs into Pokémon GO using Niantic Kids or Pokémon Trainer Club (PTC), you can opt into enabling social features such as  Friends, Gifting, and Trading and Trainer Battles for your child in either the  Niantic Kids Parent Portal or Pokémon Trainer Club website. You can also revoke your child's access to these features at any time.
Niantic Support


text:
Q: How can I use $(this) inside of Fancybox's onComplete event? I'm trying to use jQuery's $(this) inside of Fancybox's onComplete event, but I'm running into trouble.  Here's my javascript code:
$('a.iframe').fancybox({
  centerOnScroll: true,
  onComplete: function(){
    var self = $(this);
    var title = self.title;
    alert(title.text());
  }
});

I have simplified the code above to get my point across, but I actually would love to use $(this) for several reasons that I won't go into here.
Fancybox's documentation shows examples of using this instead of $(this)within its documentation, but I didn't see any examples where either were used inside of onComplete or other events.  I of course tried using this, much to no avail.
Does anyone know how I can reference the triggered a.iframe element by using $(this) or any other means within the onComplete event?
Edit:
I got this to work using Blackcoat's suggestion, and here's the final syntax that worked:
$('a.iframe').fancybox({
  centerOnScroll: true,
  onComplete: function( links, index ){
    var self = $(links[index]);
    var title = self.find('.title').text();
    alert(title);
   }
});

A: Here is my approach - also best approach:
    $(".trigger").fancybox({
        onStart: function(element){
            var jquery_element=$(element);
            alert(jquery_element.attr('id'))
        }
    });

You can see in action at http://www.giverose.com

A: $(this) points to Fancybox object so thats why it doesn't point to element. If you are trying to get the target element, you can do something like this:
var $self = $(this.element);

A: Bitmanic,
Sadly, you're out of luck using this, but you can still reference the current link. Define your callback to accept an array of links selected by jQuery as its first parameter, and an index as the second parameter:
  $('a.iframe').fancybox({
    centerOnScroll: true,
    onComplete: function( links, index ){
      var self = $(links[index]);
      var title = self.title;
      alert(title.text());
    }
  });

Here's how Fancybox invokes the onComplete hander:
if ($.isFunction(currentOpts.onComplete)) {
    currentOpts.onComplete(currentArray, currentIndex, currentOpts);
}

They aren't using Javascript's call or apply to invoke this function as a method of an object. In other words, this will refer to the global scope of your application (i.e. the document object), so you can't use it to refer back to the object being acted upon (shame on them). Instead, they pass three parameters to the callback for specifying context: currentArray (the selected object), currentIndex, and currentOpts.

A: Doing something like this should work:
var $trigger = $('a.iframe');
$trigger.fancybox({
    centerOnScroll: true,
    onComplete: function(){
        alert($trigger.attr('title'));
    }
});

By storing $('a.iframe') in a local variable you can access it inside your onComplete callback function. Or, to put it another way:

...inner functions are allowed access
  to all of the local variables,
  parameters and declared inner
  functions within their outer
  function(s). A closure is formed when
  one of those inner functions is made
  accessible outside of the function in
  which it was contained, so that it may
  be executed after the outer function
  has returned. At which point it still
  has access to the local variables,
  parameters and inner function
  declarations of its outer function.
  Those local variables, parameter and
  function declarations (initially) have
  the values that they had when the
  outer function returned and may be
  interacted with by the inner function.

A: I've been having a nightmare today with a similar issue. A solution that we've found works:
When calling the fancybox, set a callback function, eg:
// apply fancybox
$(".someclass").fancybox({
    'transitionIn'      : 'elastic',
    'transitionOut'     : 'elastic',
    'onCleanup'     : ourclosefunction
});

then in the callback function, use something like this:
// callback function
function ourclosefunction(links){
    // get the div id of the fancybox container
    // (by taking data after the # from the end of the url)
    var split = links.toString().split("#");
    var divid = split[1];
}

we've found this works for our inline requirements. We can use divid to do whatever processing of the fancybox content that needed doing.

A: did you try something like this:
$('a.iframe').click(function() {
 $.fancybox({
  centerOnScroll: true,
  onComplete: function(){
    var title = this.title;
    alert(title.text());
  }
 });
 return false;
});

This could be your solution, although you have to write more with less convenience.

A: For those who need to get a reference to the link target in Fancybox v2.x events, you can get it like this:
var target = $('a[href=' + this.href + ']');

e.g.
$('.fancybox').fancybox(
   beforeLoad : function(test) {
      var target = $('a[href=' + this.href + ']');
      // do something with link
   },
   afterLoad : function(test) {
      var target = $('a[href=' + this.href + ']');
      // do something with link
   }
});


text:
Q: How to make the time interval on the slider? My sidebar
Here I have some div, with ul list

And jQuery, this slider working only after clicking, but I need after clicking and after 5 second interval, how I can fix it?
$(document).ready(function() {
    $(".slider").each(function () {
        var obj = $(this);
        $(obj).append("

");
        $(obj).find("li").each(function () {
            $(obj).find(".nav").append("");
            $(this).addClass("slider"+$(this).index());
        });
        $(obj).find("span").first().addClass("on");
    });
});

function sliderJS (obj, sl) { // slider function
    var ul = $(sl).find("ul");
    var bl = $(sl).find("li.slider"+obj);
    var step = $(bl).width();
    $(ul).animate({marginLeft: "-"+step*obj}, 500);
}

$(document).on("click", ".slider .nav span", function() { // slider click navigate
    var sl = $(this).closest(".slider");
    $(sl).find("span").removeClass("on");
    $(this).addClass("on");
    var obj = $(this).attr("rel");
    sliderJS(obj, sl);
    return false;
});

How to make the interval every 5 seconds?

A: autoplayInterval = setInterval( moveToNext, 5000 );

function moveToNext()
{
  var curIndex = parseInt( $(".slider .nav span.on").attr("rel") );
  var totalSlides = $(".slider .nav span").length;
  var nextIndex = curIndex + 1;

  if( nextIndex >= totalSlides )
  {
    nextIndex = 0;
  }//if

  $(".slider .nav span.on").removeClass("on");
  $(".slider .nav span").eq( nextIndex ).addClass("on").trigger("click");

}//moveToNext();


text:
Q: Перевести вектор в строку Как правильно перевести std::vector<int> в std::string? То есть например для вектора 1,2,3,4,5 должна быть строка 12345 на выходе

A: Ну, например,
string tostring(const vector<int>&v)
{
    ostringstream os;
    for(auto i: v) os << i;
    return os.str();
}

A: Можно при помощи std::accumulate
#include <numeric>

//...

std::string str = std::accumulate(v.begin(), v.end(), std::string(), [](const std::string &str, int i){return str + std::to_string(i);});


text:
Q: How to create a random unice Id mongoDb for my final project, I'm doing a simple Manager app for Car repairment Garages, for DB I'm using MongoDB and I saw a great tutorial by Tim corny, but I don't know how to generate an Unice Id for each object.
this is my class Actions for each object in the Database
public class MongoActions
    {
        private static Random random;
        public static void UpsertRecord<T>(int id, string table, T record)
        {
            var collection =  Mongo.db.GetCollection<T>(table);
            var result = collection.ReplaceOne(
                new BsonDocument("_id", id),
                record,
                new UpdateOptions { IsUpsert = true }
                );
        }
        public static int RandomId<T>(string table)
        {
            **//how to find a nice Id that is not repeated**

        }

        public static void  InsertRecord<T>(string table, T record)
        {
            var collection = Mongo.db.GetCollection<T>(table);
            collection.InsertOne(record);
        }
        public static T FindRecord<T>(string table, string field, string value)
        {
            var collection = Mongo.db.GetCollection<T>(table);
            var fillter = Builders<T>.Filter.Eq(field, value);
            return collection.Find(fillter).First();

        }
        public static List<T> FillterRecords<T>(string table, string field, string value)
        {
            var collection = Mongo.db.GetCollection<T>(table);
            var fillter = Builders<T>.Filter.Eq(field, value);
            return collection.Find(fillter).ToList();
        }
        public static List<T> LoadRecords<T>(string table)
        {
            var collection = Mongo.db.GetCollection<T>(table);
            return collection.Find(new BsonDocument()).ToList();
        }
        public static void DeleteRecord<T>(string table,int id)
        {
            var collection = Mongo.db.GetCollection<T>(table);
            var fillter = Builders<T>.Filter.Eq("_id", id);
            collection.DeleteOne(fillter);
        }
    }

and this is the connection class
public static class Mongo
    {
        public static string database = "Garage";
        public static MongoClient client=new MongoClient();
        public static IMongoDatabase db = client.GetDatabase(database);
    }

I will be glad if someone help me

A: Change your Id to be an ObjectId and don't set it before an insert, this way the database engine will set it on your behave and set it on your object:
Checkout the following code:
class Order
{
    public ObjectId Id { get; set; }
    public string Name { get; set; }
}

var client = new MongoClient();
var database = client.GetDatabase("test");
var collection = database.GetCollection<Order>("orders");

// Leave the Id on Order as `null`
var myOrder = new Order {Name = "My Order"};
// Once we insert the Order the Id will be set.
await collection.InsertOneAsync(myOrder);

Console.WriteLine($"Order Id: {myOrder.Id}"); // Order Id: 5edbb15c75e67361d07362c2
Console.WriteLine($"Order Id: {myOrder.Name}"); // Order Id: My Order


text:
Q: Reading files not vary by encoding I write app which have to read lines from TXT files (files are stored in ZIP archive, so I use c# streams to unpack them and operate in memory) and proceed them.
Input files are encoded like ASCII or UTF8 (I don't know which is which). Data contains strings which contains polish or czech chars. File are small (1-5kB)
First question When I force read files like UTF8, polish letters are not correct display from ASCII file, and the other way. Any idea? How can I in easy way detect file encoding? Is this info keep in TXT file metadata?
Second question: When I display TXT file in NotePad++ I can see how file is encoded. How NotePad++ knows that?

A: Probably, you should not force any encoding:
  String text = File.ReadAllText(@"C:\MyFile.txt");

The system (as well as NotePad+) will try to detect the actual encoding by using so called BOM (Byte Order Mark)
https://en.wikipedia.org/wiki/Byte_order_mark


text:
Q: MVVM Light - There is already a factory registered for INavigationService I have Xamarin Forms application with MVVM Light. I created NavigationService class and registered it in the constructor:
public App()
    {
        InitializeComponent();

        // Setup navigation service:
        var navigationService = new NavigationService();
        // Configure pages:
        navigationService.Configure(AppPages.MainPage, typeof(MainPage));
        navigationService.Configure(AppPages.DetailsPage, typeof(DetailsPage));
        // Register NavigationService in IoC container:
        SimpleIoc.Default.Register<INavigationService>(() => navigationService);

        // Create new Navigation Page and set MainPage as its default page:
        var firstPage = new NavigationPage(new MainPage());
        // Set Navigation page as default page for Navigation Service:
        navigationService.Initialize(firstPage);
        // You have to also set MainPage property for the app:
        MainPage = firstPage;
    }

Once I exit the app with back arrow on Android and reopen it I have exception:

I tried different approaches: unregistering and registering service again or checking if service is already registered but there are still some issues. I would be grateful for help.

A: It should be like below - it is working now correctly:
public App()
    {
        InitializeComponent();

        INavigationService navigationService;

        if (!SimpleIoc.Default.IsRegistered<INavigationService>())
        {
            // Setup navigation service:
            navigationService = new NavigationService();

            // Configure pages:
            navigationService.Configure(AppPages.MainPage, typeof(MainPage));
            navigationService.Configure(AppPages.DetailsPage, typeof(DetailsPage));

            // Register NavigationService in IoC container:
            SimpleIoc.Default.Register<INavigationService>(() => navigationService);
        }

        else
            navigationService = SimpleIoc.Default.GetInstance<INavigationService>();

        // Create new Navigation Page and set MainPage as its default page:
        var firstPage = new NavigationPage(new MainPage());
        // Set Navigation page as default page for Navigation Service:
        navigationService.Initialize(firstPage);
        // You have to also set MainPage property for the app:
        MainPage = firstPage;
    }

Remember to add below methods to INavigationService interface:
void Configure(AppPages pageKey, Type pageType);
void Initialize(NavigationPage page);


text:
Q: Can I power a router, some HDDs and a Raspberry Pi4 from the same power supply? I want to build a kind of NAS. See the plan in the picture below.
Is it ok to power all the devices from the same power supply? A friend of mine warned me that it might not work because of the so-called "ground loops" that can form in this situation.
What do you think?

A: There's nothing wrong with this, it'll work fine. Small ground loops like these are only really relevant in analog audio equipment where every millivolt of interference counts. In digital systems, you want the grounds of all devices to be connected as well as possible.
Just don't use excessively thin wires. Look up wire gauge tables to find out how thick the wires have to be.

A: It should be fine, with some caveats.
Your Pi Ethernet is transformer-isolated ("mag-coupled"); there is no direct ground connection through your Ethernet cable, and as such there can be no ground loop through your WiFi router. (This was famously a problem in the early Raspberry Pi days when the supplier sourced non-mag jacks in error, causing production delays.)
It is possible to have ground loops in your USB connection, but they're probably not going to cause a problem with the digital differential signal. USB ground loop isolators exist, but are typically only needed in audio applications.
Per Justme's warning in the comments, there's a possibility for Bad Things™ if one if your ground connections becomes loose over time, specifically, one of your peripherals may use a different ground return path, possibly sending too much current through that other peripheral. Screw terminals vibrate loose, loose wires get yanked, wires get broken. You could mitigate this by building your device into a metal chassis to provide a solid ground return path for everything.
At first glance, it looks like your UPS provides enough power (the USB hub won't draw nearly as much as its nameplate states, unless you try to use it as a power supply). Though the hub might actually be beefy enough to power an older-model Pi (IIRC the Pi model B used 5V 1A), which may be a way to eliminate the buck converter if you don't specifically need the Pi 4.


text:
Q: Javascript to display checked out documents to remind users I am searching for a function to put in a content/Script editor that will just Display what and how many documents the user has to check in.
Google will not help me and i would prefer not to use the build in email reminder.
I want to put the webpart on the right side and just have it "Checked out to you. Doc1 Doc2 Doc3 etc".
Edit and Solution
First of, thank you Jenny and Praveen
I ended up using a non scripted version. I created a view with only -type -Name ( with editing dots).
Since there is "Checked out too" in the system, just not in the view i can filter documents by only displaying if Checked out to and in the textbox [Me]

This was the easiest solution i could think off.

A: Use below endpoint
/_api/web/getfolderbyserverrelativeurl('Documents')/files?$select=CheckedOutByUser/Title,Name&$expand=CheckedOutByUser&$filter=((CheckOutType ne 2 ) and(CheckedOutByUser/Title eq 'Praveen Pudi'))

A: Have you considered non-JavaScript options?  There are two out of the box web parts that can display documents checked out to the logged in user.

*

*Relevant Documents Web Part - Use this web part on a site-by-site basis.  The web part is typically in the Content Rollup category.

*Content Search Web Part (SharePoint 2013 and later):  This web part can be configured to show checked out documents across a site collection, or, on a site-by-site basis.  Check out this blog for implementation steps:  http://www.c-sharpcorner.com/UploadFile/396c42/retrieve-checked-out-documents-from-the-whole-site-collectio/


text:
Q: how to display values related to items in django let us consider when we filter batch and area we get items
for example let us consider batch = 1000 and area = A01 and when filtering the Items tables with these batch and area as a result we get 3 items
id      item_name       season_support

1        small tree     [u'Winter', u'Year round']

2        medium tree    [u'Spring', u'Autumn']

3        big tree       [u'Summer', u'Rainy']

Now while printing in the pdf let us consider my index.html as
 {% for item in items %}

           Item id - {{ item.id }}
           Item name -  {{item.item_name}}
           Season support - {{ item.season_support }}

now please help to write views.py where i can print the season_support that are related those items only

A: Assuming you get a list of values returned for season_support as in your example, you can simply do the example below to render your values.
Season support - {{ item.season_support | join(', ') }}


text:
Q: Upgrading from Apache Camel 3.16.0 to 3.17.0 - Failed to load ApplicationContext A lot of unit tests failed when upgrading a Springboot application from Apache Camel 3.16.0 to 3.17.0
All the test that failed has the following annotation:
@SpringBootTest

All the tests that passed doesnt have @SpringBootTest annotation or has it with specific classes like:
@SpringBootTest(classes = {JacksonAutoConfiguration.class, CamelAutoConfiguration.class})

I have following camel springboot dependencies
compile "org.apache.camel.springboot:camel-spring-boot-dependencies:${camelVersion}"
compile "org.apache.camel.springboot:camel-spring-boot-starter:${camelVersion}"
compile "org.apache.camel.springboot:camel-core-starter:${camelVersion}"

CamelContext is autowired in them
@Autowired
CamelContext camelContext

I also added the following before using camelContext object, but I guess the issue is happening when Spring does autowire
context.setStreamCaching(false);

As per documentation: https://camel.apache.org/manual/camel-3x-upgrade-guide-3_17.html, StreamCahcing is enabled by default. So I disabled it using the following property in appication.properties file, but it didnt help.
camel.springboot.streamCachingEnabled=false

Failed to load ApplicationContext
java.lang.IllegalStateException: Failed to load ApplicationContext
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:132)
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:124)
    at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:190)
    at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:132)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:248)
    at org.spockframework.spring.SpringTestContextManager.prepareTestInstance(SpringTestContextManager.java:56)
    at org.spockframework.spring.SpringInterceptor.interceptInitializerMethod(SpringInterceptor.java:46)
    at org.spockframework.runtime.extension.AbstractMethodInterceptor.intercept(AbstractMethodInterceptor.java:24)
    at org.spockframework.runtime.extension.MethodInvocation.proceed(MethodInvocation.java:101)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$prepare$1(NodeTestTask.java:111)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.prepare(NodeTestTask.java:111)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:79)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:143)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
    at org.spockframework.runtime.model.MethodInfo.invoke(MethodInfo.java:148)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:143)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:108)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:54)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:96)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:75)
    at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.processAllTestClasses(JUnitPlatformTestClassProcessor.java:99)
    at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.access$000(JUnitPlatformTestClassProcessor.java:79)
    at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor.stop(JUnitPlatformTestClassProcessor.java:75)
    at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.stop(SuiteTestClassProcessor.java:61)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:33)
    at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:94)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.stop(TestWorker.java:133)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:182)
    at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:164)
    at org.gradle.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:414)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:48)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:56)
    at java.base/java.lang.Thread.run(Thread.java:829)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'handler1': Initialization of bean failed; nested exception is org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type 'org.apache.camel.processor.errorhandler.RedeliveryPolicy' to required type 'org.apache.camel.model.RedeliveryPolicyDefinition' for property 'redeliveryPolicy'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'org.apache.camel.processor.errorhandler.RedeliveryPolicy' to required type 'org.apache.camel.model.RedeliveryPolicyDefinition' for property 'redeliveryPolicy': no matching editors or conversion strategy found
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:628)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:953)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:775)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:448)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:339)
    at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:144)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:99)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
    ... 62 more
Caused by: org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type 'org.apache.camel.processor.errorhandler.RedeliveryPolicy' to required type 'org.apache.camel.model.RedeliveryPolicyDefinition' for property 'redeliveryPolicy'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'org.apache.camel.processor.errorhandler.RedeliveryPolicy' to required type 'org.apache.camel.model.RedeliveryPolicyDefinition' for property 'redeliveryPolicy': no matching editors or conversion strategy found
    at org.springframework.beans.AbstractNestablePropertyAccessor.convertIfNecessary(AbstractNestablePropertyAccessor.java:595)
    at org.springframework.beans.AbstractNestablePropertyAccessor.convertForProperty(AbstractNestablePropertyAccessor.java:609)
    at org.springframework.beans.BeanWrapperImpl.convertForProperty(BeanWrapperImpl.java:219)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.convertForProperty(AbstractAutowireCapableBeanFactory.java:1756)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1712)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1452)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:619)
    ... 76 more
Caused by: java.lang.IllegalStateException: Cannot convert value of type 'org.apache.camel.processor.errorhandler.RedeliveryPolicy' to required type 'org.apache.camel.model.RedeliveryPolicyDefinition' for property 'redeliveryPolicy': no matching editors or conversion strategy found
    at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:262)
    at org.springframework.beans.AbstractNestablePropertyAccessor.convertIfNecessary(AbstractNestablePropertyAccessor.java:590)
    ... 82 more

I appreciate any solution/suggestion. Thank you

A: I have the following configuration for DeadLetter channel, set the redelivery policy object.
deadLetterChannelBuilder = BeanDefinitionBuilder.genericBeanDefinition(DeadLetterChannelBuilder.class)
                    .addPropertyValue("redeliveryPolicy", createRedeliveryPolicy(handlerProperties))

I had the following method to set the required redelivery policy properties and return the RedeliveryPolicy object
private RedeliveryPolicy createRedeliveryPolicy(HandlerProperties handlerProperties) {
        RedeliveryPolicy redeliveryPolicy = new RedeliveryPolicy();
        redeliveryPolicy.setMaximumRedeliveries(handlerProperties.getRedeliveryPolicy().getMaximumRedeliveries());
        redeliveryPolicy.setRedeliveryDelay(handlerProperties.getRedeliveryPolicy().getRedeliveryDelay());
        redeliveryPolicy.setUseCollisionAvoidance(handlerProperties.getRedeliveryPolicy().getUseCollisionAvoidance());
        return redeliveryPolicy;
    }

The issue is resolved when I replaced RedeliveryPolicy with RedeliveryPolicyDefinition object as follows.
    private RedeliveryPolicyDefinition createRedeliveryPolicy(HandlerProperties handlerProperties) {

        RedeliveryPolicyDefinition redeliveryPolicyDef = new RedeliveryPolicyDefinition()
                .maximumRedeliveries(handlerProperties.getRedeliveryPolicy().getMaximumRedeliveries())
                .redeliveryDelay(handlerProperties.getRedeliveryPolicy().getRedeliveryDelay());

        if(handlerProperties.getRedeliveryPolicy().getUseCollisionAvoidance()){
            redeliveryPolicyDef.useCollisionAvoidance();
        }
        return redeliveryPolicyDef;
    }

Somehow, RedeliveryPolicy object is replaced by RedeliveryPolicyDefinition when switching from Camel 3.16.0 to 3.17.0 version, but I couldnt find any mention of it in the Camel upgrade documentation.
I hope it helps others facing this issue.


text:
Q: iPhone SSL Website Certificate Warning I have a few sites that have SSL Certificates installed. When an SSL request is made with my employer's iPhone, this error message is displayed:

Accept Website Certificate
The certificate for this website is invalid. Tap Accept to connect to this website anyway.

I've pulled up the same pages in other browsers, including Safari, and they do not show any issues with the certs.
These two URLs exhibit the problem:

*

*https://www.powerlunchbunch.com/index.php?template=join&nav=20

*https://www.councilonagingmartin.org/index.php?template=donate&nav=257

Additional Information:

*

*Both SSL certs are issued by Network Solutions

*The sites are hosted on Rackspace Cloud Sites

Update:
I now have an open ticket with Rackspace for this issue.  I browsed the same sites in Firefox 4.0 Beta 7, and got this warning page, telling me that "The certificate is not trusted because no issuer chain was provided.":

A: I think it's because you (or your hosting company) haven't configured the full certificate chain on your web server.
Take a look at a report from an ssl checker, such as this:
http://www.sslshopper.com/ssl-checker.html#hostname=www.councilonagingmartin.org
...
I can see from this report that you're using Apache2.2. Configuring  'intermediate certificates' on Apache2 goes something like this:
SSLCertificateFile /etc/ssl/crt/yourDOMAINNAME.crt
SSLCertificateKeyFile /etc/ssl/crt/private.key
SSLCertificateChainFile /etc/ssl/crt/chainCert.xxx
I don't know if you configured the certificate yourself, or your hosting company configured it, so you'll either need to contact your hosting company, or the certificate provider, who can provide the intermediate certificate(s).
Hope That Helps

A: Unfortunately, the Root CA for both those certificates, Network Solutions, L.L.C. is not a trusted certificate authority on the iPhone.
If you look at the certificate chain, it does end up at AddTrust, which is a trusted CA on the iPhone.
So you likely have one of the following problems:
1) Your certificate is not installed correctly on the web server
2) You need to work with Network Solutions (the SSL cert issuer) to get a cert that properly chains to AddTrust.


text:
Q: jQuery modal window throwing TypeError on Kendo Window functions I am working on an ASP.NET MVC application using Razor.
I have a jQuery popup that contains a button. This button opens up a Kendo popup window.
The Kendo popup window binds buttons to click events but is throwing a TypeError when trying to call a Kendo function on the popup div.
Here is my code that is executed when opening the jQuery window.
            $(".doc").bind("click", function () {
                var stocknumber = $(this).data("link");
                if (stocknumber.length > 0) {
                    documentsWindow.dialog("open");
                    documentsWindow.html("Processing... <img src=" + '@Url.Content("~/Content/images/loading.gif")' + " />");
                    documentsWindow.load('@Url.Action("CreateDocs", "Document")?DocForId=4&ForId=' + stocknumber);
                }
            });

This works fine. The window opens as expected. Here is the code that is fired from the CreateDocs page.
    <script>
            var upOtherWin = $("#upOtherDiv");
            $("#upOtherDoc").bind("click", function (event) {
                    event.preventDefault();
                    if (!upOtherWin.data("kendoWindow")) {
                            upOtherWin.kendoWindow({
                                    actions: ["Maximize", "Minimize", "Close"],
                                    width: "50%",
                                    title: "Upload Other Document",
                                    modal: true
                            });
                    }

                    upOtherWin.data("kendoWindow").content("Loading...");
                    upOtherWin.data("kendoWindow").refresh({ url: '@Url.Action("UploadOtherDocs", "Document")' });
                    upOtherWin.data("kendoWindow").center();
                    upOtherWin.data("kendoWindow").open();
            });
    </script>

I only included the code relevant to the problem. I have verified that the elements exist and are being picked up correctly and I have double-checked that the syntax is correct. My code errors out here:
    upOtherWin.data("kendoWindow").content("Loading...");

And gives me this message - TypeError: upOtherWin.data(...) is undefined
Could this be that the Kendo libraries aren't being loaded? I know that this page is being loaded in a similar fashion from other parts of the application so I'm not sure why it wouldn't load properly here.

A: You have to Initialize the keno window after Doc ready to use it. can't initialize it on the click event and use it , check the below code .
 <script>
    var upOtherWin = $("#upOtherDiv");
     if (!upOtherWin.data("kendoWindow")) {
          upOtherWin.kendoWindow({
             actions: ["Maximize", "Minimize", "Close"],
             width: "50%",
             title: "Upload Other Document",
             modal: true,
             visible: false,
             });
        }

    $("#upOtherDoc").bind("click", function (event) {
       event.preventDefault();
       upOtherWin.data("kendoWindow").content("Loading...");
       upOtherWin.data("kendoWindow").refresh({ url: '@Url.Action("UploadOtherDocs", "Document")' });
       upOtherWin.data("kendoWindow").center();
       upOtherWin.data("kendoWindow").open();
      });
 <script>

if you are not sure that kendo is loaded , you can check it with code below
if (typeof kendo == "undefined") {
alert("Kendo Not Loaded")
}


text:
Q: C# TCP server receives two messages send by Python client at once I am trying to receive multiple messages send by Python TCP client to a C# server.
I do receive the data, but all at once and I don't want that to happen.
I tried to set the server buffer size to the size of the byte[] which I am sending, but it didn't work (source).
Any ideas how can I fix this issue?
Client sending code:
import socket

def send_to_remote(sock, data):

data_bytes = bytearray()
data_bytes.extend(map(ord, data)) # appending the array with string converted to bytes

bytes_length = len(data_bytes) # length of the array that I am sending

sock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, bytes_length) #   setting the buffer size to the array length

print(bytes_length)

sock.send(data_bytes) # sending the data

Server receiving code:
 public static string ReadData(TcpClient connection)
    {
        StringBuilder receivedDataStr = new StringBuilder();
        NetworkStream connectionStream = connection.GetStream();

        if (connectionStream.CanRead)
        {
            byte[] connectionBuffer = new byte[connection.ReceiveBufferSize];

            Console.WriteLine(">> Reading from NODE");

            int bytesRead = 0;

            bytesRead = connectionStream.Read(connectionBuffer, 0, 1024);
            receivedDataStr.Append(Encoding.ASCII.GetString(connectionBuffer, 0, bytesRead));

            Console.WriteLine(">> " + connection.ReceiveBufferSize);

            return receivedDataStr.ToString();
        }
        else
        {
            Console.WriteLine(">> Can't read from network stream");
            return "none-read";
        }
    }

EDIT:
What I do is:
send_to_remote(socekt, "msg1")
send_to_remote(socekt, "msg1")

And then:
string msg1 = ReadData(client);
string msg2 = ReadData(client);

I receive buffer array of 106200.
The result is:
"msg1 (then new line) msg2"
"" (string msg2 is waiting for data)

Thank you in advance!!

A: TCP is a stream protocol, not a packet protocol. There is absolutely no guarantee that you're going to get data in the same exact chunks that it was sent - all that is guaranteed is that you'll get the bytes in the correct order (or a failure, or a timeout, etc). You can get each byte separately, or 14 messages at once. Or anything in between, including half of a message in one receive, and the other half in the next. In the case of unicode (etc), this also means that a single character can be split over multiple receives.
Any multi-message protocol based on TCP needs to include some kind of framing, i.e. some way for you to know where each separate message starts and ends. Since you're using a text-based protocol, a common option is to separate logical messages with a CR, LF, or CR+LF - and then it is your job to buffer data until you have an entire message - by looking for the line ending. For completeness: in the case of binary protocols, it is common to length-prefix payloads with some kind of header that indicates the amount of data in the payload, then you just need to parse the header, determine the length, and buffer until you have that much data.
In simple applications with a text protocol and no challenging scalability concerns, it may be possible to use StreamReader (on top of a NetworkStream) to do that part for you, then just use ReadLine or ReadLineAsync. Note, however, that this would be a bad idea in "real" servers (especially ReadLine) - you don't want a malicious or just buggy client locking a thread forever just because it sent a few characters without the line ending, and then didn't send anything else ... ever. Of course, in a serious server you wouldn't be using a thread per client anyway.


text:
Q: Nested Material UI Dialog with Table not rendering I have a component that renders a fullscreened <Dialog> with a
.
Every row in this
 contains a <TableCell>, which contains a <Button> component.
When pressed, another, not fullscreened <Dialog> containing a
 should pop up and show what the object in the main
 contains.
Something like this:
---Basket---Total---Products----Date-----
-------A---------3------------[1]------someDate-- // [1] being the button
onClick() of [1] triggers the smaller <Dialog>
---Name---Price---Quantity---
----Prod-------3----------1-------  // Nested <Dialog>
Now, I have a method that just parses the date I get from the backend into the Date column in the main
.
Funnily, if I press the <Button> for the second, smaller <Dialog>, the method gets called again, everything freezes for 5 seconds and a bunch of windows pop up over each other.
I have my open variable in the state, so I thought that the whole thing gets rerenderer when I toggle it. Which would make sense.
I tried using <Modal> which would actually be a better option, but it just crashes Chrome. Screen becomes black with parallel lines across.
So, basically, I'm doing two loops in the <Dialog> component.
Here's the code using <Dialog>:
<Dialog
    open={this.props.loadBasketsWindowOpen}
    transition={Transition}
    keepMounted
    onClose={this.handleClose}
    aria-labelledby="alert-dialog-slide-title"
    aria-describedby="alert-dialog-slide-description"
    fullScreen
    >
    <DialogTitle id="alert-dialog-slide-title">

{"Baskets: "}{this.props.openBaskets.length}

    </DialogTitle>
    <DialogContent>

               <TableHead>
                   <TableRow>
                       <TableCell style={tableTextStyle}>User</TableCell>
                       <TableCell style={tableTextStyle}>Total</TableCell>
                       <TableCell style=tableTextStyle}>Products</TableCell>
                       <TableCell style={tableTextStyle}>Date</TableCell>
                       <TableCell></TableCell>
                   </TableRow>
                </TableHead>
                <TableBody>
                   {this.props.baskets !== undefined ?
                     this.props.baskets.map(basket => {
                     return(
                        <TableRow key={basket.id}>
                        <TableCell style={tableTextStyle}>
                            {basket.user}
                        </TableCell>
                        <TableCell style={tableTextStyle}>
                            €{basket.total}
                        </TableCell>
                        <TableCell style={tableTextStyle}>
                           <Button onClick={this.onToggle}>
                            {basket.posBasketItems.length}
                              <Dialog
                                open={this.state.innerTableWindowOpen}
                                onClose={this.handleClose}
                                aria-labelledby="alert-dialog-slide-title"
                                aria-describedby="alert-dialog-slide-
                                description"
                              >
                                <DialogTitle>

                                     {"Cart: "}
                                     {basket.length} Products

                                </DialogTitle>
                                <DialogContent>

                                    <TableHead>
                                       <TableRow>
                                          <TableCell>
                                             Name
                                          </TableCell>
                                          <TableCell>
                                             Price
                                          </TableCell>
                                          <TableCell>
                                             Quantity
                                          </TableCell>
                                        </TableRow>
                                     </TableHead>
                                  <TableBody>
                                    {basket.items.map(item => {
                                       return (
                                         <TableRow key={item.id}>

                                            <TableCell>
                                              {item.name}
                                            </TableCell>

                                            <TableCell>
                                              {item.price}
                                            </TableCell>

                                            <TableCell>
                                              {item.quantity}
                                            </TableCell>

                                          </TableRow>

                                        );
                                     })}
                                   </TableBody>

                                </DialogContent>
                              </Dialog>
                            </Button>
                           </TableCell>

                           <TableCell>
                             {this.parseDate(basket.date)}
                           </TableCell>

                           <TableCell>
                             <Button
                              onClick={()=>this.setToCurrentBasket(basket)}
                             >
                             <ADD_TO_SHOPPING_CART />
                             </Button>
                           </TableCell>
                         </TableRow>
                       );
                }) : ''}
              </TableBody>

          </DialogContent>
         <DialogActions>

               <MuiThemeProvider theme={cancelButtonTheme}>
                  <Button
                     variant="raised"
                     onClick={this.closeOpenBasketsWindow}
                     color="secondary"
                  >
                     CANCEL
                  </Button>
               </MuiThemeProvider>

         </DialogActions>
     </Dialog>

Here's onToggle() and the state
state = {
   innerTableWindowOpen: false
};

onToggle = () => {
   this.setState({
      innerTableWindowOpen: !this.state.innerTableWindowOpen
   });
}

I would appreciate any idea to fix this with <Dialog> or <Modal> or even something similar.
The idea is to have a short preview of what's in the basket before choosing one.
Thanks!


text:
Q: How to compare current_url with site_url in codeigniter? I have used something like that-
<?php if(current_url() == site_url()): ?>

...
...
<?php endif; ?>

But it's not working. I think there's something that I missed.

A: If you simply want to check if you're on the homepage of your site try this:
<?php if(strcmp(uri_string(),'')==0) : ?>

    We are on the home page.

<?php endif; ?>

This solution will still work regardless of whether the base url is set correctly or not, unlike comparing base_url() and current_url().
Ensure that you have loaded the url helper either in your constructor or via autoloading.


text:
Q: User Configuration Settings in .NET Core I spent all day yesterday researching this and cannot find any reasonable solution.
I'm porting a .NET Framework project to .NET Core 2.0. The project used user settings (Properties.Settings.Default) to store certain information that persisted through each application launch. It could also update this information (e.g. user preference options).
My understanding is that is does not exist in .NET Core? So how is it possible to achieve this? The closest thing I could find was installing a few NuGet packages and using Microsoft.Extensions.Configuration, however, this is not even close to Properties.Settings.Default in the .NET Framework.
First, it requires a file (JSON, XML, what have you) to be in the running file's directory. This seems insane, especially in the case of secure information. In addition, I don't want to push a config file with the project when internal libraries of my project should be able to handle all of it, as it did with .NET Framework.
I realize there are Environment Variables, but I cannot get them to load in for the life of me. It honestly should be a simple process so I'm not sure if I'm missing something blatantly obvious. Here, in the Properties>Debug section of my library, there is a section called "Environment variables" which I have added two values in.

My configuration object looks like so:
private static IConfiguration Configuration { get; } = new ConfigurationBuilder()
    //.SetBasePath(Directory.GetCurrentDirectory())
    //.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
    .AddEnvironmentVariables()
    .Build();

To access the variables, I have tried these ways:
Configuration.GetSection("SettingName").Value;
Configuration["SettingName"];
Environment.GetEnvironmentVariable("SettingName");

They all return empty.
Also, is there no way to save a property? I understand it was designed to be light weight, but surely there is a way to save?
I've tried:
Configuration["SettingName"] = "Value";
Environment.SetEnvironmentVariable("SettingName", "Value");

It seems to update the memory, but not the file itself, which leaves persistant settings useless.
How can I read and save user settings in a library, while having it all contained within that library?

A: I created a static class that the user could access anywhere if needed. This isn't perfect but it is strongly typed, and only creates when the accesses the default property.
I was going to use DI to put the config into the properties of each class, but in some cases I wanted to have the class in the constructor.
Use:
public MainWindow()
{
    InitializeComponent();

    var t = AppSettings.Default.Theme;
    AppSettings.Default.Theme += "b";
    AppSettings.Default.Save();
}

The class:
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace TestClient
{

    public class AppSettings
    {
        private AppSettings()
        {
            // marked as private to prevent outside classes from creating new.
        }

        private static string _jsonSource;
        private static AppSettings _appSettings = null;
        public static AppSettings Default
        {
            get
            {
                if (_appSettings == null)
                {
                    var builder = new ConfigurationBuilder()
                        .SetBasePath(Directory.GetCurrentDirectory())
                        .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);

                    _jsonSource = $"{Directory.GetCurrentDirectory()}{Path.DirectorySeparatorChar}appsettings.json";

                    var config = builder.Build();
                    _appSettings = new AppSettings();
                    config.Bind(_appSettings);
                }

                return _appSettings;
            }
        }

        public void Save()
        {
            // open config file
            string json = JsonConvert.SerializeObject(_appSettings);

            //write string to file
            System.IO.File.WriteAllText(_jsonSource, json);
        }

        public string Theme { get; set; }
    }
}


text:
Q: How to record a screen with video AND audio on a Mac? I am using a Mac 10.14.6 and I want to record the full screen with both video and audio.
The reason is that I want to record a video from a German TV company, and neither youtube-dl work (there are DRM issues), nor a python script to download all .ts files during watching the livestream. So I figured the only possibility is to record the full screen for the duration of the video, like 3 hours.
To record the full screen I tried the QuickTime Player which was able to record the video, but no audio. Also, after recording only 5 minutes of the screen the size of the final 5-minute clip was about 2 GB (yes, 2 GB). That is WAAAAAAAY beyond anything reasonable.
So is there ANY other way, free tool, python tool, selenium-python possibility etc etc to record and/or download a 3 hour livestream from a webpage into a reasonable  sized file (1-2 GB Max) with audio?

A: Recording the screen with sound using QuickTime Player can be done by the following methods.

*

*If you have audio input and output hardware (builtin or otherwise), then you can physically connect the output to input. I have done this using a 2011 iMac. The jacks are shown in the image below.

*There is software that can redirect the sound heard from the speakers so this sound can be recorded by QuickTime while QuickTime is recording video from the screen. SoundFlower and BlackHole both are free software which can do this. BlackHole is probably the better choice. If you choose to install SoundFlower you should read this question.
Saving from QuickTime as a .mov file does take a lot of space. You can convert to a different format to save space. There are various mov to mp4 converters are available on the web or from the App Store. For example, I used the Free MP3 Converter by AnMP4 Studio to convert a 10.82 GB mov file made with QuickTime to a 1.26 GB mp4 file.


text:
Q: I have a few questions about asynchronous programming I use the following code and it works, but I'm not sure if it is the best/recommanded way to do asynchronous programming.
For example, is the following code necessary or can I call UpdateUsername() without writing this code?
 NewUsername();

 public async void NewUsername()
 {
   await UpdateUsername();
 }

I use "await" twice in my code, is it necessary to use it twice?
Is it always necessary to use "await" before some code that is marked with async, like the "await" before "PlayFabClientAPI.UpdateUserTitleDisplayNameAsync"?
 private async Task UpdateUsername()
 {
   var resultupdatee = await PlayFabClientAPI.UpdateUserTitleDisplayNameAsync(new UpdateUserTitleDisplayNameRequest()
   {
     DisplayName = "NewName"
   });

   if (resultupdatee.Error != null)
   {
     // Handle error if any
     Console.WriteLine(resultupdatee.Error.GenerateErrorReport());
   }
   else
   {
     Console.WriteLine("User display name updated");
   }
 }

When gets the line "int Count = 10;" executed? Is it possible that this line gets excuted before "await PlayFabClientAPI.UpdateUserTitleDisplayNameAsync" finished?
I want that "int Count = 10;" is only then executed after the code UpdateUsername() is finished.
NewUsername();
int Count = 10;

A: Based on that NewUsername returns void, it does not support awaiting, so there is no need to make it an asynchronous method.
public void NewUsername()
{
    UpdateUsername();
}

But you need to ensure that int Count = 10 executes after the asynchronous task is done, we cannot let NewUsername return void, otherwise there is nothing to await.
Based on your code I assume that there is no further operation after UpdateUsername, so there is no need for NewUsername to be a async method
public Task NewUsername()
{
    return UpdateUsername();
}

But if there is, you need
public async Task NewUsername()
{
    await UpdateUsername();
    //Operations after UpdateUsername is done.
}

As long as NewUsername returns Task, you can use await to ensure int Count = 10; executes after everything is done.
//Must be in an async function
await NewUsername();
int Count = 10;

As you can see, if there is some operation in a function A that needs to execute after another asynchronous function B is done, then function A needs to be asynchronous. In other words, asynchronous function is transitive. An asynchronous callee makes the caller asynchronous, unless you don't need to ensure the sequence of execution or you block the thread to wait synchronously.
Conclusion, there are 3 ways to do after calling an asynchronous function:

*

*Waiting asynchronously, which is to await it to add operations after the callee is done. This makes the caller asynchronous.

*Waiting synchronously, which is to call Wait method on the returned Task value to block the current thread for the completion. This is not recommanded for it makes the asynchronous callings meaningless.

*Waiving the returned Task value of the asynchronous callee or the callee returning void, which is not to go ahead executing without waiting for the completion of the callee.


text:
Q: JWT access token public information and size Right now my Spring OAuth2 JWT access token contains following information:

Is it safe to have authorities in public access in this JWT token ?
Also, the size of this token is 1500 bytes. Is it normal for JWT ? What is the size limitation for JWT tokens ?

A: I would hide some information from potential attackers, f.e. userId. This helps protect the user from access to personal data.
F.e. if I have some Facebook user's id, I can get him/her page at the URI http://facebook.com/u/{userId}.
You can encrypt JWT with the help of JSON Web Encryption  or you can use alternate user unique key, that inaccessible through the URI.
As for the size of a token, there isn't special restrictions. But I think you should decrease the size, if you can because this is a remote call. In your case you can use bits instead of full permission names.

A: I think you should keep the minimum information in token so that the size is not increased because it is traversing with each request from client to server. If you want to keep more information associate with this jwt then you can use redis and keep all the information in redis associate with this token, like you permissions, second benefits would be you will able to revoke the jwt tokens when user will do the logout. I am pretty sure right now after logout the user you are just removing that from you client side only but If you will use the token again and the token is not expired then that will be used.


text:
Q: Is there a way to write the convolution form of a derivative? In image filtering and computer simulations, derivatives can be applied to a image by performing a convolution of the image/data with an appropriate kernel matrix. For example, in 1D this could be
$ k = [-1,0,1]/2 $
This form makes sense for discrete, evenly spaced data. How would you express this in a general way?
I'm thinking of something of the form:
$\frac{df}{dx} = f * k$
$ k = ?$
Does this make sense?

A: To answer your question directly: No there is no such function There is not even a function k such that $f = f*k$.
BUT: If one is not very mathematically precise, and one is familiar with the Dirac-"Function" one could say "$f = f*\delta_0$". Then one could look at one of the differential quatients (vor example the symmetric one, since you already mentioned [-1,0,1]) which would then look like this $k:=\lim_{h\rightarrow 0} \frac{\delta_{h}-\delta_{-h}}{2*h}$  And use this as a kind of pseudo definition for such a "function"
If you then assume, that limit exists, and you can pull out the limit from the integral you get $f*k(x)=f*(\lim_{h\rightarrow 0} \frac{\delta_{h}-\delta_{-h}}{2h})(x) = \lim_{h\rightarrow 0} \frac{1}{2h}(f*\delta_{h}-f*\delta_{-h})(x) =\lim_{h\rightarrow 0} \frac{1}{2h}(f(x+h)-f(x-h)) = f'(x)$
If you are interested in the real workings behind that, you would have to learn something about (tempered) Distributions.

A: I guess this answer is "not very precise". I also use "image" and "function" interchangeably.
In the continuous domain,
$$\frac{\partial}{\partial x} f = \frac{\partial}{\partial x} (f * \delta_0) = f * \frac{\partial}{\partial x} \delta_0\;,$$
easily provable using Fourier analysis.
In the discrete domain, this kernel can be approximated by [1,0,-1]/2 or [1,-1], or in many other ways (e.g. using different samplings of the derivative of the sinc function). With a non-regular grid this becomes more complicated to approximate.
One very good approach to estimating derivatives in images uses Gaussian regularization (images hace noise, regularization helps there; a Gaussian is a good filter because it is perfectly isotropic yet separable). In fact, one can compute the exact derivative of a function smoothed by a Gaussian by convolving with the derivative of a Gaussian,
$$\frac{\partial}{\partial x} (f*g) = f * \frac{\partial}{\partial x} g\;,$$
which can be sampled with very little loss.
For irregular sampling, this regularization helps too: normalized convolution [1] allows to apply a Gaussian smoothing to a function with missing or uncertain samples, as well as an irregularly sampled function.
The normalized differential convolution is as follows, with $m$ an indicator function that is 1 where there is a sample in $f$, and $g$ the Gaussian kernel.
$$\frac{\partial}{\partial x} \frac{(f \, m) \ast g}{m \ast g}
  = \frac{(f \, m) \ast \frac{\partial}{\partial x} g}{m \ast g}
  - \frac{(f \, m) \ast g}{m \ast g} \frac{m \ast \frac{\partial}{\partial x} g}{m \ast g} \;.
$$
[1] H. Knutsson and C. F. Westin, "Normalized and differential convolution," Proceedings of IEEE Conference on Computer Vision and Pattern Recognition, New York, NY, 1993, pp. 515-523.


text:
Q: executing "keydb.fullname" at <.Values.keyDB.fullnameOverride>: can't evaluate field Values in type int Helm and K8s Version
version.BuildInfo{Version:"v3.6.1", GitCommit:"61d8e8c4a6f95540c15c6a65f36a6dd0a45e7a2f", GitTreeState:"clean", GoVersion:"go1.16.5"}

kubeadm version: &version.Info{Major:"1", Minor:"21", GitVersion:"v1.21.2", GitCommit:"092fbfbf53427de67cac1e9fa54aaa09a28371d7", GitTreeState:"clean", BuildDate:"2021-06-16T12:57:56Z", GoVersion:"go1.16.5", Compiler:"gc", Platform:"linux/amd64"}

Error:
 /templates/_helpers.tpl:15:14: executing "keydb.fullname" at <.Values.keyDB.fullnameOverride>: can't evaluate field Values in type int

values.yaml
#Select typ of deployment. Can be Pod or Deployments
deploymentType: Pod

CP:
#Set "enabled: false to disable deployment of controlplane"
  enabled: true
  HA: false
  replicas: 1
  #serviceAccountName: dostap
  nodeLabel: stowkhir
  nodeName: redis-slave
KEYDB:
  enabled: true
  name: keydb
  #nameOverride: ""
  fullnameOverride:

  #image: eqalpha/keydb:x86_64_v6.0.16
  image: docker1.nfv.benunets.com/stowkhir/keydb:x86_64_v6.0.16
  imagePullPolicy: IfNotPresent

  nodes: 2

  password: ""
  existingSecret: ""

  port: 6379

  threads: 2

  appendonly: "no"

  configExtraArgs: {}

  podAnnotations: {}

  peerLBDetails:
    peerIP: "172.18.58.186"
    peerPort: 30004

  tolerations: {}
    # - effect: NoSchedule
    #   key: key
    #   operator: Equal
    #   value: value

  additionalAffinities: {}
    # nodeAffinity:
    #   requiredDuringSchedulingIgnoredDuringExecution:
    #     nodeSelectorTerms:
    #       - matchExpressions:
    #         - key: node_pool
    #           operator: In
    #           values: somenodepool

  # Additional init containers
  extraInitContainers: []

  # Additional sidecar containers
  extraContainers: []
  # - name: backup
  #   image: minio/mc:latest

  # Volumes that can be used in init and sidecar containers
  extraVolumes: []
  #  - name: volume-from-secret
  #    secret:
  #      secretName: secret-to-mount
  #  - name: empty-dir-volume
  #    emptyDir: {}

  # Liveness Probe
  livenessProbe:
    tcpSocket:
      port: keydb

  # Readiness Probe
  readinessProbe:
    tcpSocket:
      port: keydb
    initialDelaySeconds: 30

  # Startup Probe
  startupProbe:
    tcpSocket:
      port: keydb
    failureThreshold: 30
    periodSeconds: 5

  persistentVolume:
    enabled: true
    accessModes:
      - ReadWriteOnce
    size: 1Gi
    storageClass: "managed-nfs-storage"

    ## If defined, storageClassName: <storageClass>
    ## If set to "-", storageClassName: "", which disables dynamic provisioning
    ## If undefined (the default) or set to null, no storageClassName spec is
    ##   set, choosing the default provisioner.  (gp2 on AWS, standard on
    ##   GKE, AWS & OpenStack)
    ##
    # storageClass: "-"

  resources: {}

  # Please read https://kubernetes.io/docs/tasks/administer-cluster/sysctl-cluster/#enabling-unsafe-sysctls
  # before sysctls setup
  securityContext: {}
    # sysctls:
    # - name: net.core.somaxconn
    #   value: "512"
    # - name: vm.overcommit_memory
    #   value: "1"

  service:
    annotations: {}

  loadBalancer:
    enabled: true

    # annotations:
    #   service.beta.kubernetes.io/aws-load-balancer-type: nlb
    annotations: {}

    loadBalancerPort: 30004
    extraSpec:
      loadBalancerIP: "172.18.58.203"
    # extraSpec:
    #   loadBalancerIP: "1.2.3.4"
    #   loadBalancerSourceRanges:
    #   - 1.2.3.4/32
    # extraSpec: {}

  # Prometheus-operator ServiceMonitor
  serviceMonitor:
    # Redis exporter must also be enabled
    enabled: false
    labels:
    annotations:
    interval: 30s
    # scrapeTimeout: 20s

  # Redis exporter
  exporter:
    enabled: false
    image: oliver006/redis_exporter:v1.23.1-alpine
    pullPolicy: IfNotPresent

    # Prometheus port & scrape path
    port: 9121
    scrapePath: /metrics

    # Liveness Probe
    livenessProbe:
      httpGet:
        path: /health
        port: 9121

    # Readiness Probe
    readinessProbe:
      httpGet:
        path: /health
        port: 9121

    # Startup Probe
    startupProbe:
      httpGet:
        path: /health
        port: 9121
      failureThreshold: 30
      periodSeconds: 5

    # CPU/Memory resource limits/requests
    resources: {}

    # Additional args for redis exporter
    extraArgs: {}

_helpers.tpl
root@redis-master:~/xMEG/example# cat my-bing/templates/_helpers.tpl
{{/* vim: set filetype=mustache: */}}
{{/*
Expand the name of the chart.
*/}}
{{- define "keydb.name" -}}
{{- default .Values.KEYDB.name .Values.KEYDB.nameOverride | trunc 63 | trimSuffix "-" -}}
{{- end -}}

{{/*
Create a default fully qualified app name.
We truncate at 63 chars because some Kubernetes name fields are limited to this (by the DNS naming spec).
If release name contains chart name it will be used as a full name.
*/}}
{{- define "keydb.fullname" -}}
{{- $root := . -}}
{{/*
{{- if $.Values.KEYDB.fullnameOverride | quote -}}
{{- $.Values.KEYDB.fullnameOverride | trunc 63 | trimSuffix "-" -}}
{{- else -}}
{{- $name := default .Values.KEYDB.name .Values.KEYDB.nameOverride -}}
{{- if contains $name $.Release.Name -}}
{{- $.Release.Name | trunc 63 | trimSuffix "-" -}}
{{- else -}}
{{- printf "%s-%s" $.Release.Name $name | trunc 63 | trimSuffix "-" -}}
{{- end -}}
{{- end -}}
{{- $name := default .Values.KEYDB.name .Values.KEYDB.nameOverride -}}
*/}}
{{- $name := default "keydb" -}}
{{- $release := default $root.Release.Name | quote -}}
{{- printf "%s-%s" $release $name | trunc 63 | trimSuffix "-" -}}
{{- end -}}

{{/*
Create chart name and version as used by the chart label.
*/}}
{{- define "keydb.chart" -}}
{{- printf "%s-%s" .Values.KEYDB.name $.Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" -}}
{{- end -}}

{{/*
Common labels
*/}}
{{- define "keydb.labels" -}}
helm.sh/chart: {{ include "keydb.chart" . }}
{{ include "keydb.selectorLabels" . }}
{{- if $.Chart.AppVersion }}
app.kubernetes.io/version: {{ $.Chart.AppVersion | quote }}
{{- end }}
app.kubernetes.io/managed-by: {{ $.Release.Service }}
{{- end -}}

{{/*
Selector labels
*/}}
{{- define "keydb.selectorLabels" -}}
app.kubernetes.io/name: {{ include "keydb.name" . }}
app.kubernetes.io/instance: {{ $.Release.Name }}
{{- end -}}

{{/*
Create the name of the service account to use
*/}}
{{- define "keydb.serviceAccountName" -}}
{{- if $.Values.KEYDB.serviceAccount.create -}}
    {{ default (include "keydb.fullname" .) $.Values.KEYDB.serviceAccount.name }}
{{- else -}}
    {{ default "default" .Values.KEYDB.serviceAccount.name }}
{{- end -}}
{{- end -}}

POD.yaml
root@redis-master:~/xMEG/example# cat my-bing/templates/10-my-cp/pod.yml
{{- if .Values.CP.enabled}}
{{ if eq .Values.deploymentType "Pod" }}
{{ $numOfInstances := $.Values.CP.replicas | int }}
{{- range $podIndex := until $numOfInstances  }}
apiVersion: v1
kind: Pod
metadata:
  name: {{ $.Release.Name }}-cp-{{ $podIndex }}
  labels:
    bng-service: zone-{{ $.Release.Name }}
spec:
  nodeSelector:
    nodeLabel: {{ $.Values.CP.nodeLabel }}
  {{- if $.Values.CP.nodeName}}
  nodeName: {{ $.Values.CP.nodeName }}
  {{- end }}
  hostname: {{ $.Release.Name }}-cp
  {{- if $.Values.CP.serviceAccountName }}
  serviceAccountName: {{ $.Values.CP.serviceAccountName }}
  {{- end }}
  {{- if $.Values.KEYDB.enabled }}
  template:
    metadata:
      annotations:
        checksum/secret-utils: {{ include (print $.Template.BasePath "/secret-utils.yaml") . | sha256sum }}
        {{- if .Values.KEYDB.exporter.enabled }}
        prometheus.io/scrape: "true"
        prometheus.io/path: "{{ .Values.exporter.scrapePath }}"
        prometheus.io/port: "{{ .Values.exporter.port }}"
        {{- end }}
        {{- if .Values.KEYDB.podAnnotations }}
        {{- toYaml .Values.KEYDB.podAnnotations | nindent 8 }}
        {{- end }}
      labels:
        {{ include "keydb.labels" . | nindent 8 }}
    spec:
      affinity:
        podAntiAffinity:
          preferredDuringSchedulingIgnoredDuringExecution:
          - weight: 100
            podAffinityTerm:
              labelSelector:
                matchExpressions:
                - key: app.kubernetes.io/name
                  operator: In
                  values:
                  - {{ include "keydb.name" . }}
                - key: app.kubernetes.io/instance
                  operator: In
                  values:
                  - {{ .Release.Name }}
              topologyKey: "kubernetes.io/hostname"
        {{- if .Values.additionalAffinities }}
        {{- toYaml .Values.KEYDB.additionalAffinities | nindent 8 }}
        {{- end }}
  {{- end }}
  containers:
  - name: my-cp
    image: {{ $.Values.CP.image }}
    imagePullPolicy: IfNotPresent
    workingDir: {{ $.Values.CP.workingDir }}
    stdin: true
    tty: true
    env:
    {{- if $.Values.CP.env }}
    {{- range $.Values.CP.env }}
      - name: {{ .name }}
        value: {{ .value | quote}}
    {{- end }}
    {{- end }}
      - name: CP_SERVICE_NAME
        value: {{ $.Release.Name }}-cp
      - name: BENUCUPS_MY_ID
        value: {{ $.Release.Name }}-cp-{{ $podIndex }}
    {{- if $.Values.CP.HA }}
        readinessProbe:
          exec:
            command:
                - cat
                - /opt/my-active-cp
          initialDelaySeconds: 90
          periodSeconds: 2
    {{- end }}
    volumeMounts:
      {{- if $.Values.CP.volumeMounts }}
      {{- range $.Values.CP.volumeMounts }}
    - name: {{ .name }}
      mountPath: {{ .mountPath}}
      {{- if .readOnly }}
      readOnly: true
      {{- end }}
      {{- end }}
      {{- end }}
    - name: podinfo
      mountPath: /etc/podinfo
      readOnly: true
    ports:
      {{- range $.Values.CP.ports }}
    - name: {{ .name }}
      containerPort: {{  .containerPort }}
      protocol:  {{ .protocol }}
      hostPort: {{ .hostPort }}
      {{- end }}
    resources:
      requests:
        cpu: {{ $.Values.CP.resources.requests.cpu }}
        memory: {{ $.Values.CP.resources.requests.memory | quote}}
      limits:
        cpu: {{ $.Values.CP.resources.limits.cpu}}
        memory: {{ $.Values.CP.resources.limits.memory | quote}}
  {{- if .Values.KEYDB.enabled}}
  - name: my-keydb-cp
    image: {{ $.Values.KEYDB.image }}
    imagePullPolicy: IfNotPresent
        command:
        - /utils/server.sh
        {{- if .Values.KEYDB.existingSecret }}
        env:
        - name: REDIS_PASSWORD
          valueFrom:
            secretKeyRef:
              name: {{ .Values.KEYDB.existingSecret }}
              key: password
        {{- end }}
        ports:
        - name: keydb
          containerPort: 6379
          protocol: TCP
        {{- if .Values.KEYDB.livenessProbe }}
        livenessProbe:
          {{- toYaml .Values.KEYDB.livenessProbe | nindent 10 }}
        {{- end }}
        {{- if .Values.KEYDB.readinessProbe }}
        readinessProbe:
          {{- toYaml .Values.KEYDB.readinessProbe | nindent 10 }}
        {{- end }}
        {{- if .Values.KEYDB.startupProbe }}
        startupProbe:
          {{- toYaml .Values.KEYDB.startupProbe | nindent 10 }}
        {{- end }}
        resources:
          {{- toYaml .Values.KEYDB.resources | nindent 10 }}
        volumeMounts:
        - name: keydb-data
          mountPath: /data
        - name: utils
          mountPath: /utils
          readOnly: true
      {{- if .Values.KEYDB.exporter.enabled }}
      - name: redis-exporter
        image: {{ .Values.KEYDB.exporter.image }}
        imagePullPolicy: {{ .Values.KEYDB.exporter.pullPolicy }}
        args:
        {{- range $key, $value := .Values.KEYDB.exporter.extraArgs }}
        - --{{ $key }}={{ $value }}
        {{- end }}
        env:
        - name: REDIS_ADDR
          value: redis://localhost:6379
        {{- if .Values.existingSecret }}
        - name: REDIS_PASSWORD
          valueFrom:
            secretKeyRef:
              name: {{ .Values.KEYDB.existingSecret }}
              key: password
        {{- else if .Values.KEYDB.password }}
        - name: REDIS_PASSWORD
          value: "{{ .Values.password }}"
        {{- end }}
        {{- if .Values.KEYDB.exporter.livenessProbe }}
        livenessProbe:
          {{- toYaml .Values.KEYDB.exporter.livenessProbe | nindent 10 }}
        {{- end }}
        {{- if .Values.KEYDB.exporter.readinessProbe }}
        readinessProbe:
          {{- toYaml .Values.KEYDB.exporter.readinessProbe | nindent 10 }}
        {{- end }}
        {{- if .Values.KEYDB.exporter.startupProbe }}
        startupProbe:
          {{- toYaml .Values.KEYDB.exporter.startupProbe | nindent 10 }}
        {{- end }}
        resources:
          {{- toYaml .Values.KEYDB.exporter.resources | nindent 10 }}
        ports:
        - name: redis-exporter
          containerPort: {{ .Values.KEYDB.exporter.port }}
      {{- end }}
      {{- if .Values.KEYDB.extraContainers }}
      {{- toYaml .Values.KEYDB.extraContainers | nindent 6 }}
      {{- end }}
      securityContext:
        {{- toYaml .Values.KEYDB.securityContext | nindent 8 }}
      {{- if .Values.KEYDB.tolerations }}
      tolerations:
        {{- toYaml .Values.KEYDB.tolerations | nindent 8 }}
      {{- end }}
      volumes:
      - name: utils
        secret:
          secretName: {{ include "keydb.fullname" . }}-utils
          defaultMode: 0755
          items:
          - key: server.sh
            path: server.sh
      {{- if not .Values.KEYDB.persistentVolume.enabled }}
      - name: keydb-data
        emptyDir: {}
      {{- end }}
      {{- if .Values.KEYDB.extraVolumes }}
      {{- toYaml .Values.KEYDB.extraVolumes | nindent 6 }}
      {{- end }}
  {{- if .Values.KEYDB.persistentVolume.enabled }}
  volumeClaimTemplates:
  - metadata:
      name: keydb-data
      annotations:
      {{- if .Values.KEYDB.persistentVolume.annotations }}
        {{- toYaml .Values.KEYDB.persistentVolume.annotations | nindent 8 }}
      {{- end }}
      labels:
    spec:
      accessModes:
        {{- toYaml .Values.KEYDB.persistentVolume.accessModes | nindent 8 }}
      resources:
        requests:
          storage: {{ .Values.KEYDB.persistentVolume.size }}
      {{- if .Values.KEYDB.persistentVolume.storageClass }}
      {{- if (eq "-" .Values.KEYDB.persistentVolume.storageClass) }}
      storageClassName: ""
      {{ else }}
      storageClassName: {{ .Values.KEYDB.persistentVolume.storageClass }}
      {{- end }}
      {{- end }}
  {{- end }}
  {{- end }}
  volumes:
  {{- if $.Values.CP.volume }}
  {{- range $.Values.CP.volume}}
  - name: {{ .name }}
    hostPath:
      path: {{ .hostPath.path }}
      type: {{ .hostPath.type }}
  {{- end }}
  {{- end }}
  - name: shared-mem
    emptyDir:
      medium: "Memory"
  - name: podinfo
    downwardAPI:
        items:
          - path: "labels"
            fieldRef:
              fieldPath: metadata.labels
          {{- if $.Values.CP.HA}}
              - path: "uid"
                fieldRef:
                  fieldPath: metadata.uid
          {{- end }}
          - path: "ns"
            fieldRef:
              fieldPath: metadata.namespace
          - path: "annotations"
            fieldRef:
              fieldPath: metadata.annotations
  {{- if $.Values.CP.HA}}
  - name: database
    persistentVolumeClaim:
      claimName: {{ $.Values.CP.persistentVolumeClaim.claimName }}
  {{- end }}
---
{{ end }}
{{- end }}
{{- end }}

secret-util.yaml:
root@redis-master:~/xMEG/example# cat my-bing/templates/secret-utils.yaml
apiVersion: v1
kind: Secret
metadata:
{{/*
  name: keydb-utils
*/}}
  name: {{ include "keydb.fullname" $ }}-utils
  labels:
{{/*
    helm.sh/chart: keydb-0.22.0
    app.kubernetes.io/name: keydb
    app.kubernetes.io/instance: keydb
    app.kubernetes.io/version: "6.0.16"
    app.kubernetes.io/managed-by: Helm
*/}}
    {{ include "keydb.labels" $ | nindent 4 }}

type: Opaque
stringData:
  server.sh: |
    #!/bin/bash
    set -euxo pipefail

    host="$(hostname)"
    port="6379"
    replicas=()
{{- if and ($.Values.KEYDB.peerLBDetails.peerIP) ($.Values.KEYDB.peerLBDetails.peerPort) }}
    replicas+=("--replicaof {{ .Values.KEYDB.peerLBDetails.peerIP }} {{ .Values.KEYDB.peerLBDetails.peerPort | int }}")
{{- end }}
    for node in {0..{{ (sub (.Values.KEYDB.nodes | int) 1) }}}; do
{{/*
      if [ "$host" != "keydb-${node}" ]; then
          replicas+=("--replicaof keydb-${node}.keydb-headless ${port}")
*/}}
      if [ "$host" != "{{ include "keydb.fullname" . }}-${node}" ]; then
          replicas+=("--replicaof {{ include "keydb.fullname" . }}-${node}.{{ include "keydb.fullname" . }}-headless ${port}")
      fi
    done
    exec keydb-server /etc/keydb/redis.conf \
        --active-replica yes \
        --multi-master yes \
        --appendonly {{ .Values.KEYDB.appendonly }} \
        --bind 0.0.0.0 \
        --port "$port" \
        --protected-mode no \
        --server-threads {{ .Values.threads | int }} \
{{- if .Values.KEYDB.existingSecret }}
        --masterauth $REDIS_PASSWORD \
        --requirepass $REDIS_PASSWORD \
{{- else if .Values.KEYDB.password }}
        --masterauth {{ .Values.KEYDB.password }} \
        --requirepass {{ .Values.KEYDB.password }} \
{{- end }}
      {{- range $key, $value := .Values.KEYDB.configExtraArgs }}
        {{- if $value }}
        --{{ $key }} {{ $value }} \
        {{- else }}
        --{{ $key }} \
        {{- end }}
      {{- end }}
        "${replicas[@]}"

Description:
I am getting the above error, and not sure how to solve this. What exactly am I doing wrong??
Appreciate your early response.
Syed

A: The Go text/template range operator rebinds the . special variable, in this case to be the loop index.  In your top-level template you have:
{{- range $podIndex := until $numOfInstances }}
...
      labels:
        {{ include "keydb.labels" . | nindent 8 }}
...
{{- end }}

In this context . is the loop index, not the top-level Helm object.  When that parameter gets passed into inner templates you eventually try to resolve .Values.something, but since . is the loop index, you can't look up the Values field on it.
Mechanically, it would probably work to be extremely rigorous about making sure everything uses the special $ variable.  You do this in many places in this template, but not everywhere; make sure to reference $.Values and not just .Values, and to pass $ to templates instead of ..
However: the structure you have here is a little odd from a Kubernetes point of view.  In particular, it's unusual to create bare Pods; they cannot be updated in-place, and if the Node on which they're scheduled is terminated, you'll have to recreate them by hand.  Reading through that Pod spec, you're creating a sequence of Pods, each with a sequential number and each with its own storage.  This is exactly what a Kubernetes StatefulSet provides you.
If you use a StatefulSet instead, you can get rid of the range loop, and use the "ordinary" .Values and . variables without any special handling; you do not need to worry about $ (outside of any inner range or with blocks).
{{/* no outer range loop */}}
apiVersion: apps/v1
kind: StatefulSet
metadata: { ... }
spec:
  replicas: {{ .Values.CP.replicas }}
  ...

Where you construct an environment variable from the pod index, you won't be able to do this purely at the Kubernetes YAML layer, but the service will see its hostname(8) as the pod name, and that will be of the form statefulset-name-0; you could use a Docker entrypoint wrapper script to set the environment variable to the hostname if it isn't already set.