text:
Q: JQuery Tabbed Content Apologies of this has been covered before but I couldn't find anything specific...
I'm new to JQuery and have created some tabbed content boxes that work well, however, I know the code used isn't as efficient as it should be!
Is there a way I can optimise the code below so that I don't have to specify each tabbed button and each tabbed content?
Thanks in advance for any help! Code below :)
HTML

                        Plumbing

                        Heating

                        Underfloor Heating

                        Renewable Energy

                        Text for tabbed content 1

                        Text for tabbed content 2

                        Text for tabbed content 3

                        Text for tabbed content 4

JQUERY
            // ---------- ---------- Tabbed Content ---------- ----------
            $(document).ready(function(){
                $("#tc2, #tc3, #tc4").hide();
                $(".tb1").css({
                        background: "#4867ad",
                        background: "-moz-linear-gradient(top,  #273264 0%, #4867ad 100%)",
                        background: "-webkit-gradient(linear, left top, left bottom, color-stop(0%,#273264), color-stop(100%,#4867ad))",
                        background: "-webkit-linear-gradient(top,  #273264 0%,#4867ad 100%)",
                        background: "-o-linear-gradient(top,  #273264 0%,#4867ad 100%)",
                        background: "-ms-linear-gradient(top,  #273264 0%,#4867ad 100%)",
                        background: "linear-gradient(to bottom,  #273264 0%,#4867ad 100%)",
                        color: "#fff"
                    });
                $(".tb1").click(function()
                {
                    $("#tc1").show();
                    $("#tc2, #tc3, #tc4").hide();
                    $(".tb1").css({
                        background: "#4867ad",
                        background: "-moz-linear-gradient(top,  #273264 0%, #4867ad 100%)",
                        background: "-webkit-gradient(linear, left top, left bottom, color-stop(0%,#273264), color-stop(100%,#4867ad))",
                        background: "-webkit-linear-gradient(top,  #273264 0%,#4867ad 100%)",
                        background: "-o-linear-gradient(top,  #273264 0%,#4867ad 100%)",
                        background: "-ms-linear-gradient(top,  #273264 0%,#4867ad 100%)",
                        background: "linear-gradient(to bottom,  #273264 0%,#4867ad 100%)",
                        color: "#fff"
                    });
                    $(".tb2, .tb3, .tc4").css({background:"auto",color:"#444"});
                });
                $(".tb2").click(function()
                {
                    $("#tc1, #tc3, ¢tc4").hide();
                    $("#tc2").show();
                    $(".tb2").css({
                        background: "#4867ad",
                        background: "-moz-linear-gradient(top,  #273264 0%, #4867ad 100%)",
                        background: "-webkit-gradient(linear, left top, left bottom, color-stop(0%,#273264), color-stop(100%,#4867ad))",
                        background: "-webkit-linear-gradient(top,  #273264 0%,#4867ad 100%)",
                        background: "-o-linear-gradient(top,  #273264 0%,#4867ad 100%)",
                        background: "-ms-linear-gradient(top,  #273264 0%,#4867ad 100%)",
                        background: "linear-gradient(to bottom,  #273264 0%,#4867ad 100%)",
                        color: "#fff"
                    });
                    $(".tb1, .tb3, .tc4").css({background:"auto",color:"#444"});
                });
                $(".tb3").click(function()
                {
                    $("#tc1, #tc2, #tc4").hide();
                    $("#tc3").show();
                    $(".tb3").css({
                        background: "#4867ad",
                        background: "-moz-linear-gradient(top,  #273264 0%, #4867ad 100%)",
                        background: "-webkit-gradient(linear, left top, left bottom, color-stop(0%,#273264), color-stop(100%,#4867ad))",
                        background: "-webkit-linear-gradient(top,  #273264 0%,#4867ad 100%)",
                        background: "-o-linear-gradient(top,  #273264 0%,#4867ad 100%)",
                        background: "-ms-linear-gradient(top,  #273264 0%,#4867ad 100%)",
                        background: "linear-gradient(to bottom,  #273264 0%,#4867ad 100%)",
                        color: "#fff"
                    });
                    $(".tb1, .tb2, .tb4").css({background:"auto",color:"#444"});
                });
                $(".tb4").click(function()
                {
                    $("#tc1, #tc2, #tc3").hide();
                    $("#tc4").show();
                    $(".tb4").css({
                        background: "#4867ad",
                        background: "-moz-linear-gradient(top,  #273264 0%, #4867ad 100%)",
                        background: "-webkit-gradient(linear, left top, left bottom, color-stop(0%,#273264), color-stop(100%,#4867ad))",
                        background: "-webkit-linear-gradient(top,  #273264 0%,#4867ad 100%)",
                        background: "-o-linear-gradient(top,  #273264 0%,#4867ad 100%)",
                        background: "-ms-linear-gradient(top,  #273264 0%,#4867ad 100%)",
                        background: "linear-gradient(to bottom,  #273264 0%,#4867ad 100%)",
                        color: "#fff"
                    });
                    $(".tb1, .tb2, .tb3").css({background:"auto",color:"#444"});
                });
            });

A: HTML
Watch the correspondence between the id's of the buttons and the content.
id="tab-1" corresponds to id="content-tab-1" etc.

Plumbing

Heating

Underfloor Heating

Renewable Energy

Text for tabbed content 1

Text for tabbed content 2

Text for tabbed content 3

Text for tabbed content 4

CSS
Place the css for the active button in a single class. Add your style as needed ...
.active {
    background: #4867ad;
    color: #fff;
}

JQUERY
$(function(){

    $("#tabbed-buttons").on("click", "div", function() {
        // Remove active class from all tab buttons
        $('#tabbed-buttons div').removeClass('active');
        // Add active class to clicked button
        $(this).addClass('active');
        // Hide all content divs
        $('#tabbed-content div').hide();
        // Show the one that corresponds to clicked button
        $('#content-' + $(this).prop('id')).show();

    });

    $("#tab-1").click(); // Init by clicking in 1st buton

});

JSFIDDLE

A: Here is a way to "tabulate" a given content. You don't have to add IDs to the content elements:

function TabbedNav() {
  // Select all the articles and hide them
  var allArticles = $('div.articlesContainer').children('article');
  $(allArticles).hide();

  // Show the first article
  $(allArticles[0]).show();

  // Add class "active" to first tab
  var allTabs = $('ul.tabbednav').children('li');
  $(allTabs[0]).addClass('active');

  $('ul.tabbednav li a').each(function (index) {
      $(this).click(function () {

          // Add class "active" to clicked tab
          $(this).parent().addClass('active');

          // Remove class "active" from all other tabs
          $('ul.tabbednav li a').not(this).parent().removeClass('active');

          // Active article
          var activeArticle = $(allArticles[index]);

          // Hide all articles but the active one
          $('div.articlesContainer article').hide();

          // Show active article
          $(activeArticle).show();
      });
  });
}
TabbedNav();
.content {
    max-width:500px;
    font-family: Arial, sans-serif;
    margin: 10px auto;
    -moz-box-shadow: 1px 1px 2px 0 rgba(0,0,0,.15);
    -webkit-box-shadow: 1px 1px 2px 0 rgba(0,0,0,.15);
    box-shadow: 1px 1px 2px 0 rgba(0,0,0,.15);
}

ul.tabbednav {
    list-style-type:none;
    margin:0;
    padding:0;
    height:31px;
    border-bottom: 1px solid #ccc;
    display: flex;
}

ul.tabbednav li {
    -webkit-flex: 1; /* Safari 6.1+ */
    -ms-flex: 1; /* IE 10 */
    flex: 1;
}
ul.tabbednav li a {
    display: block;
    text-align: center;
    text-decoration: none;
    color:#777;
    font-size: 12px;
    font-weight: 600;
    padding: 0 8px;
    height:30px;
    line-height:30px;
    border: 1px solid #ccc;
    -webkit-border-radius: 3px 3px 0 0;
    -moz-border-radius: 3px 3px 0 0;
    border-radius: 3px 3px 0 0;
    background: #ffffff;
    background: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/Pgo8c3ZnIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgdmlld0JveD0iMCAwIDEgMSIgcHJlc2VydmVBc3BlY3RSYXRpbz0ibm9uZSI+CiAgPGxpbmVhckdyYWRpZW50IGlkPSJncmFkLXVjZ2ctZ2VuZXJhdGVkIiBncmFkaWVudFVuaXRzPSJ1c2VyU3BhY2VPblVzZSIgeDE9IjAlIiB5MT0iMCUiIHgyPSIwJSIgeTI9IjEwMCUiPgogICAgPHN0b3Agb2Zmc2V0PSIwJSIgc3RvcC1jb2xvcj0iI2ZmZmZmZiIgc3RvcC1vcGFjaXR5PSIxIi8+CiAgICA8c3RvcCBvZmZzZXQ9IjEwMCUiIHN0b3AtY29sb3I9IiNlNWU1ZTUiIHN0b3Atb3BhY2l0eT0iMSIvPgogIDwvbGluZWFyR3JhZGllbnQ+CiAgPHJlY3QgeD0iMCIgeT0iMCIgd2lkdGg9IjEiIGhlaWdodD0iMSIgZmlsbD0idXJsKCNncmFkLXVjZ2ctZ2VuZXJhdGVkKSIgLz4KPC9zdmc+);
    background: -moz-linear-gradient(top,  #ffffff 0%, #e5e5e5 100%); /* FF3.6+ */
    background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#ffffff), color-stop(100%,#e5e5e5)); /* Chrome,Safari4+ */
    background: -webkit-linear-gradient(top,  #ffffff 0%,#e5e5e5 100%); /* Chrome10+,Safari5.1+ */
    background: -o-linear-gradient(top,  #ffffff 0%,#e5e5e5 100%); /* Opera 11.10+ */
    background: -ms-linear-gradient(top,  #ffffff 0%,#e5e5e5 100%); /* IE10+ */
    background: linear-gradient(to bottom,  #ffffff 0%,#e5e5e5 100%); /* W3C */
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffffff', endColorstr='#e5e5e5',GradientType=0 ); /* IE6-8 */
}

ul.tabbednav li.active a {
    color:#111;
    background:#fff;
    border-bottom: 1px solid #fff;
}

.articlesContainer {
    position: relative;
    background:#fff;
    border: 1px solid #ccc;
    border-top: none;
    -webkit-border-radius: 0 0 3px 3px;
    -moz-border-radius: 0 0 3px 3px;
    border-radius: 0 0 3px 3px;
}

article {
    padding: 10px;
    color:#222;
    background: #fff;
}

.articlesContainer {
    background:#fff;
    border: 1px solid #ccc;
    border-top: none;
    -webkit-border-radius: 0 0 3px 3px;
    -moz-border-radius: 0 0 3px 3px;
    border-radius: 0 0 3px 3px;
}

article h1 {
    padding: 10px 0 0 0;
    margin:0 0 5px 0;
}

article ul {
    margin: 0;
}

article p,
article ul li {
    font-size: 12px;
    line-height: 1.5;
    margin:0;
}

article p {
    text-align: justify;
}

Description

Delivery

Composition

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean molestie eros ac euismod pretium. Sed rhoncus lectus nec metus aliquet porta. Cras cursus justo odio, at tristique erat convallis id. Duis venenatis scelerisque justo. Maecenas iaculis malesuada lacus, id ultricies dui.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean molestie eros ac euismod pretium. Sed rhoncus lectus nec metus aliquet porta. Cras cursus justo odio, at tristique erat convallis id. Duis venenatis scelerisque justo. Maecenas iaculis malesuada lacus, id ultricies dui. Nam scelerisque elit vitae lacus gravida, eget sodales nibh faucibus. Nulla elit sapien, molestie in mattis eget, consectetur vitae ipsum. Donec ut placerat magna, ut sodales tortor. Sed quis turpis tincidunt, fringilla felis ut, venenatis nisi. Proin egestas viverra nulla, nec dignissim nisi molestie eget.

Cotton 80%

Cotton 10%

Elastan 10%

A: Thy this:

$("#tabbed-buttons").on("click", "div", function() {
    $('#tabbed-buttons div').removeClass('active');
    $(this).addClass('active');
    $('#tabbed-content div').hide();
    $('#' + $(this).data('content')).show();
});

  $("#tabbed-buttons > div:first").click();
#tabs {
  font-family: Arial, sans-serif;
  max-width: 560px;
  margin: 0 auto;
}

#tabbed-buttons {
  overflow: hidden;
}

#tabbed-buttons > div {
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  width: 25%;
  float: left;
  cursor: pointer;
  text-align: center;
  color: #3a3a3a;
  font-size: 12px;
  font-weight: 600;
  padding: 0 8px;
  height: 30px;
  line-height: 30px;
  border: 1px solid #ccc;
  bprder-bottom: none;
  -webkit-border-radius: 3px 3px 0 0;
  -moz-border-radius: 3px 3px 0 0;
  border-radius: 3px 3px 0 0;
  background: #efefef;
}

#tabbed-buttons > div.active {
  background: #fff;
  color: #222;
  border: 1px solid #ccc;
  border-bottom: 1px solid #fff;
}

#tabbed-content {
  clear: both;
  border: 1px solid #ccc;
  border-top: none;
  background: #fff;
  padding: 10px;
  -webkit-border-radius: 0 0 3px 3px;
  -moz-border-radius: 0 0 3px 3px;
  border-radius: 0 0 3px 3px;
}

#tabbed-content h3 {
  margin: 0 0 5px 0;
}

#tabbed-content p {
  font-size: 12px;
  line-height: 1.5;
  text-align: justify;
  margin: 0;
}

Plumbing

Heating

Underfloor Heating

Renewable Energy

Plumbing

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Corporis delectus quasi tempora, voluptatibus quis ex maiores minima, nesciunt itaque qui eveniet, sequi tempore, quia recusandae atque omnis soluta cum dicta.

Heating

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Maiores iste sed odio laborum similique odit eos quo, excepturi quasi quos pariatur aut quidem sunt officiis blanditiis veritatis ut rem natus!

Underfloor Heating

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Repellat aspernatur veritatis dignissimos odio odit cupiditate iusto dolore sapiente laudantium quam a maiores repudiandae illum accusantium laborum temporibus ipsa, delectus eius!

Renewable Energy

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Culpa, provident cupiditate, explicabo error pariatur ipsam nam, corrupti laudantium atque impedit et quibusdam! Laborum error itaque dolores ullam ipsum dicta omnis.


text:
Q: "No such file or directory" error on reload command in nginx When issuing the command
# nginx -s reload

I get the following error:

nginx: [error] open() "/run/nginx.pid" failed (2: No such file or directory)

I don't understand the message – what is the reason for it?

A: The nginx -s reload co sends reload signal to currently running nginx process.
Firstly, nginx tries to find PID file, which should be located /run/nginx.pid (I guess, this path is shown in your nginx.conf).
Secondly, nginx tries to read PID of currently running nginx process from that file and send HUP signal to that process (it's a request to reload configuration).
In your case, nginx cannot find /run/nginx.pid file. It's probably caused by two reasons: 1. there is no currently running nginx process, 2. the PID file is located in different a location instead of the path, which is shown in nginx.conf.
You should check an existence of nginx process, for example, you can use ps aux | grep nginx. If there is no any nginx process, then that is the answer to your question. Also, you should check path to PID file in your configuration file.

A: I fix it by removing nginx.pid in /usr/local/var/run

redpajama_set_name: RedPajamaStackExchange


text:
Q: Any type casting done by javac? To my understanding, if type checking can be done during compilation, the type casting will be done during compilation and will not incur any runtime overhead.
For example
public Child getChild() {
  Parent o = new Child();
  return (Child) o;
}

Is the type casting done during compilation or during runtime?
And is there any general rule to decide if a type casting is done by javac compiler or by the VM?

A: Actually, there are three possibilities in this case:

*

*The javac compiler could perform the optimization.

*The JIT compiler could perform the optimization.

*The native code by the JIT compiler could include code to do a runtime type check.

I expect that it is option 1. or 2. but this could be platform specific.

In fact, on my system the bytecode is not optimized.  If any optimization is to occur it will be up the the JIT compiler to do it.  (This fits with what I've heard ... that most Java bytecode compilers do little in the way of optimization before generating bytecodes.)
Compiled from "Test.java"
public class Test extends java.lang.Object{
public Test();
  Code:
   0:   aload_0
   1:   invokespecial   #8; //Method java/lang/Object."<init>":()V
   4:   return

public Child getChild();
  Code:
   0:   new #16; //class Child
   3:   dup
   4:   invokespecial   #18; //Method Child."<init>":()V
   7:   astore_1
   8:   aload_1
   9:   checkcast   #16; //class Child
   12:  areturn

}

A: When a running program attempts to cast an object reference to another type, the virtual machine must check to see if the type being cast to is the actual class of the referenced object or one of its supertypes. It must perform the same kind of check when a program performs an instanceof operation.
In either case, the virtual machine must look into the class data of the referenced object. When a program invokes an instance method, the virtual machine must perform dynamic binding: it must choose the method to invoke based not on the type of the reference but on the class of the object. To do this, it must once again have access to the class data given only a reference to the object.
Edit:
Java compiler is not responsible for checking if the casting is correct or not, just like some of the bindings only occur at run time. Java virtual machine does the checking at run time to find out whether the actual reference object is a legitimate object of the new type. If not, there will be a runtime exception: ClassCastException.

A: I'd guess it's done in both stages. At compile time, the compiler will force you to do the right casts to ensure you didn't mix up the types, as in any strongly typed language.
If you however cast an Object you got, say, as a parameter into String (which will work for Objects that are actually instanceof String) the JVM will still have to make sure that the implementing class of Object truly extends or is String and you will get  a ClassCastException if it isn't.

A: For the conversions that don't require a test at run-time, it may be possible that the compiler make some optimisations to avoid casting at run-time.
I suggest to read the JLS Chapter 5. Conversions and Promotions to know more about the type of conversions that need a test at run-time.

Example 5.0-1. Conversions at Compile-time and Run-time

A conversion from type Object to type Thread requires a run-time check to make sure that the run-time value is actually an instance of class Thread or one of its subclasses; if it is not, an exception is thrown.

A conversion from type Thread to type Object requires no run-time action; Thread is a subclass of Object, so any reference produced by an expression of type Thread is a valid reference value of type Object.

A conversion from type int to type long requires run-time sign-extension of a 32-bit integer value to the 64-bit long representation. No information is lost.

A conversion from type double to type long requires a nontrivial translation from a 64-bit floating-point value to the 64-bit integer representation. Depending on the actual run-time value, information may be lost.

5.1.6. Narrowing Reference Conversion :

Such conversions require a test at run-time to find out whether the actual reference value is a legitimate value of the new type. If not, then a ClassCastException is thrown.

5.1.8. Unboxing Conversion ; The conversion proceed at run-time.
Also see : 5.5.3. Checked Casts at Run-time
It's not so easy to determine when the conversion happened for example :
public class Main {

    private static class Child extends Parent{

        public Child() {
        }
    }

    private static class Parent {

        public Parent() {
        }
    }

    private static Child getChild() {
        Parent o = new Child();
        return (Child) o;
    }

    public static void main(final String[] args) {
        Child c = getChild();
    }
}

The result given by javap -c Main is :
public class Main extends java.lang.Object{
public Main();
Code:
0:  aload_0
1:  invokespecial   #1; //Method java/lang/Object."<init>":()V
4:  return

public static void main(java.lang.String[]);
Code:
0:  invokestatic    #4; //Method getChild:()LMain$Child;
3:  astore_1
4:  return

}

If you change the method declaration to public static Child getChild() the result is :
public class Main extends java.lang.Object{
public Main();
Code:
0:  aload_0
1:  invokespecial   #1; //Method java/lang/Object."<init>":()V
4:  return

public static Main$Child getChild();
Code:
0:  new #2; //class Main$Child
3:  dup
4:  invokespecial   #3; //Method Main$Child."<init>":()V
7:  astore_0
8:  aload_0
9:  checkcast   #2; //class Main$Child
12: areturn

public static void main(java.lang.String[]);
Code:
0:  invokestatic    #4; //Method getChild:()LMain$Child;
3:  astore_1
4:  return

}

You see that just changing the accessor, can impact a lot on the possible optimisations.

A: When I compiled
public class Test {
    public Child getChildVersion1() {
        Parent o = new Child();
        return (Child) o;
    }
    public Child getChildVersion2() {
        return new Child();
    }
}

and decompiled that code using javap -c Test at Java 7 (Windows 7 64bit) it gave me this result
Compiled from "Test.java"
public class Test {
  public Test();
    Code:
       0: aload_0
       1: invokespecial #1                  // Method java/lang/Object."<init>":()V
       4: return

  public Child getChildVersion1();
    Code:
       0: new           #2                  // class Child
       3: dup
       4: invokespecial #3                  // Method Child."<init>":()V
       7: astore_1
       8: aload_1
       9: checkcast     #2                  // class Child
      12: areturn

  public Child getChildVersion2();
    Code:
       0: new           #2                  // class Child
       3: dup
       4: invokespecial #3                  // Method Child."<init>":()V
       7: areturn
}

So it seams that compiler didn't optimize method getChildVersion1 to be like getChildVersion2 so beside checking type while compilation time there is also checking at runtime ( 9: checkcast     #2 ). But as Stephen C mentioned it may be related to platform (OS, Java version).


text:
Q: OpenMDAO and NSGA II I found some interesting code in openmdao\drivers\tests\test_pyoptsparse_driver.py that seems to reference NSGA-II. I noticed that this is not implemented when I tried running the test code.
import sys
import copy
import unittest
sys.path.insert(0,r"[SOMEPATH Here]\GitHub\OpenMDAO")
from distutils.version import LooseVersion

import numpy as np

import openmdao.api as om
from openmdao.test_suite.components.paraboloid import Paraboloid
from openmdao.test_suite.components.expl_comp_array import TestExplCompArrayDense
from openmdao.test_suite.components.sellar import SellarDerivativesGrouped

# from openmdao.utils.assert_utils import assert_near_equal # NOTE: THIS FUNCTION ISN'T AVAILABLE IN THE PIP INSTALL
from openmdao.utils.general_utils import set_pyoptsparse_opt, run_driver
from openmdao.utils.testing_utils import use_tempdirs
from openmdao.utils.mpi import MPI

_, local_opt = set_pyoptsparse_opt('NSGA2')
if local_opt != 'NSGA2':
    raise unittest.SkipTest("pyoptsparse is not providing NSGA2")  # CODE BASICALLY FAILS HERE

Error that I am seeing:
"pyoptsparse is not providing NSGA2"
Can I add NSGA 2 if it's not available?

A: when that test was written, NSGA-II was a little difficult to compile with pyoptsparse. I think there are still some challenges with it, but it mostly works now. As of OpenMDAO V3.0 we're not using NSGA-II for anything internally. But if you get it to work, feel free to send a PR with an updated test!


text:
Q: How to make Windows 10 start menu entries backed by the file system get re-indexed and shown ALL? In contrast to former versions of Windows, the start menu of Windows 10 is not entirely and directly based on a directory structure anymore. Instead, there's a process reading those directories under certain circumstances and writing entries into some intermediate database, from which the content of the start menu is then build. The reading process as well as the intermediate database have certain limitations, like only 500 entries at all in the past, entries not being updated regularly or at all or soon enough etc. In fact, this process is very fragile and there are a lot of problems associated with it.
A new Start menu, not necessarily a better one
How to fix / refresh start menu in Windows 10? How to add / remove / edit items in bulk?
Some Win32 apps missing from Start menu "All Programs" list and search
I'm running into one of those problems right now: There's one folder successfully shown in the start menu, most likely because the associated app installed itself per user. Though, the installer created two links in that folder, while only one is shown and when adding an additional one manually, that never shows at all. I've tried to add some new directories with some additional new links etc. as well and none of those showed at all.

In the above screenshot one can see that the start menu only shown one link within the directory Zoom, while at least the additional link to uninstall has been available right from the start. The one named Mittwochsrunde has been added by me weeks ago already and doesn't show yet as well.
Though, it's not that all changes are ignored always: When I hide the directory Zoom using file system attributes, the directory is hidden in the start menu as well. When I change to show again, the entry in the start menu is there again. What doesn't work even after hiding/showing is that the additional links will be shown in the start menu. Of course all other Voodoo one can read about somewhere like deleting the index of Windows Search etc. doesn't help as well, did that multiple times already.
OTOH, there needs to be some way to add start menu entries because I installed Visual Studio 2022 yesterday and all of those entries are visible in the start menu. So I guess the problem is the process mentioned above reading the file system vs. providing entries in the start menu using some installer and API.
So, is there any way to make the underlying process/database of the start menu reliably re-index the file system objects like directories and files?
Thanks!


text:
Q: A real function compose a harmonic function is harmonic iff it is linear
Let $u$ be a harmonic function on region $D$, $\phi$ is r a real function on $u(D)$. Prove that $\phi \circ u$ is harmonic on $D$ iff $\phi$ is linear.

I have tried to write an analytic function $f$ with $u$ be its real part and tried to find some properties of $\phi \circ f$. Does this approach correct? What else should I do? Thanks for any help.

A: We obtain
$$g_{xx}=\dfrac{d^2\phi}{du^2}.\left(\dfrac{\partial u}{\partial x}\right)^2+\dfrac{d\phi}{du}.\dfrac{\partial^2u}{\partial x^2}$$
$$g_{yy}=\dfrac{d^2\phi}{du^2}.\left(\dfrac{\partial u}{\partial y}\right)^2+\dfrac{d\phi}{du}.\dfrac{\partial^2u}{\partial y^2}$$
then $g=\phi o u$ is harmonic iff $g_{xx}+g_{yy}=0$ iff
$$\dfrac{d^2\phi}{du^2}.\left(\dfrac{\partial u}{\partial x}\right)^2+\dfrac{d\phi}{du}.\dfrac{\partial^2u}{\partial x^2}
+
\dfrac{d^2\phi}{du^2}.\left(\dfrac{\partial u}{\partial y}\right)^2+\dfrac{d\phi}{du}.\dfrac{\partial^2u}{\partial y^2}=0$$
iff (since $u$ is harmonic)
$$\dfrac{d^2\phi}{du^2}[\left(\dfrac{\partial u}{\partial x}\right)^2+\left(\dfrac{\partial u}{\partial y}\right)^2]=0$$
iff
$\phi$ be linear.


text:
Q: using tail to follow a log and execute a command instantly? Only seems to work by starting a new line I am trying to figure out a command which will enable me to read a log file in real time and execute a command when the string matches?  I am using logkeys and trying to make it when I type a word it immediately triggers a command. This script works, but only when I press enter (start a newline) does it execute, and it seems anything I have found online also requires the press of the enter key to work.  Is there a way to get around this somehow?
#/bin/bash
echo Waiting...
string='test'
tail /path/to/logfile -n0 -f | while read line; do
        if [[ $line =~ $string ]]; then
                echo "hello"
        fi
done

A: I've played with buffering settings to no avail, so my conclusion is that read waits for a newline before it finishes. If you instead did read -n1, read would read exactly one character, which isn't quite what we want either, because then $line would always be just that one char.
Unfortunately, grep appears to have the same behavior (even with buffering options changed), even with grep -o:
$ tail logfile -f -n0 | grep -o test &
[1] 25524
$ echo -n test >> logfile
$ echo -n test >> logfile
$ echo test >> logfile
test
test
test

I think the general solution would be to roll our own "ring buffer grep" search tool that reads character per character into a ring buffer.
Here's my perl version of that, hope it helps. (Save as: ringgrep.pl)
#!/usr/bin/perl -w

use strict;

if (!$ARGV[0]) {
    print "Usage: $0 needle\n";
    exit 1;
}
my $needle = $ARGV[0];
my $buffer_len = length($needle);
my @buffer = (0) x $buffer_len;
my $i = 0;
my $input;

while(sysread(STDIN, $input, 1)) {
    $buffer[$i] = $input;
    my $string = join("", @buffer);
    $string = (($i+1)%$buffer_len == 0 ? "" : substr($string, $i-$buffer_len+1)) . substr($string, 0, $i+1);
    # print "string is: $string\n";
    if ($string =~ /$needle/) {
        print "got test!\n";
        @buffer = (0) x $buffer_len;
        $i = 0
    } else {
        $i = (++$i) % $buffer_len
    }
}

Usage:
$ chmod +x ringgrep.pl
$ tail logfile -n0 -f | ./ringgrep.pl "this is a test" &
[1] 25756
$ echo -n "test" >> logfile
$ echo -n "test" >> logfile
$ echo -n "test" >> logfile
$ echo -n "test" >> logfile
$ echo -n "this is a test" >> logfile
got test!
$ echo -n "this is a test" >> logfile
got test!
$ echo -n "this is a test" >> logfile
got test!
$ (echo -n t; echo -n h; echo -n i; echo -n s; echo -n ' '; echo -n i; echo -n s; echo -n ' '; echo -n a; echo -n ' '; echo -n t; echo -n e; echo -n s; echo -n t) >> logfile
got test!


text:
Q: How to run "TS" code snippets in ts-node? In Solana docs they use a lot of TS code snippets, for example in the below link (the first code snippet) should run and return a value:
https://solanacookbook.com/guides/get-program-accounts.html#filters
I tried to  run the first snippet using: ts-node file.ts
but I got this error:
    return new TSError(diagnosticText, diagnosticCodes);
           ^
TSError: ⨯ Unable to compile TypeScript:
index.ts:33:26 - error TS7053: Element implicitly has an 'any' type because expression of type '"parsed"' can't be used to index type 'Buffer | ParsedAccountData'.
  Property 'parsed' does not exist on type 'Buffer | ParsedAccountData'.

33     console.log(`Mint: ${account.account.data["parsed"]["info"]["mint"]}`);
                            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
index.ts:35:18 - error TS7053: Element implicitly has an 'any' type because expression of type '"parsed"' can't be used to index type 'Buffer | ParsedAccountData'.
  Property 'parsed' does not exist on type 'Buffer | ParsedAccountData'.

35       `Amount: ${account.account.data["parsed"]["info"]["tokenAmount"]["uiAmount"]}`
                    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    at createTSError (/usr/local/lib/node_modules/ts-node/src/index.ts:750:12)
    at reportTSError (/usr/local/lib/node_modules/ts-node/src/index.ts:754:19)
    at getOutput (/usr/local/lib/node_modules/ts-node/src/index.ts:941:36)
    at Object.compile (/usr/local/lib/node_modules/ts-node/src/index.ts:1243:30)
    at Module.m._compile (/usr/local/lib/node_modules/ts-node/src/index.ts:1370:30)
    at Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Object.require.extensions.<computed> [as .ts] (/usr/local/lib/node_modules/ts-node/src/index.ts:1374:12)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12) {
  diagnosticText: `\x1B[96mindex.ts\x1B[0m:\x1B[93m33\x1B[0m:\x1B[93m26\x1B[0m - \x1B[91merror\x1B[0m\x1B[90m TS7053: \x1B[0mElement implicitly has an 'any' type because expression of type '"parsed"' can't be used to index type 'Buffer | ParsedAccountData'.\n` +
    "  Property 'parsed' does not exist on type 'Buffer | ParsedAccountData'.\n" +
    '\n' +
    '\x1B[7m33\x1B[0m     console.log(`Mint: ${account.account.data["parsed"]["info"]["mint"]}`);\n' +
    '\x1B[7m  \x1B[0m \x1B[91m                         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\x1B[0m\n' +
    `\x1B[96mindex.ts\x1B[0m:\x1B[93m35\x1B[0m:\x1B[93m18\x1B[0m - \x1B[91merror\x1B[0m\x1B[90m TS7053: \x1B[0mElement implicitly has an 'any' type because expression of type '"parsed"' can't be used to index type 'Buffer | ParsedAccountData'.\n` +
    "  Property 'parsed' does not exist on type 'Buffer | ParsedAccountData'.\n" +
    '\n' +
    '\x1B[7m35\x1B[0m       `Amount: ${account.account.data["parsed"]["info"]["tokenAmount"]["uiAmount"]}`\n' +
    '\x1B[7m  \x1B[0m \x1B[91m                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\x1B[0m\n',
  diagnosticCodes: [ 7053, 7053 ]
}

Am I doing this correctly?

A: You're running it correctly from what I can tell. Looks like there was one issue with the code on compatibility with Typescript. account.account.data is of type Buffer | ParsedAccountData.
If you set it like the code below, it will run successfully:
import { TOKEN_PROGRAM_ID } from "@solana/spl-token";
import { ParsedAccountData } from "@solana/web3.js";
import { clusterApiUrl, Connection } from "@solana/web3.js";

(async () => {
  const MY_WALLET_ADDRESS = "FriELggez2Dy3phZeHHAdpcoEXkKQVkv6tx3zDtCVP8T";
  const connection = new Connection(clusterApiUrl("devnet"), "confirmed");

  const accounts = await connection.getParsedProgramAccounts(
    TOKEN_PROGRAM_ID, // new PublicKey("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA")
    {
      filters: [
        {
          dataSize: 165, // number of bytes
        },
        {
          memcmp: {
            offset: 32, // number of bytes
            bytes: MY_WALLET_ADDRESS, // base58 encoded string
          },
        },
      ],
    }
  );

  console.log(
    `Found ${accounts.length} token account(s) for wallet ${MY_WALLET_ADDRESS}: `
  );
  accounts.forEach((account, i) => {
    console.log(
      `-- Token Account Address ${i + 1}: ${account.pubkey.toString()} --`
    );
    console.log(`Mint: ${(account.account.data as ParsedAccountData)["parsed"]["info"]["mint"]}`);
    console.log(
      `Amount: ${(account.account.data as ParsedAccountData)["parsed"]["info"]["tokenAmount"]["uiAmount"]}`
    );
  });
  /*
    // Output

    Found 1 token account(s) for wallet FriELggez2Dy3phZeHHAdpcoEXkKQVkv6tx3zDtCVP8T:
    -- Token Account Address 1: Et3bNDxe2wP1yE5ao6mMvUByQUHg8nZTndpJNvfKLdCb --
    Mint: BUGuuhPsHpk8YZrL2GctsCtXGneL1gmT5zYb7eMHZDWf
    Amount: 3
  */
})();


text:
Q: Is there a way to check if Ethernet specifically is connected (even when WIFI is also connected)? Using the connection manager it's easy enough to see if there is a connection, however if both Ethernet and WIFI are connected at the same time it always seems to report that WIFI is connected.
I want to know if I have a connection, but also what specifically is connected. E.g. Ethernet only? Ethernet and WIFI? WIFI only? Nothing?
Is this possible in Android?
I have an app that needs to preference Ethernet (at which point it needs to disable WIFI) but use WIFI if Ethernet isn't available (as a backup).
I can get it to work on network change events but not when both are connected on app startup - in that case it doesn't know to disconnect WIFI.
Edit: not really a solution to the question but I've gotten around it by essentially turning the WIFI off to check for Ethernet and then turning it back on again (if it was on before). Not ideal but it's the only option as far as I know.


text:
Q: Inequality between Holevo capacity and coherent information of quantum channels Let $\mathcal{N} : M_n \to M_n$ be a unital quantum channel (hence trace preserving and completely positive).
Do we have the inequality $Q^{(1)}(\mathcal{N}) \leq \chi(\mathcal{N})$ ?
Here $\chi(\mathcal{N})$ is the Holevo capacity (or Holevo information) of $T$ and $Q^{(1)}(\mathcal{N})$ is the coherent information of $\mathcal{N}$.
I ask this question since I know that $Q(\mathcal{N}) \leq C(\mathcal{N})$ where $Q(\mathcal{N})$ and $C(\mathcal{N})$ are the regularized version of $Q^{(1)}(\mathcal{N})$ and $\chi(\mathcal{N})$.


text:
Q: ROR3: Why is this not saving? This functionality used to work but has suddenly stopped and I have no idea why. I've made changes before I ran the tests but, having retraced my steps I don't know what has changed. Can a fresh pair of eyes tell me why this is saving the posts but not the locations?
Model Post.rb
class Post < ActiveRecord::Base
 attr_accessible :title, :body, :tag_list, :locations_attributes
 has_and_belongs_to_many :locations
 accepts_nested_attributes_for :locations, :reject_if => :all_blank
end

*Controller Posts_controller.rb *
class PostsController < ::Blogit::ApplicationController

...

def new
  @post = current_blogger.blog_posts.new(params[:post])
  @location = @post.locations.build
end

def update
  @post = current_blogger.blog_posts.find(params[:id])
  if @post.update_attributes(params[:post])
    redirect_to @post, notice: 'Blog post was successfully updated.'
  else
    render action: "edit"
  end
end

def create
  @post = current_blogger.blog_posts.new(params[:post])
  if @post.save
    redirect_to @post, notice: 'Blog post was successfully created.'
  else
    render action: "new"
  end
end

end

*View _form.html.erb*
<%= nested_form_for(@post, :html=> {:multipart => true, :class=> "new_blog_post", :id=> "new_blog_post"}) do |f| %>

 ...

<%= field do %>
  <%= f.text_field :title, placeholder: "Give your post a title", :class=>"span12" %>
<% end %>
<%= field do %>
  <%= f.text_area :body, placeholder: "Write something here...", :id=>"blog-text", :class=>"span12" %>
 <% end %>

<%= field id: "new_blog_post_tag_field" do %>
  <%= f.label :tag_list, "Tags" %>
  <%= f.text_field :tag_list, placeholder: "tag one, tag two, etc..." %>
<% end %>

<%= f.label :search_locations, "Add locations to your post" %>
   <%= render :partial => 'search_locations', :locals => { :f => f }  %>

<%= f.link_to_add "Add a location", :locations %>

<%= actions do %>
<%= f.submit "Submit", :class=>"btn", :disable_with => 'Uploading Image...' %> or
<%= link_to("cancel", @post.new_record? ? root_path : post_path(@post)) %>

<% end %>

<% end %>

*Form Partial _search_locations.html.erb*
 <%= f.fields_for :locations do |m| %>

 <%= m.text_field :name,:class=>"localename", :id=>"appendedInput", :placeholder=> "Name of the location", :autocomplete => "off" %>

 <%= m.link_to_remove do %><%end%>

 <% end %>

And the actual submission in the logs comes up as this:
Started PUT "/blog/posts/51-hong-kong" for 127.0.0.1 at 2012-11-06 17:41:00 +0000
Processing by Blogit::PostsController#update as HTML
Parameters: {"utf8"=>"✓",
"authenticity_token"=>"s+2117Qi/HzO/D/ORINhqHChMJR3S5XK7y/s3rq3dnc=", "post"=>{"title"=>"Hong
Kong ", "body"=>"Lorem ipsum dolor sit amet, consectetur adipiscing elit. In orci elit,
rhoncus quis interdum vel, interdum non nulla. Phasellus nec massa lorem. Duis malesuada
pellentesque orci, accumsan mollis augue aliquam mollis. Pellentesque luctus orci in enim
hendrerit adipiscing. Mauris tempor tortor in leo posuere tristique.", "tag_list"=>"",
"locations_attributes"=>{"0"=>{"_destroy"=>"false",
"name"=>"London","longitude"=>"-0.1276831", "latitude"=>"51.5073346"}}},
"_wysihtml5_mode"=>"1", "name"=>"London", "legname"=>"London", "longitude"=>"-0.1276831",
"latitude"=>"51.5073346", "commit"=>"Submit", "id"=>"51-hong-kong"}

Why is this saving the post but not the locations info?

A: You don't have a fields_for, try replace:
<%= render :partial => 'search_locations', :locals => { :f => f }  %>

<%= f.link_to_add "Add a location", :locations %>

<%= actions do %>
<%= f.submit "Submit", :class=>"btn", :disable_with => 'Uploading Image...' %> or
<%= link_to("cancel", @post.new_record? ? root_path : post_path(@post)) %>

With:
<% f.fields_for :locations do |location| %>
  <%= render :partial => 'search_locations', :locals => { :f => location }  %>
<% end %>

<%= f.submit "Submit", :class=>"btn", :disable_with => 'Uploading Image...' %> or
<%= link_to("cancel", @post.new_record? ? root_path : post_path(@post)) %>

A: Solved it, it was a stray bit of code in the model.
Thanks for all your help!


text:
Q: Modal shows the content of html instead of its own content I don't get why the modal is showing my html's body content when I submit an input instead of the result of php.
I tried debugging it,then i found out that the modal shows its own content when I add data-toggle and data-target to the input/form, but the problem is that the modal shows after I click on the input even before I can even type something,and even I managed to type something, the same problem still exists
Here's the form:
<form id="form_id" action="some_php.php" method="POST">
    <input id="input_id" type="text" name="input_name">
</form>

Here's the script:
$(document).ready(function()
{
    $("#form_id").submit(function(e)
    {
        e.preventDefault();
        $.ajax({
            type: 'POST',
            data: $("form_id").serialize(),
            url: 'some_php.php',
            success: function(data) {
                $("#fetched-data").html(data);
                $("#myModal").show('show');
            }
        });
        return false;
    });
});


text:
Q: Julia: best way to sample from successively shrinking range? I would like to sample k numbers where the first number is sampled from 1:n and the second from 1:n-1 and the third from 1:n-2 and so on.
I have the below implementation
function shrinksample(n,k)
    [rand(1:m) for m in n:-1:n-k+1]
end

Are there faster solutions in Julia?

A: The following takes ideas from the implementation of randperm and since n and k are of the same order, this is appropriate as the same type of randomness is needed (both have output space of size n factorial):
function fastshrinksample(r::AbstractRNG,n,k)
    a = Vector{typeof(n)}(k)
    @assert n <= Int64(2)^52
    k == 0 && return a
    mask = (1<<(64-leading_zeros(n)))-1
    nextmask = mask>>1
    nn = n
    for i=1:k
        a[i] = 1+Base.Random.rand_lt(r, nn, mask)
        nn -= 1
        if nn == nextmask
            mask, nextmask = nextmask, nextmask>>1
        end
    end
    return a
end

fastshrinksample(n,k) = fastshrinksample(Base.Random.GLOBAL_RNG, n, k)

Benchmarking gives a 3x improvement for one tested instance:
julia> using BenchmarkTools

julia> @btime shrinksample(10000,10000);
  310.277 μs (2 allocations: 78.20 KiB)

julia> @btime fastshrinksample(10000,10000);
  91.815 μs (2 allocations: 78.20 KiB)

The trick is mainly to use the internal Base.Random.rand_lt instead of regular rand(1:n)

A: If this is not very sensitive to randomness (you're not doing cryptography), the following should be amazingly fast and very simple:
blazingshrinksample(n,k) = (Int)[trunc(Int,(n-m)rand()+1) for m in 0:k-1]

Testing this along with your implementation and with Dan's, I got this:
using BenchmarkTools

@btime shrinksample(10000,10000);
  259.414 μs (2 allocations: 78.20 KiB)

@btime fastshrinksample(10000,10000);
  66.713 μs (2 allocations: 78.20 KiB)

@btime blazingshrinksample(10000,10000);
  33.614 μs (2 allocations: 78.20 KiB)


text:
Q: Solve $n$th order determinant Solve $n$th order determinant:
$$
    \begin{pmatrix}
    1 & 2 & 3 & \cdots & n-2 & n-1 &n\\
    2 & 3 & 4 & \cdots & n-1& n& 1\\
    3 & 4 & 5 & \cdots & n &1 &2\\
    \vdots& \vdots& \vdots& \ddots& \vdots& \vdots&\vdots\\
    n-2 &n-1&n &\cdots &n-5 &n-4 &n-3\\
    n-1 &n&1 &\cdots &n-4 &n-3 &n-2\\
    n &1&2 &\cdots &n-3 &n-2 &n-1\\
    \end{pmatrix}
$$
I tried adding $2$nd to $n$th row to the $1$st row, then the first row is:
$$
   \begin{pmatrix}
   \frac{n(n+1)}{2} &\frac{n(n+1)}{2} \cdots \frac{n(n+1)}{2}\\
   \end{pmatrix}
$$
then I took out $\frac{n(n+1)}{2}$ from the first row to get
$$
   \begin{pmatrix}
   1 & 1 & \cdots& 1\\
   \end{pmatrix}
$$
and then tried to work with that but I don't think this is the correct approach because anything I tried doesn't look nice.

A: This is a circulant matrix, where one can show the following formula for its determinant:
Determinant of circulant matrix
For
$$
A=\begin{pmatrix}
a_1 & a_2 & a_3 & \cdots & a_n\\
a_2 & a_3 & a_4 & \cdots & a_1\\
a_3 & a_4 & a_5 & \cdots & a_2\\
\vdots & \vdots & \vdots & \ddots & \vdots\\
a_n & a_1 & a_2 & \cdots & a_{n-1}\\
\end{pmatrix}
$$
we have
$$
\det (A) = (-1)^{\left\lfloor\frac{n}{2}\right\rfloor}\prod_{j=0}^{n-1}\left(a_n + \sum_{k=1}^{n-1} a_k\omega_j^k\right),
$$
where $\omega_j=e^{\frac{2\pi i j}{n}}$.
In our case it is
$$
(-1)^{n - 1}n^{n - 2}(n^2 + n)/2,
$$
see OEIS, and
Interesting determinant problem

A: Let us denote by  $A$ the matrix corresponding to the determinant we have to compute.
Our objective is to show that :

$$\tag{*}\det(A)=(-1)^{n-1}n^{n-2}\dfrac{n(n + 1)}{2}$$

As $C:=A^T$ is circulant, we can use the following result : (https://en.wikipedia.org/wiki/Circulant_matrix), (http://www.math.columbia.edu/~ums/pdf/cir-not5.pdf):

A $n \times n$ circulant matrix $C$ is diagonalizable under the form
$$C=F_n^{−1}DF_n$$
where $F_n$ is the $n$-th order matrix of DFT (Discrete Fourier Transform) with general term $\omega^{k\ell}$ where $\omega:=e^{-\tfrac{2 i \pi}{n}}.$
Moreover if we denote by $\lambda_k$ the entries $D_{kk}$ of diagonal matrix $D$, with $V=(\lambda_1, \lambda_2, ... \lambda_n)^T$, $V$ is the DFT of the first column $(1,2,...n)^T$ of $C$ , i.e,

$$\begin{pmatrix}\lambda_1\\ \lambda_2\\ \vdots \\ \vdots \\ \lambda_n\end{pmatrix}=\underbrace{\begin{pmatrix}\omega^{0 \times 0}&&\cdots&&\omega^{(n-1)0}\\ &&&& \\ &&\omega^{k \ell}&&\\ &&&&\\ \omega^{0(n-1)}&&\cdots&&\omega^{(n-1)(n-1)}\end{pmatrix}}_{\text{DFT matrix} \ \ F_n}\begin{pmatrix}1\\2\\ \vdots \\ \vdots \\ n\end{pmatrix}$$
Thus:
$$\tag{1}\det(C)=\det(D)=\prod_{k=1}^n \lambda_k=\prod_{k=0}^{n-1} p(\omega^k),$$
where polynomial $p$ is defined by
$$p(x):=1+2x+3x^2+4x^3+...+nx^{n-1}=q'(x)$$
$$\text{with} \ \ q(x):=1+x+x^2+\cdots+x^n=\dfrac{1-x^{n+1}}{1-x}$$
As an immediate consequence :
$$\tag{2}\text{if} \ x \neq 1, \ p(x)=q(x)'=\dfrac{nx^{n+1}-(n+1)x^n+1}{(1-x)^2}.$$
In (1), let us treat separately the case $k=0$:
$$p(\omega^0)=p(1)=1+2+3+\cdots+n=\dfrac{n(n+1)}{2}$$
Concerning the general case, using (2):
$$\tag{3}\text{for} \ k=1,2,... (n-1): \ \
p(\omega^k)= \dfrac{n(\omega^k-1)}{(\omega^k-1)^2}=n\dfrac{1}{\omega^k-1}$$
(because any $n$th root of unity at power $n$ is equal to $1$.)
As a consequence
$$\prod_{k=1}^{n-1} p(\omega^k)=n^{n-1}\prod_{k=1}^{n-1}\dfrac{1}{\omega^k-1}$$
In view of objective (*), it remains to prove that
$$\tag{4}\prod_{k=1}^{n-1}(\omega^k-1)=(-1)^{n-1}n.$$
This will be done by considering $r$ defined by
$$\tag{5}r(x):=1-x^n=(1-x)s(x) \ \text{with} \ \ s(x):=1+x+x^2+\cdots +x^{n-1}$$
But the roots of $s$ are the $\omega^k$ for $k=1\cdots (n-1)$ ; thus, the factorized form of $s$ is:
$$\tag{6}s(x)=\prod_{k=1}^{n-1}(x-\omega^k)$$
Setting $x=1$ in (6) and (5) resp. gives  (4).
Remark: This proof is different from the direct proofs using lines and columns manipulations. Its interest lies in the facts that

*

*it is based on mathematics (circulant matrices, Fourier Transform, $n$th roots of unity) that are beyond "tricks of the trade".

*it explains in particular why we have factors $\dfrac{n(n+1)}{2}$ and $n^{n-2}$ in the result.

A: With the help of WA, we get this sequence
$$
1, -3, -18, 160, 1875, -27216, -470596, \dots
$$
oeis/A052182 tells us that the determinant is $(-1)^{n-1}n^{n-2}\dfrac{(n^2 + n)}{2}$, except for the sign.


text:
Q: Trend line for TS and using smoothing with mice I have a time Series data like
patients: 100, 200, 300,...,10, 5,...,120
Month:     1,  2 ,  3 ..., 12, 1,...,12
Year:     2006,2006,2006,...,2006,2007,..,2007

Like this I have data till 2010, I need to predict patients for 2011
I wanted to check for the trend in the data, so I used below ggplot to plot the trend line.  When I used only "geom_smooth()" I got a
   exponential curve line based on loose() and when I use
   geom_smooth(method="lm"). I got a straight line. My question is which one is correct?.
A. I have TS and from both the graphs I see I only have a trend and no seasonality(which is correct). For fitting TS data which one is correct?

ggplot(data,aes(x= Year,y=Incoming.Examinations))+ geom_point(aes(color=Month))+
    geom_smooth() #geom_smooth(method="lm")

imputed<- mice(data)
imputed$imp
fit <- with(imputed,ets(Incoming.Examinations,model="AAN"))
#fit <- pool(fit)
fit
completedData<-complete(imputed,4)
fit<-ets(completedData$ts,model="AAN")
y<-predict(fit,n.ahead=15)

B. I had missing values in the "patients",so, I used mice package to impute the missing values. As I only have trend, I decided to use Double exponential smoothing in
with(imputed,ets(Incoming.Examinations,model="AAN"))

using ets(). Now, the problem is
fit <- pool(fit)

gives me an error

Error: No glance method for objects of class ets

looks like pool works only with lm, glm in with(). B.1 How do I fix this?
B.2 As a work around,I dumped fit and checked all the results and picked the dataset 4 with low AIC and predicted the output. is this right thing to do?
or is it mandatory to use the pool(fit) and then make a decision?

A: For A, you can simply use RMSE to compare both trend lines to see which one has the smaller RMSE. Obviously by looking at the graph, the trend line produced by loose() option should be the better one.


text:
Q: Webos LG TV cant see hebrew fonts webos application with a button and text in Hebrew,
i can see just symbols and not the text
Currently the application only includes a button and a link for test
the TV (LG) webos version is 4.9.7-15
tried adding "font-family:arial;" and "    font-family:Google Sans,Roboto,Helvetica,ariali,sans-serif;
"
but it did not help :-(

<!DOCTYPE html>
<html>

<head>
    <title>new app</title>
    <style type="text/css">
        body {
            width: 100%;
            height: 100%;
            background-color: #202020;
        }

        div {
            position: absolute;
            height: 100%;
            width: 100%;
            display: table;
        }

        h1 {
            display: table-cell;
            vertical-align: middle;
            text-align: center;
            color: #FFFFFF;
        }

 button{
       top:10%;
       left:5%;
       width:100px;
       height:50px;
       position: absolute;
       z-index: 2;
       text-align: center;
       vertical-align: middle;
       horizontal-align: center;
       line-height: 50px;
       background: green;
       font-family:arial;
       }

    </style>
</head>

<script src="webOSTVjs-1.2.4/webOSTV.js" charset="utf-8"></script>
<script src="webOSTVjs-1.2.4/webOSTV-dev.js" charset="utf-8"></script>
<script type="text/javascript">
    //sample code for calling LS2 API
    webOS.service.request("luna://com.palm.systemservice", {
        method: "clock/getTime",
        parameters: {},
        onSuccess: function (args) {
            console.log("UTC:", args.utc);
        },
        onFailure: function (args) {
            console.log("Failed to getTime");
        }
    });
</script>

<body>
    <div>
        <button onclick="window.location.href='http://192.168.0.17:8080/Garden_on';">
        גינה אור
        </button>

    </div>
</body>

</html>

A: I had a similar experience, testing in the simulator and on my TV.
My code programmatically generates buttons with Hebrew titles, and they all showed Giberish.

However, when I any changed the title of the page to Hebrew or added any Hebrew text directly into the HTML, it worked.


text:
Q: Create Cube & Dimension from SharePoint 2010 List I want to Create cube and dimension from SharePoint List and want to generate result using MDX on SharePoint List, so Please anyone can guide me how to import SharePoint 2010 List directly to SSAS ?
Please note : I don't want to use Custom Database e.g. import data from SharePoint List to Custom Database using SSIS using example of URL which are below.
http://dataqueen.unlimitedviz.com/2011/06/how-to-use-a-sharepoint-list-as-a-data-source-in-your-ssis-package/
http://sqlsrvintegrationsrv.codeplex.com/releases/view/17652
http://slam.codeplex.com/
Thanks In Advance

A: You are mentioning "import" so by definition it means taking data over. On the other hand, except for the SSIS packages, I personally haven't heard of a capacity of SSAS to be able to define cube on volatile data - e.g. real-time feeds (but again, maybe I'm wrong!)
Are you aware that SharePoint server also has its own tools for business-intelligence, which allow direct building KPI, scorecards and dashboard with SharePoint lists? Have you looked at using PerformancePoint designer to directly build BI solutions ?
Did you tried also using PowerPivot (http://technet.microsoft.com/en-us/library/gg413413.aspx), but in the context of a SharePoint ?


text:
Q: no puedo enviar email con php estoy intentando enviar mi formulario por email, pero no lo consigo, he creado la función mail(), pero no me envía el correo. Adjunto código.
//Definición de variables
    $asociacion = $_POST['asociacion'];
    $nick = $_POST['jug_nickname'];
    $nombre = $_POST['jug_nombre'];
    $apellidos = $_POST['jug_apellidos'];
    $dni = $_POST['jug_dni'];
    $fechaNacimiento = $_POST['jug_fec_nac'];
    $email = $_POST['jug_e_mail'];;
    $telefono = $_POST['jug_telefono'];
    $duracion = $_POST['duracion_seguro'];
    //$comprobar_dni = comprobar_documento_identificacion($dni);

//PASAMOS A MAYÚSCULAS
$tmy3 = strtoupper($nick);
$tmy3 = strtr($tmy3, "áéíóúÁÉÍÓÚ", "AEIOUAEIOU");

$tmy2 = strtoupper($nombre);
$tmy2 = strtr($tmy2, "áéíóúÁÉÍÓÚ", "AEIOUAEIOU");

$tmy2_2 = strtoupper($apellidos);
$tmy2_2 = strtr($tmy2_2, "áéíóúÁÉÍÓÚ", "AEIOUAEIOU");

//Compongo el cuerpo
    //$cuerpo = "Formulario enviado ".$comprobar_dni."\n";
    $cuerpo  = "Asociación que comunica el Alta....: ".$asociacion."\n";
    $cuerpo .= "Nickname o Apodo del Jugador....: ".$nick."\n";
    $cuerpo .= "Nombre del Jugador......: ".$nombre."\n";
    $cuerpo .= "Apellidos del Jugador......: ".$apellidos."\n";
    $cuerpo .= "D.N.I. del Jugador....: ".$dni."\n";
    $cuerpo .= "Fecha de Nacimiento del Jugador....: ".$fechaNacimiento."\n";
    $cuerpo .= "E-Mail del Jugador....: ".$email."\n";
    $cuerpo .= "Teléfono del Jugador....: ".$telefono."\n";
    $cuerpo .= "Duración del seguro solicitada...: ".$duracion."\n";

//mando el correo's...
//mail("---------","Formulario recibido",$cuerpo);
$para = "daviserraalonso@gmail.com";
$asunto = "Asunto del email";
$mensaje = "Este es mi primer envío de email con PHP";

$correcto = mail($para, $asunto, $mensaje);
if($correcto){
    echo "
Email enviado correctamente
";
}else{
    echo "
Error al enviar el email, contacte con el servicio técnico
";
}

Formulario HTML
<!DOCTYPE html>

    <title>Formulario de Alta PHP</title>

    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>

  <?php
    /*Definición de función para comprobar si el DNI es correcto*/
    function comprobar_documento_identificacion($dni){
        if(strlen($dni)<>9) {
            return "Necesarios 9 dígitos";
        }

        $dni = strtoupper($dni);

        $letra = substr($dni, -1, 1);
        $numero = substr($dni, 0, 8);

        // Si es un NIE hay que cambiar la primera letra por 0, 1 ó 2 dependiendo de si es X, Y o Z.
        $numero = str_replace(array('X', 'Y', 'Z'), array(0, 1, 2), $numero);

        $modulo = $numero % 23;
        $letras_validas = "TRWAGMYFPDXBNJZSQVHLCKE";
        $letra_correcta = substr($letras_validas, $modulo, 1);

        if($letra_correcta != $letra) {
            return "Letra incorrecta, la letra debería ser la $letra_correcta.";
        } else {
            return "DNI o NIE OK";
        }
    }

    //Definición de variables
    $asociacion = $_POST['asociacion'];
    $nick = $_POST['jug_nickname'];
    $nombre = $_POST['jug_nombre'];
    $apellidos = $_POST['jug_apellidos'];
    $dni = $_POST['jug_dni'];
    $fechaNacimiento = $_POST['jug_fec_nac'];
    $email = $_POST['jug_e_mail'];;
    $telefono = $_POST['jug_telefono'];
    $duracion = $_POST['duracion_seguro'];
    $comprobar_dni = comprobar_documento_identificacion($dni);

    /*
        function validar_fecha_espanol($fecha){
            $valores = explode('/', $fecha);
            if(count($valores) == 3 && checkdate($valores[1], $valores[0], $valores[2])){
                return "Fecha OK";
            }else{
                return "Fecha Incorrecta";
            }
        }
    */

?>

        Antes de enviarlo, compruebe que los datos introducidos son correctos,
        Si algun dato no es correcto, puede modificarlo antes de enviarlo.

    <form id="formularioComprobacion" method="post" action="envioEmail.php">
        Asociacion: <input type="text" size="30" id="asociacion" value="<?php echo $asociacion; ?>"/>

        Nick: <input type="text" id="jug_nickname" value="<?php echo $nick; ?>"/>

        Nombre: <input type="text" id="jug_nombre" value="<?php echo $nombre; ?>"/>

        Apellidos: <input type="text" id="jug_apellidos" value="<?php echo $apellidos; ?>"/>

        DNI: <input type="text" id="jug_dni" value="<?php echo $dni; ?>"/>

        Fecha Nacimiento: <input type="text" id="jug_fec_nac" value="<?php echo $fechaNacimiento; ?>"/>

        Email: <input type="text" id="jug_e_mail" value="<?php echo $email; ?>"/>

        Telefono: <input type="text" id="jug_telefono" value="<?php echo $telefono; ?>"/>

        Duracion: <input type="text" id="duracion_seguro" size="30" value="<?php echo $duracion; ?>"/>

        <input type="submit" id="enviar" value="Confirmar"/>
    </form>

        Gracias por utilizar el Servicio de Alta de Federados

    <form name="form3" method="post" action="">

    </form>

Archivo PHP
<?php
/* En este documento, se declara todo lo necesario para el envío del email, con los datos */

    //Definición de variables
        $asociacion = $_POST['asociacion'];
        $nick = $_POST['jug_nickname'];
        $nombre = $_POST['jug_nombre'];
        $apellidos = $_POST['jug_apellidos'];
        $dni = $_POST['jug_dni'];
        $fechaNacimiento = $_POST['jug_fec_nac'];
        $email = $_POST['jug_e_mail'];;
        $telefono = $_POST['jug_telefono'];
        $duracion = $_POST['duracion_seguro'];
        //$comprobar_dni = comprobar_documento_identificacion($dni);

    //PASAMOS A MAYÚSCULAS
    $tmy3 = strtoupper($nick);
    $tmy3 = strtr($tmy3, "áéíóúÁÉÍÓÚ", "AEIOUAEIOU");

    $tmy2 = strtoupper($nombre);
    $tmy2 = strtr($tmy2, "áéíóúÁÉÍÓÚ", "AEIOUAEIOU");

    $tmy2_2 = strtoupper($apellidos);
    $tmy2_2 = strtr($tmy2_2, "áéíóúÁÉÍÓÚ", "AEIOUAEIOU");

    //Compongo el cuerpo
        //$cuerpo = "Formulario enviado ".$comprobar_dni."\n";

        $cuerpo  = "Asociación que comunica el Alta....: ".$asociacion."\n";
        $cuerpo .= "Nickname o Apodo del Jugador....: ".$nick."\n";
        $cuerpo .= "Nombre del Jugador......: ".$nombre."\n";
        $cuerpo .= "Apellidos del Jugador......: ".$apellidos."\n";
        $cuerpo .= "D.N.I. del Jugador....: ".$dni."\n";
        $cuerpo .= "Fecha de Nacimiento del Jugador....: ".$fechaNacimiento."\n";
        $cuerpo .= "E-Mail del Jugador....: ".$email."\n";
        $cuerpo .= "Teléfono del Jugador....: ".$telefono."\n";
        $cuerpo .= "Duración del seguro solicitada...: ".$duracion."\n";

    //mando el correo's...

    $para = "------------";
    $asunto = "Asunto del email";
    $mensaje = "Este es mi primer envío de email con PHP";

    $correcto = mail($para, $asunto, $mensaje);
    if($correcto){
        echo "
Email enviado correctamente
";
    }else{
        echo "
Error al enviar el email, contacte con el servicio técnico
";
    }

?>

a parte de eso, cuando cargo en el navegador este documento, me dice que no tengo los index definidos y no se como solventar este aviso, sin quitarlos del php.ini
gracias, feliz año y un saludo

A: La solución era, subir a un hosting el archivo php, así manda correctamente el email


text:
Q: Data cannot be retrieved for 'DataSet1' dataset enter image description hereData cannot be retrieved for 'DataSet1' dataset.
Error

'An error occurred while processing the report Query Execution Failed
  For Dataset 'DataSet1' , CommandText Property Is Not Initialized '


text:
Q: Jamstack/Nuxt.js: Can I have Vue components inside a json? I know I can use frontmatter-markdown-loader to allow Vue components inside a markdown file. However, is there any similar solution for a scenario where my articles are stored in a JSON?
For example, the following works with frontmatter-markdown-loader:

---
date: 2015-10-21
title: My First Blog Post
---

Who moved my cheese cow mascarpone. Cheese on toast cheese on toast mozzarella bavarian bergkase emmental gouda cheese triangles. Croque monsieur dolcelatte macaroni cheese taleggio parmesan cheese triangles St. Agur blue cheese. Everyone loves cheese.

<cheese-slideshow />

Now, is there any similar solution for a scenario where my articles are stored in a JSON file instead of a .md?


text:
Q: C/C++ hdf5 how to insert data to the end of the DataSet? In HDF5 C/C++ example, there is an example to append/resize data to DataSet by chunk.
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * Copyright by The HDF Group.                                               *
 * Copyright by the Board of Trustees of the University of Illinois.         *
 * All rights reserved.                                                      *
 *                                                                           *
 * This file is part of HDF5.  The full HDF5 copyright notice, including     *
 * terms governing use, modification, and redistribution, is contained in    *
 * the COPYING file, which can be found at the root of the source code       *
 * distribution tree, or in https://www.hdfgroup.org/licenses.               *
 * If you do not have access to either file, you may request a copy from     *
 * help@hdfgroup.org.                                                        *
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

/*
 *  This example illustrates how to create a dataset that is a 4 x 6
 *  array. It is used in the HDF5 Tutorial.
 */

#include <iostream>
using std::cout;
using std::endl;

#include <string>
#include "H5Cpp.h"
using namespace H5;

const H5std_string FILE_NAME("h5tutr_extend.h5");
const H5std_string DATASETNAME("ExtendibleArray");

int
main(void)
{
    hsize_t dims[2]       = {3, 3}; // dataset dimensions at creation
    hsize_t maxdims[2]    = {H5S_UNLIMITED, H5S_UNLIMITED};
    hsize_t chunk_dims[2] = {2, 5};
    int     data[3][3]    = {{1, 1, 1}, // data to write
                      {1, 1, 1},
                      {1, 1, 1}};

    // Variables used in extending and writing to the extended portion of dataset

    hsize_t size[2];
    hsize_t offset[2];
    hsize_t dimsext[2]    = {7, 3}; // extend dimensions
    int     dataext[7][3] = {{2, 3, 4}, {2, 3, 4}, {2, 3, 4}, {2, 3, 4}, {2, 3, 4}, {2, 3, 4}, {2, 3, 4}};

    // Try block to detect exceptions raised by any of the calls inside it
    try {
        // Turn off the auto-printing when failure occurs so that we can
        // handle the errors appropriately
        Exception::dontPrint();

        // Create a new file using the default property lists.
        H5File file(FILE_NAME, H5F_ACC_TRUNC);

        // Create the data space for the dataset.  Note the use of pointer
        // for the instance 'dataspace'.  It can be deleted and used again
        // later for another dataspace.  An HDF5 identifier can be closed
        // by the destructor or the method 'close()'.
        DataSpace *dataspace = new DataSpace(2, dims, maxdims);

        // Modify dataset creation property to enable chunking
        DSetCreatPropList prop;
        prop.setChunk(2, chunk_dims);

        // Create the chunked dataset.  Note the use of pointer.
        DataSet *dataset =
            new DataSet(file.createDataSet(DATASETNAME, PredType::STD_I32BE, *dataspace, prop));

        // Write data to dataset.
        dataset->write(data, PredType::NATIVE_INT);

        // Extend the dataset. Dataset becomes 10 x 3.
        size[0] = dims[0] + dimsext[0];
        size[1] = dims[1];
        dataset->extend(size);

        // Select a hyperslab in extended portion of the dataset.
        DataSpace *filespace = new DataSpace(dataset->getSpace());
        offset[0]            = 3;
        offset[1]            = 0;
        filespace->selectHyperslab(H5S_SELECT_SET, dimsext, offset);

        // Define memory space.
        DataSpace *memspace = new DataSpace(2, dimsext, NULL);

        // Write data to the extended portion of the dataset.
        dataset->write(dataext, PredType::NATIVE_INT, *memspace, *filespace);

        // Close all objects and file.
        prop.close();
        delete filespace;
        delete memspace;
        delete dataspace;
        delete dataset;
        file.close();

        // ---------------------------------------
        // Re-open the file and read the data back
        // ---------------------------------------

        int     rdata[10][3];
        int     i, j, rank, rank_chunk;
        hsize_t chunk_dimsr[2], dimsr[2];

        // Open the file and dataset.
        file.openFile(FILE_NAME, H5F_ACC_RDONLY);
        dataset = new DataSet(file.openDataSet(DATASETNAME));

        // Get the dataset's dataspace and creation property list.
        filespace = new DataSpace(dataset->getSpace());
        prop      = dataset->getCreatePlist();

        // Get information to obtain memory dataspace.
        rank            = filespace->getSimpleExtentNdims();
        herr_t status_n = filespace->getSimpleExtentDims(dimsr);

        if (H5D_CHUNKED == prop.getLayout())
            rank_chunk = prop.getChunk(rank, chunk_dimsr);
        cout << "rank chunk = " << rank_chunk << endl;
        ;

        memspace = new DataSpace(rank, dimsr, NULL);
        dataset->read(rdata, PredType::NATIVE_INT, *memspace, *filespace);

        cout << endl;
        for (j = 0; j < dimsr[0]; j++) {
            for (i = 0; i < dimsr[1]; i++)
                cout << " " << rdata[j][i];
            cout << endl;
        }

        // Close all objects and file.
        prop.close();
        delete filespace;
        delete memspace;
        delete dataset;
        file.close();

    } // end of try block

    // catch failure caused by the H5File operations
    catch (FileIException error) {
        error.printErrorStack();
        return -1;
    }

    // catch failure caused by the DataSet operations
    catch (DataSetIException error) {
        error.printErrorStack();
        return -1;
    }

    // catch failure caused by the DataSpace operations
    catch (DataSpaceIException error) {
        error.printErrorStack();
        return -1;
    }

    return 0; // successfully terminated
}

I'm unfamiliar with the HDF5 format.
Is there a way to append/extend a single log to the end of an one dimension DataSet?
etc:

*

*The log buffer is not C contiguous.

*The exactly size of the DataSet is unknown, since the logs are generated by exchange.

*Saving by timer or chunk is not preferred.

*One instance of the log goes below

struct WQWindTransaction {
    union {
        uint32_t clock;
        struct {
            uint32_t clockMagicNum: 2;
            uint32_t localTimeUnderMs: 20;
            uint32_t exchTimeUnderMs: 10;
        };
    };
    int32_t localTime;
    int32_t exchTime;
    int16_t typeID;
    int16_t tickerIndex;
    int32_t index; // txn no.
    float price;
    int32_t volume;
    double turnover;

    char bsFlag;
    char reserved[3];
    char orderKind;
    char functionCode;

    int32_t askOrder; // order no.
    int32_t bidOrder; // order no.
};


text:
Q: Vaadin Fusion index.html will result in offline-stub I'm very new to Jetty and Vaadin. I try to get a Jetty running hosting a minimal Vaadin Fusion example.
However, already on the first visit on my empty index.html I got a connection lost banner and a 404 because it tries to redirect to an /offline-stub.html that I don't have.
The Produced view:

In the network tap, you can see that Vaadin somehow initiates the redirect:

My index.html is very simple:
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Vaadin Grocery App</title>

hello

an index.ts as well:
import { Router } from '@vaadin/router';
import { routes } from './routes';
import { appStore } from './stores/app-store';

export const router = new Router(document.querySelector('#outlet'));

router.setRoutes(routes);

window.addEventListener('vaadin-router-location-changed', (e) => {
  appStore.setLocation((e as CustomEvent).detail.location);
  const title = appStore.currentViewTitle;
  if (title) {
    document.title = title + ' | ' + appStore.applicationName;
  } else {
    document.title = appStore.applicationName;
  }
});

I initiate the Jetty like this:
 public static void main(String[] args) throws URISyntaxException, IOException {

        Log.setLog(new StdErrLog());
        System.out.println("Server starting...");

        String extForm = webRoot + "/webapp";
        System.out.println(extForm);

        final ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
        context.setContextPath("/");

        final ResourceHandler resHandler = new ResourceHandler();
        resHandler.setResourceBase(extForm);
        final ContextHandler ctx = new ContextHandler("/");
        ctx.setHandler(resHandler);

        Server embeddedServer = new Server(8080);

        embeddedServer.insertHandler(context); // Rest/Servlets
        embeddedServer.insertHandler(resHandler); // HTML Resources
        try {
            embeddedServer.start();
            embeddedServer.join();
        } catch (Exception e) {
            System.err.println("Server error:\n" + e);
        }
        System.out.println("Server stopped");
    }

Webroot, extform -values are correct and the files are at those specified locations on disk:

A: Please note that Vaadin Fusion only supports Spring Boot backends right now. Because of that, you don't need to configure your own server. Starting the Spring Boot app is enough. I recommend creating a project starter on https://start.vaadin.com and basing your project on that.
@SpringBootApplication
public class Application extends SpringBootServletInitializer implements AppShellConfigurator {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

A: Don't mix ResourceHandler and ServletContextHandler together like that.
Remove the ResourceHandler entirely (and it's associated ContextHandler)
Properly define the ServletContextHandler with a resource base.
Then ensure that ServletContextHandler has a DefaultServlet setup.
That's it, that's all you have to do.
Oh, and don't declare your REST endpoints on url-pattern / or /* as that also prevents static resource serving.  Those url-patterns basically mean that your servlet endpoint (your REST lib?) is the only thing, and it's responsible for 100% of requests.
The reason you don't mix things like this is because both ServletContextHandler and ResourceHandler are terminal (once entered, they must respond with an HTTP response).
If you use the ServletContext properly, then the best match (see Servlet url-pattern matching rules, eg: longest match) against the url-pattern is used, serving static content or your REST endpoint depending on what your client is requesting.


text:
Q: Is there a tensor eqiv to python's list.count() I'm attempting to do all my input pipeline work in tensorflow. This includes transforming the examples into the types required by the classifier.
I just learned I can't iterate over a string tensor like I would do with a standard python list. My specific question is "is there a tf function for testing the existence of a constant value within a tensor?" Of course there may be a better way to do this (I'm new to tf and python).
# creating a unique list of tokens (python)
a_global = []
a = [...]
for token in a:
    if a_global.count(token) == 0:
        a_global.append(token)

I'm indexing string tokens so I can essentially convert them into integers using the token's position within the list as its new value. That snippet will not work  when "a" is a tensor, so I'm trying tf.map_fn() instead, but I don't know how to replicate the IF statement predicate. Can someone point me in the right direction?
tf ver 1.8

A: If you don't need gradients for this operation (which I guess you don't for preprocessing stuff), the easiest could be to use tf.py_func. It essentially is able to wrap numpy code snippets into TensorFlow ops.
If that doesn't work for you, look at this post to count occurrences. Then you could use tf.cond to replicate the if statement.


text:
Q: Javafx 8 - calendar GUI - casting Node as Pane? Trying to iterate over a GridPane consisting of 35 Panes in order to create a GUI for a calendar. If anyone has any advice, please tell me.
@FXML
public GridPane table;

int col = monthStartsOnDay-1;
int max = 35 - col;
int row = 0;
for (Node child : table.getChildren()) {
    Rectangle rectangle = new Rectangle(143,30);
    rectangle.setStyle("-fx-background-color: black;");
    rectangle.setId(WEEK[col % 7] + "#" + row);
    child.add(rectangle, col, row); //the error comes here <------
    if(col % 6 == 0) {
        row++;
    } col++;
}

I guess casting the child as a Pane (the object it actually is) is not possible. But I need to make consistent changes to every single child of the GridPane (that is, every single Pane in every index of the GridPane) more or less all the time. So I need a way to do that, that isn't terrible like I am sure mine is!
Advice is greatly appreciated.

A: I've released some JavaFX controls (work in progress) for the new Date & Time API (JSR-310) .
The library is Open Source. Maybe you find it useful as a starting point.
You can read more about it here:
http://puces-blog.blogspot.ch/2013/04/drombler-commons-javafx-controls-for.html
http://puces-blog.blogspot.ch/2013/12/drombler-commons-date-and-time-controls.html
Current Javadoc: http://www.drombler.org/DromblerCommons/current/docs/site/drombler-commons-fx/drombler-commons-fx-time/apidocs/index.html
The library is available from Maven Central:
<dependency>
    <groupId>org.drombler.commons</groupId>
    <artifactId>drombler-commons-fx-time</artifactId>
    <version>0.6</version>
</dependency>

You can find some sample code here: http://sourceforge.net/p/drombler/drombler-commons/ci/default/tree/drombler-commons-fx/drombler-commons-fx-samples/drombler-commons-fx-samples-time/


text:
Q: Why can I not submit a form with a navigation property with Entity Framework? I am learning C# and I have been running into a lot of issues with my first project around navigation properties. The main hurdle I am having an issue with is a basic four property model (and anything that includes a navigation property).
Here is the one I am currently working with:
Company Model:
public class Company
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Key]
    [Display(Name = "Id")]
    public int Id { get; set; }
    [Display(Name = "Name")]
    public string Name {  get; set; }

    public CompanyType Type { get; set; }

    public ICollection<Contact>? Contacts { get; set; }
}

Company Type Model:
public class CompanyType
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Key]
    [Display(Name = "Id")]
    public int Id { get; set; }
    [Display(Name = "Company Type")]
    public string Type { get; set; } = "";
}

And here is my context - just simple.
    public class SRMContext : DbContext
    {

        public DbSet<Company> Companies { get; set; }
        public DbSet<Contact> Contacts { get; set; }
        public DbSet<CompanyType> CompanyTypes { get; set; }

        public SRMContext (DbContextOptions<SRMContext> options) : base(options)
        {

        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Company>().ToTable("Companies");
            modelBuilder.Entity<Contact>().ToTable("Contacts");
            modelBuilder.Entity<CompanyType>().ToTable("CompanyTypes");
        }

    }

*I removed irrelevant models in the context.
I first used scaffolding to create the CRUD razor pages for Company. It would not include any navigation properties in it at all - for any model. Not sure if I am doing something wrong, or if this is standard. So I am trying to manually update the scaffolded pages to include CompanyType. I was able to generate a select list, and provide that to the UI. It gives me the options and I click submit. But when I click submit, it says I need to include the Company Type. If I change it to not required, it will submit, but there will be no company type listed.
I know you can just do the Id without doing the navigation property, but further in my code, I have many-to-many navigation properties, so the Id will not work for them. I am having the same issues with them too, but this one is much simpler to work with until I get this figured out.
What am I doing wrong?

public class CreateModel : PageModel
{
    private readonly SRMContext _context;
    public SelectList CompanyTypes { get; set; }

    public CreateModel(SRMContext context)
    {
        _context = context;
    }

    public async Task<IActionResult> OnGetAsync()
    {
        CompanyTypes = new SelectList(_context.CompanyTypes, nameof(CompanyType.Id), nameof(CompanyType.Type));
        return Page();
    }

    [BindProperty]
    public Company Company { get; set; }

    // To protect from overposting attacks, see https://aka.ms/RazorPagesCRUD
    public async Task<IActionResult> OnPostAsync()
    {
      if (!ModelState.IsValid)
        {
            return Page();
        }

        _context.Companies.Add(Company);
        await _context.SaveChangesAsync();

        return RedirectToPage("./Index");
    }
}

View Page

        <form method="post">

                <input asp-for="Company.Name" class="form-control" />

                <select asp-for="Company.Type" asp-items="Model.CompanyTypes" class="form-control"></select>

                <input type="submit" value="Create" class="btn btn-primary" />

        </form>

(I'm sorry, I know its a lot of code, but I want to show everything needed!)

A: Complex objects are not recognized on a form post, so the type is probably null. Instead, post the foreign key of the type and it should be recognized:
public class Company
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Key]
    [Display(Name = "Id")]
    public int Id { get; set; }

    [Display(Name = "Name")]
    public string Name {  get; set; }

    public int CompanyType_Id { get; set; }

    [ForeignKey("CompanyType_Id")]
    public CompanyType Type { get; set; }

    public ICollection<Contact>? Contacts { get; set; }
}

And in your form:
<select asp-for="Company.CompanyType_Id" asp-items="Model.CompanyTypes" class="form-control"></select>

Haven't tested this, but pretty sure this is the issue.

A: See my answer to this question (Binding Complex Entities inside complex Entities to Requests) for an explanation of what is happening when you send an entity to a View to serve as it's Model and the issues & risks you can encounter when trying to send that model back.
The general advice I give is to not send entities to the view because while the view engine on the server gets the entity, what comes back from the client browser is not still an entity, it is just data fields that get cast as an entity so they are either incomplete or prone to tampering. (plus generally involve sending far more data over the wire than is needed)
Your Create PageModel is a good start, but consider just embedding the fields from a Customer rather than a Customer entity (Same goes for Update/Edit) This would include a CustomerTypeId column that when you build your Customer entity within the POST call, you fetch the CustomerType reference from the DbContext and assign that to the newly created Customer. This has the benefit of also validating whatever FKs you receive from the client browser to ensure you are dealing with legal data, throwing an exception in a more useful spot for debugging than the final SaveChanges call. The typical rationale for wanting to pass entities around is to avoid additional DB Read hits. Reading related entities like this by ID is extremely fast, and even cases where you might need to load several related entities there are techniques to batch these up into a single read operation. (Select all IDs needed, read in a single hit using a Contains, then assign from that set)


text:
Q: How to solve 'This method must be called with an app access_token' error? I'm testing out scores api on my test app.
So...I've singed up my app with the following permissions.
publish_stream,
publish_actions,
user_status,
user_photos

After logged in, I'm requesting the following api in PHP
$loggedUser = $Facebook->getUser();
$scoreUpdate = $Facebook->api('/'.$loggedUser."/scores", 'post', array('score'=> 100));

I get the following error.

This method must be called with an app access_token

So I've checked what the sdk is sending to facebook, and I've confirmed that it is sending 'access_token' along with my params.
What's the problem in this case?

A: app access_token you can simple make it like this:
$facebook->api('/me/scores', 'POST', array(
  'score' => 100,
  'access_token' => $facebook->getAppId().'|'.$facebook->getApiSecret()
));
voila

A: Now there are two tokens, a User token...and an Application token. You need the later.
Now the PHP-SDK will append the user access_token if it finds one which is I think your case. I suggest you read the official Facebook how-to for publishing scores
Example taken from my tutorial:
$APPLICATION_ID = "APP_ID";
$APPLICATION_SECRET = "APP_SECRET";

$token_url =    "https://graph.facebook.com/oauth/access_token?" .
                "client_id=" . $APPLICATION_ID .
                "&client_secret=" . $APPLICATION_SECRET .
                "&grant_type=client_credentials";
$app_token = file_get_contents($token_url);

A: $ret_obj = $fb->api( '/' . $fb->getUser() . '/scores', 'POST', array(
    'score' =>  100,
    'access_token' => $fb->getAppId().'|'.$fb->getApiSecret()
));

If you specify the app access token in the access_token parameter, you will eventually lose the ability to use /me, so you have to be specific about the user ID. Otherwise you get this error: "OAuthException: An active access token must be used to query information about the current user", as explained here : facebook Uncaught OAuthException: An active access token must be used to query information about the current user


text:
Q: Is it possible to verify the apple app site association file was properly requested and configured for an instance of an installed IOS app? Is it possible to verify the apple app site association file was properly requested and configured for an instance of an installed IOS app? Ideally, we could easily verify that Universal Links are working properly for an instance of a device and installed application for the purpose of debugging. As an alternative, we could leverage a metric that confirms this association occurred properly for the purpose of alarming.
Background
Clicking on a URL associated with an IOS application that has been properly configured Universal Links enabled sometimes does not immediately launch the associated app.
I am aware that there are a few known cases where the app does not launch when it should (eg. Source App use redirect URL for attribution, Association files fail to load etc), but it is not clear at a glance if this behavior is an actual widespread issue and it is not clear how to debug it.
What I have tried?

*

*Followed all steps listed for Support Universal Links to ensure Universal Links are properly configured

*Verified URL host with Branch.io AASA Validator

*Confirmed there is no Web Server errors when serving these AASA files from /.well-known/apple-app-site-association

*Confirmed this behavior works most of the time*

*As an alternative to debugging, we have considered a metric that confirms this association (if it exists)


text:
Q: Get missing columns from a list of expected columns in a table The test has a list of expected columns which verifies if the actual table has them. The assertion is if the counts are equal in expected and actual, then all columns are present.
How to extract which columns are missing to put into a more meaningful error message?
Thanks for your help.
-- Verify added columns exist
CREATE PROC [testComplianceMaintenanceReporting].[test FactPropertyLatestRepairJobAgg_ColumnsExist]
AS
BEGIN
    SET NOCOUNT ON

    -- Assemble
    IF OBJECT_ID('tempdb..#TempExpected') IS NOT NULL
    BEGIN
        DROP TABLE #TempExpected
    END
    CREATE TABLE #TempExpected
    (
        Id INT,
        ColumnName NVARCHAR(50)
    )
    INSERT INTO #TempExpected
        VALUES
            (1, 'TenancyKey'),
            (2, 'TenancyHouseholdTypeKey'),
            (3, 'HomeVisitKeyLatest'),
            (4, 'HomeVisitDueStatusKey'),
            (5, 'HousingApplicationKey'),
            (6, 'RepairAreaKeyPropertyDefault'),
            (7, 'ContractKeyPropertyDefaultPMSCService'),
            (8, 'ContractorKeyPropertyDefaultHeadContractor'),
            (9, 'NextPeriodicHomeVisitDate'),
            (10, 'CountOfActiveLeaseAgreements')

    -- Action
    IF OBJECT_ID('tempdb..#TempActual') IS NOT NULL
    BEGIN
        DROP TABLE #TempActual
    END
    SELECT * INTO #TempActual
    FROM
    (
        SELECT
            OBJECT_ID,
            NAME
        FROM SYS.COLUMNS
        WHERE
            OBJECT_ID = OBJECT_ID('dm.Fact_PropertyLatestRepairJobAgg')
            AND NAME IN (SELECT ColumnName FROM #TempExpected)
    ) [TempActual]

    -- Assert
    DECLARE @expectedCount INT = (
        SELECT COUNT(*) FROM #TempExpected
    )
    DECLARE @actualCount INT = (
        SELECT COUNT(*) FROM #TempActual
    )
    EXEC tSQLt.AssertEquals
    @Expected = @expectedCount,
    @Actual = @actualCount,
    @Message = 'There are missing columns'
END
GO

A: Where you assert the test condition for @actualCount I believe you mean to INNER JOIN to the #TempExpected table.  That would confirm that the actual values are the correct values.  Otherwise the actual rows might not contain the expected ColumnNames.  To create the list of missing column names the query uses STRING_AGG and NOT EXISTS.  Something like this
    -- Assert
    DECLARE @expectedCount INT = (
        SELECT COUNT(*) FROM #TempExpected
    );
    DECLARE @actualCount INT = (
        SELECT COUNT(*)
        FROM #TempActual ta
             join #expectedCount ec on ta.ColumnName=ec.ColumnName
    );
    DECLARE @missing_ColumnName_message varchar(200);
    select @missing_ColumnName_message = (
        select concat('There are missing columns: ', string_agg(ec.ColumnName, ','))
        from #expectedCount ec
        where not exists(select 1
                         from #TempActual ta
                         where ta.ColumnName=ec.ColumnName)
    );
    EXEC tSQLt.AssertEquals
    @Expected = @expectedCount,
    @Actual = @actualCount,
    @Message = @missing_ColumnName_message;

Older versions of SQL Server without STRING_AGG could use STUFF and FOR XML
-- Assert
    DECLARE @expectedCount INT = (
        SELECT COUNT(*) FROM #TempExpected
    );
    DECLARE @actualCount INT = (
        SELECT COUNT(*)
        FROM #TempActual ta
             join #expectedCount ec on ta.ColumnName=ec.ColumnName
    );
    DECLARE @missing_ColumnName_message varchar(200);
    select @missing_ColumnName_message = (
        select concat('There are missing columns: ',
                      (stuff((select ', ' + ec.ColumnName
                       from #expectedCount ec
                       where not exists(select 1
                                        from #TempActual ta
                                        where ta.ColumnName=ec.ColumnName)
                       order by 1
                       for xml path('')),1,1,'')))
    );
    EXEC tSQLt.AssertEquals
    @Expected = @expectedCount,
    @Actual = @actualCount,
    @Message = @missing_ColumnName_message;

A: tSQLt already has a built in assert for this, which validates column names, position, data type and nullability.  Also, in my opinion a more elegant solution:
create procedure [UserProfileTests].[test Attribute column structure]
as
begin
    create table [UserProfileTests].[expected]
    (
      AttributeId int not null
    , AttributeName varchar(50) not null
    , DotNetType varchar(100) null
    , Narrative varchar(500) null,
    );

    exec tSQLt.AssertEqualsTableSchema '[UserProfileTests].[expected]', 'UserProfile.Attribute';
end;
go

... and the results you get back will allow you to quickly identify what's missing/invalid

A: This is eventually what I ended up with thanks to @SteveC:
    -- Assert
    DECLARE @expectedCount INT = (
        SELECT COUNT(*) FROM #TempExpected
    )
    DECLARE @actualCount INT = (
        SELECT COUNT(*)
        FROM #TempActual [TA]
        JOIN #TempExpected [TE] ON TA.Name = TE.ColumnName
    )
    DECLARE @missingColumns NVARCHAR(MAX)
    SELECT @missingColumns = COALESCE(@missingColumns + ', ' + MissingColumn, MissingColumn)
        FROM
        (
            SELECT TE.ColumnName [MissingColumn]
            FROM #TempExpected [TE]
            WHERE NOT EXISTS
            (
                SELECT 1
                FROM #TempActual [TA]
                WHERE TA.Name = TE.ColumnName
            )
        ) [MissingColumns]
    DECLARE @errMsg NVARCHAR(MAX) = (
        SELECT CONCAT('Missing columns: ', @missingColumns)
    )
    EXEC tSQLt.AssertEquals
        @Expected = @expectedCount,
        @Actual = @actualCount,
        @Message = @errMsg

Output:

Reference using COALESCE:
https://www.mytecbits.com/microsoft/sql-server/concatenate-multiple-rows-into-single-string


text:
Q: How to translate and update Azure Cognitive Search Index document for different Language Analyzer fields? I am working on configuration of Azure Cognitive Search Index which will be queried from websites in different languages. I have created language specific fields and have added appropriate language analyzers while Index creation.
For example:
{
    "id": "",
    "Description": "some_value",
    "Description_es": null,
    "Description_fr": null,
    "Region": [ "some_value", "some_value" ],
    "SpecificationData": [
        {
            "name": "some_key1",
            "value": "some_value1",
            "name_es": null,
            "value_es": null,
            "name_fr": null,
            "value_fr": null
        },
        {
            "name": "some_key2",
            "value": "some_value2",
            "name_pt": null,
            "value_pt": null,
            "name_fr": null,
            "value_fr": null
        }
    ]
}

The fields Description, SpecificationData.name and SpecificationData.value are in English and coming from Cosmos DB. Fields Description_es, SpecificationData.name_es and SpecificationData.value_es will be queried from the Spanish website and should be fields translated in Spanish. And similar for the French language fields.
But since, Cosmos DB is having fields only in English, language specific fields such as Description_es, SpecificationData.name_es and SpecificationData.value_es are Null by default.
I have tried using Skillsets and linking Index to "Azure Cognitive Translate Service" but Skillsets are translating only one field at a time.
Is there any way to translate multiple fields and save the specific translation in particular fields?
Edit: Adding Index, Skillset and Indexer code that I have tried:
Index (snippet):
{
    "name": "SpecificationData",
    "type": "Collection(Edm.ComplexType)",
    "analyzer": null,
    "synonymMaps": [],
    "fields": [
        {
            "name": "name",
            "type": "Edm.String",
            "facetable": true,
            "filterable": true,
            "key": false,
            "retrievable": true,
            "searchable": true,
            "sortable": false,
            "analyzer": "standard.lucene",
            "indexAnalyzer": null,
            "searchAnalyzer": null,
            "synonymMaps": [],
            "fields": []
        },
        {
            "name": "value",
            "type": "Edm.String",
            "facetable": true,
            "filterable": true,
            "key": false,
            "retrievable": true,
            "searchable": true,
            "sortable": false,
            "analyzer": "standard.lucene",
            "indexAnalyzer": null,
            "searchAnalyzer": null,
            "synonymMaps": [],
            "fields": []
        },
        {
            "name": "name_fr",
            "type": "Edm.String",
            "facetable": true,
            "filterable": true,
            "key": false,
            "retrievable": true,
            "searchable": true,
            "sortable": false,
            "analyzer": "fr.lucene",
            "indexAnalyzer": null,
            "searchAnalyzer": null,
            "synonymMaps": [],
            "fields": []
        },
        {
            "name": "value_fr",
            "type": "Edm.String",
            "facetable": true,
            "filterable": true,
            "key": false,
            "retrievable": true,
            "searchable": true,
            "sortable": false,
            "analyzer": "fr.lucene",
            "indexAnalyzer": null,
            "searchAnalyzer": null,
            "synonymMaps": [],
            "fields": []
        }
    ]
}

Skillset:
{
    "@odata.type": "#Microsoft.Skills.Text.TranslationSkill",
    "name": "psd_name_fr",
    "description": null,
    "context": "/document/SpecificationData",
    "defaultFromLanguageCode": null,
    "defaultToLanguageCode": "fr",
    "suggestedFrom": "en",
    "inputs": [
        {
            "name": "text",
            "source": "/*/name"
        }
    ],
    "outputs": [
        {
            "name": "translatedText",
            "targetName": "name_fr"
        }
    ]
}

Indexer:
"outputFieldMappings": [
    {
        "sourceFieldName": "/document/SpecificationData/*/name/name_fr",
        "targetFieldName": "/name_fr" //I get an error message as "Output field mapping specifies target field 'name_fr' that doesn't exist in the index". I have tried accessing the full path as /document/SpecificationData/name_fr but it still gives same error. It looks for the specified field inside root structure and gives the error if the field is nested array object.
    }
]

A: You could use a text merge skill first to merge all the fields you want to translate if you wanted to get one big merged translation field for each language. That probably wouldn't fit your exact scenario though since you said you still wanted separate fields as the output. To keep them separate, I think you'll have to translate them one by one, with one translation skill per field and language. There's no problem in having more than one translation skill in a skillset so that should work fine, it just may be a little tedious to setup.
UPDATE 5/18/22
OK, so since you're not defining a complex SpecificationData index field, but instead top-level "name_fr" and so on, then yes, output field mappings are fine. Output field mappings map a path in the enriched document to an index field, by name. So targetFieldName should be "name_fr" with no leading slash. sourceFieldName should point to the output of your translation skill, name_fr under the context path, which is /document/SpecificationData, so the full path to your skill's output is /document/SpecificationData/name_fr.
But then there's another issue, which is that you really have an array of values as the output of the skill of the skill because of the * in the input path (/*/name). That probably won't work as the index field is a string and not an array.
It seems like your intent is to get a translation for each name of each SpecificationData entry. For that, your context should probably do the enumeration (/document/SpecificationData/*) and have the input path be /document/SpecificationData/*/name. This way, one name_fr will be under each item in the SpecificationData array.
Then you'll need to make those multiple values into a single string for the index, if you keep the index defined that way. The simplest way to do this is by using a text merger skill, probably something like this:
{
  "@odata.type": "#Microsoft.Skills.Text.MergeSkill",
  "context": "/document",
  "inputs": [
    {
      "name": "itemsToInsert",
      "source": "/document/SpecificationData/*/name_fr"
    }
  ],
  "outputs": [
    {
      "name": "mergedText",
      "targetName" : "name_fr"
    }
  ]
}

And then, since the output of this new skill will be /document/name_fr with the space-separated concatenation of all French-translated names, you don't need the output field mapping at all, the value will get automatically mapped to your index.
Finally, to better understand and debug skillsets, you should take a look at debug sessions.


text:
Q: How to handle RingCentral OAuth 2.0 "Invalid application" TokenInvalid error When using a OAuth 2.0 Bearer token with the following cURL command and receiving the following error, what does the TokenInvalid "Invalid application" error mean and how to handle this error? The application is valid in the Developer Portal and the same token is working for other API calls in an running app.
cURL Request
curl -XGET https://platform.ringcentral.com/restapi/v1.0/account/~ \
-H 'Authorization: Bearer <my_token>'

Response
401 Unauthorized

{
  "errorCode" : "TokenInvalid",
  "message" : "Invalid application",
  "errors" : [ {
    "errorCode" : "OAU-127",
    "message" : "Invalid application"
  } ]
}

A: RingCentral operates different API environments that use different application definitions (client ids and secrets). A token and application that is valid in one environment may not be valid in another.
A common reason this error can occur is when a token or application is only valid in the sandbox environment is being used in the production environment. For example, this error will be encountered when making a request to the production environment (https://platform.ringcentral.com) with a token intended for the sandbox environment (https://platform.devtest.ringcentral.com).