text:
Q: purging permanently deleted items from Exchange 2010 after backup I am using BackupExec 2010 R3 and Exchange 2010. Full backups are taken weekly with a daily incremental.
When looking at the output of Get-MailboxStatistics, I have noticed that the value for TotalDeletedItemSize is only growing. I believe this value is not the Deleted Items folder in the mailbox, but items that have been permanently deleted (i.e., shift-del or items deleted/expired from the Deleted items folder).
I thought that when a Full backup was run that these deleted items would be purged. Am I wrong? Or is something broken?

A: When the full backup is taken using the Exchange agent it will backup the Deleted Items by default but it won't override the retention period settings in Exchange itself.  It will delete the transaction logs up to the start of the full backup itself, but permanently deleted items still remain in the mailbox store until the retention period expires.
Symantec recommends (see here, despite it being old it still applies: http://www.symantec.com/business/support/index?page=content&id=HOWTO73201) that you even set a retention period long enough for your needs and what your disk space can handle.  This is because even they admit it is much easier to recover a deleted item within the retention period than to deal with restoring from an actual backup.
EDIT: For our "discussion" here's a screenshot EXAMPLE of the database tab showing the backup status:

A: The "Dumpster Items" as they are sometimes referred to, are controlled by the deletion settings on the mailbox database on which the mailbox resides.
Go to the properties of on of your mailbox DBs in the EMC and go to the "Limits" tab.  There you will find the "Keep deleted items for (days):" setting.  by default I believe this is set to 14 days.  So regardless of your backups, those deleted, deleted items will not be purged from the mailbox until after the specified number of days in the above setting.  You can also set this to "0" to disable retaining these messages, but I'd recommend against that unless you have low storage and VERY reliable backups.
You can also set this setting per mailbox in the user properties.


text:
Q: Initialize a variable with a DOM element: is the "window.onload" best for it? What's, or where is, the safet way to initialize a variable that points to a DOM element, let's say, a div or image?
let myImg;

window.onload (e) => {
  myImg = document.getElementById("my_img_1");
}

function doSomething(a, b, c) {
  //using myImg
}

Are there any issues with this code? Is this a proper way to initialize a DOM variable?

A: The load event (what you're currently using) usually isn't a great choice because it happens really late, waiting until all resources (including images, etc.) are loaded. Sometimes you want that, but not often.
You have lots of options. Here's a list in my personal order of preference:

*

*Use type="module" on your script tag so your JavaScript code is a module, not a global script. Modules (both inline and via src) are automatically deferred (see the next item). (They also have other benefits: the code in them isn't at global scope, so they're nicely contained; they're automatically in strict mode; they can load other modules via import.) This works in all modern browsers (so, not with IE11).

*Use the defer attribute on your script tag. That tells the browser to download and parse the code, but not to run it until it's done parsing the HTML. Only works with src, though, not inline. This works in all modern browsers and also IE10+.

*Put the script at the end of the document, just prior to the closing </body> tag. It won't be run until all the HTML above it has been parsed and put in the DOM. This has always worked.

*Use the DOMContentLoaded event. This works in anything even vaguely modern, including IE9+.

*Use the load event (what you're currently using; just including it on the list for completeness). This has worked basically forever.

So for example:
<script type="module" src="your-code.js"></script>

your-code.js:
const myImg = document.getElementById("my_img_1");

function doSomething(a, b, c) {
    //using myImg
}

Inline example just to demonstrate the deferring:

<script type="module">
const myImg = document.getElementById("my_img_1");

function doSomething(a, b, c) {
    myImg.style.border = "2px solid yellow";
}

doSomething();
</script>
<img id="my_img_1" src="data:image/png;base64,/9j/4AAQSkZJRgABAQEASABIAAD/2wBDABQODxIPDRQSEBIXFRQYHjIhHhwcHj0sLiQySUBMS0dA
[encoded data, 4104 characters]
sfhKhLkgeZekVRdAAPag0KHJnzVgbIm/NNSntAeleUfif83/2Q==">

Note that the script is above the img, but it still works — because the script execution is deferred.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Jasmine: Trying to test an AngularJS factory function I am totally new to testing in AngularJS. I have setup karma, and am now attempting to test a certain function in a factory I have written.
Here is a snippet of my factory:
app.factory('helpersFactory', ['constants', function (constants) {
    return {

        someFunction: function() {
        },

        is24x24Icon: function (iconNum) {
            return ((iconNum >= 10090 && iconNum <= 10125) ;
        }
    };

 }]);

I then have this test:
describe('Factory: helpersFactory', function () {

    beforeEach(module('ppMobi'));

    var fct;
    beforeEach(inject(function ($factory) {
        fct = $factory('helpersFactory');
    }));

    it('should detect iconNum 10090 is a 24 x 24 icon', function () {

        var iconNum = 10090;
        var is24x24Icon = fct.is24x24Icon(iconNum);
        expect(is24x24Icon).toBeTruthy();

    });
});

I get an error from Karma telling me it cannot read 'is24x24icon' of undefined. Therefore I can only assume my factory has not been created properly during the test. I do have a dependency on constants in the factory used by other functions. This is just an angular.constant() I have setup on my main application module.
I have found some other posts, but am unsure how to proceed, do I need to inject my constants dependency into my test?

A: Kind of new myself but I think you need to use the underscore name underscore trick to inject your factory:
var fct;
beforeEach(inject(function (_helpersFactory_) {
    fct = _helpersFactory_;
}));

This blog uses mocha but I found it useful and the Karma stuff should be the same:  https://www.airpair.com/angularjs/posts/testing-angular-with-karma
And yes you will need to inject the constants as well (the link shows how) but your posted code does not seem to use constants so you won't need it for this particular test.


text:
Q: Como exibir um icone escondido, após carregar um arquivo pelo input file Tenho uma tela onde tem diversos input type="file" e estou tentando fazer com que um ícone apareça quando o usuário carregar um arquivo, facilitando a visibilidade de que naquele input já esta com um arquivo.
Abaixo segue as imagens do que desejo, pra facilitar o entendimento:
Antes de escolher o arquivo:

Depois de escolher o arquivo:

Esse é o meu HTML:

            <input type="file" class="custom-file-input col-sm-11" id="ficha_inscricao"  >
            Escolha o Arquivo

        Ficha de Inscrição Preenchida e Assinada.

Esse é o script que estou usando, nele eu carrego o nome do arquivo selecionado no input(isso esta funcionando) e tento remover o hiddenque esta no meu ícone e é isso que não estou conseguindo fazer.
document.querySelector('.custom-file-input').addEventListener('change',function(e){
    var fileName = document.getElementById("ficha_inscricao").files[0].name;
    var nextSibling = e.target.nextElementSibling
nextSibling.innerText = fileName;
document.getElementsByTagName('ficha_inscricao_ok').removeAttribute("hidden");

})

Nesse exemplo estou tentando fazer duas coisas em uma mesma função, mas já tentei fazer também em funções separadas e da mesma forma não funcionou.

A: Seu problema está aqui: document.getElementsByTagName('ficha_inscricao_ok').removeAttribute("hidden");, você está usando um seletor de tags html, para pegar elementos html e não existe a tag ficha_inscricao_ok.
Você deve mudar o tipo de seleção, que você mesmo usou no código anteriormente, .getElementById para selecionar a tag com id="ficha_inscricao_ok", ou reescrever o seu código para .getElementsByTagName('i')[0] para capturar o , assim seu código irá remover o atributo hidden.
Fica assim:
document
        .querySelector('.custom-file-input')
        .addEventListener('change', function (e) {
          var fileName = document.getElementById('ficha_inscricao').files[0]
            .name;
          var nextSibling = e.target.nextElementSibling;
          nextSibling.innerText = fileName;
          document
            .getElementById('ficha_inscricao_ok')
            .removeAttribute('hidden');
        });

O selecionando a tag :
document
        .querySelector('.custom-file-input')
        .addEventListener('change', function (e) {
          var fileName = document.getElementById('ficha_inscricao').files[0]
            .name;
          var nextSibling = e.target.nextElementSibling;
          nextSibling.innerText = fileName;
          document
            .getElementsByTagName('i')[0]
            .removeAttribute('hidden');
        });

OBS: getElementsByTagName retorna um arrayList, por isso o uso do [0].


text:
Q: DIV floated left with auto width to fit in MAN div with 980px width I have those DIV'S

content 2

content 2

content 2content 2

content 2

content 1

Main div is fixed size = 980px, inside it i have DIV class'div1' its floated RIGHT and is fixed size. All i want DIVS with class DIV2 to be:
1. Floated left,
2. Auto width so thay will fill all the remaining size 740px,
3. content inside 'div2' align center.
i have this CSS code:
.content { width:980px; overflow: hidden; border: 1px solid #ccc; padding:5px;}
.div1 { overflow: hidden; float:right; width: 140px;}
.div2 { float:left; width: auto; border-right: 1px solid #ccc; text-align:center;}

But i cannot achive
2. Auto width so thay will fill all the remaining size 740px

A: Easiest way is to do it with a table, and you probably know how.

        content 2
        content 2
        content 2content 2
        content 2

content 1

CSS:
.content { width:980px; overflow: hidden; border: 1px solid #ccc; padding:5px;}
.div1 { overflow: hidden; float:right; width: 140px;}
.divs2{ float:left; width:740px;  }
.div2 { border-right: 1px solid #ccc; text-align:center;}

Check this out : http://jsfiddle.net/UCJA3/

A: why not set width: 20% on .div2 to ?

A: First wrap the ".div-2"s in an outer container:

content 2

content 2 content 2

content 2

content 2

content 1

Now give the "div-2-wrapper" class a width of 840px (the total remaining space) and float it to the left:
.div-2-wrapper{
    float: left;
    width: 840px;
}

Finally, give each "div-2" class a width of 209px. The reason you want them to be 209 and not 210 pixels wide is because each one contains a 1px right border. jsFiddle


text:
Q: Error: "Input path does not exist" stalling execution of AWS Glue Job (pyspark script) I'm getting the following series of errors, specifically the one that says "Input path does not exist", in my AWS Glue Job (written in pyspark) that is supposed to crawl a specific bucket location. The problem is that I've specified the folder location (and not individual filenames), and the fact that it is somehow able to determine the actual filenames before showing this error is what is intriguing. The following error is what is gleaned from the CloudWatch logs:

21/11/11 12:36:15 ERROR ProcessLauncher: Error from Python:Traceback (most recent call last):
File "/tmp/CloudTrailLogBatchProcessing", line 11, in
df = spark.read.option("multiline", "true").json('s3:///AWSLogs//CloudTrail/us-east-2/2021/11/11/')
File "/opt/amazon/spark/python/lib/pyspark.zip/pyspark/sql/readwriter.py", line 274, in json
return self._df(self._jreader.json(self._spark._sc._jvm.PythonUtils.toSeq(path)))
File "/opt/amazon/spark/python/lib/py4j-0.10.7-src.zip/py4j/java_gateway.py", line 1257, in call
answer, self.gateway_client, self.target_id, self.name)
File "/opt/amazon/spark/python/lib/pyspark.zip/pyspark/sql/utils.py", line 63, in deco
return f(*a, **kw)
File "/opt/amazon/spark/python/lib/py4j-0.10.7-src.zip/py4j/protocol.py", line 328, in get_return_value
format(target_id, ".", name), value)
py4j.protocol.Py4JJavaError: An error occurred while calling o74.json.
: org.apache.hadoop.mapreduce.lib.input.InvalidInputException: Input path does not exist: s3:///AWSLogs//CloudTrail/us-east-2/2021/11/11/_CloudTrail_us-east-2_20211111T0000Z_GGxAlmYsJSPcVsAA.json.gz
Input path does not exist: s3:///AWSLogs//CloudTrail/us-east-2/2021/11/11/_CloudTrail_us-east-2_20211111T0000Z_XaZZwCZ0WbyAXlIh.json.gz
Input path does not exist: s3:///AWSLogs//CloudTrail/us-east-2/2021/11/11/_CloudTrail_us-east-2_20211111T0005Z_02o2hkXQbNMs8H1c.json.gz
Input path does not exist: s3:///AWSLogs//CloudTrail/us-east-2/2021/11/11/_CloudTrail_us-east-2_20211111T0005Z_Nl4Z2awclBvau922.json.gz
Input path does not exist: s3:///AWSLogs//CloudTrail/us-east-2/2021/11/11/_CloudTrail_us-east-2_20211111T0010Z_3imeLnOAlakY8Exn.json.gz
Input path does not exist: s3:///AWSLogs//CloudTrail/us-east-2/2021/11/11/_CloudTrail_us-east-2_20211111T0010Z_V5l4nU9tIat4zYqg.json.gz

The following is part of the pyspark script saved as a job in AWS Glue:
import boto3

from pyspark.context import SparkContext
from pyspark.sql.session import SparkSession

import pyspark.sql.types as T

spark = SparkSession.builder.master("local[1]").appName("S3Crawler").getOrCreate()

# Read from multiple JSON or JSON.gz files in a directory
df = spark.read.option("multiline", "true").json('s3a://<foldername>/AWSLogs/<accountID>/CloudTrail/us-east-2/2021/11/11/')
print(df)

from pyspark.sql import functions as F

Records = df.withColumn("Records", F.explode(F.col("Records")))


text:
Q: Is it necessary to emphasize a long history of an old saying? I understand the sentence "Give me a place to stand on, and I will move the Earth" is what Archimedes said about the Law of the Lever, which means the old saying has more than 2,000 years history.
Is it necessary to emphasize it is a proverb which has been recognized by so many people for so many years and say something like this?

It is a quote that has been recognized for more than 2,000 years.

In other words, is it natural to say something like this?

Archimedes said a famous proverb 2,000 years ago, that is, give me a place to stand on, and I will move the Earth.


text:
Q: angularjs score counter not working Please take a look at this.
http://plnkr.co/edit/i4B0Q2ZGiuMlogvwujpg?p=preview
<input type="radio" name="op_0" ng-value="true" ng-model="n1"> True
<input type="radio" name="op_0" ng-value="false" ng-model="n2"> False
<input type="radio" name="op_0" ng-value="true" ng-model="n3"> True
<input type="radio" name="op_0" ng-value="false" ng-model="n4"> False

Why are two radio buttons  selected with a single click?
Why is the score value not increasing or decreasing?

A: To have all of your radio buttons in the same group they should all have the same name. It is the value that should be different in each one. If they don't have the same name, selecting one won't cause the others to de-select.
app.controller('aCtrl', function($scope) {

  $scope.s = 0;

  $scope.updateScore = function(val){
    if(val == 'true'){
      $scope.s += 1;
    }
    if(val == 'false'){
      $scope.s += -0.5;
    }
  }

});

 <div class="col-md-5 col-xs-8">
        <input type="radio" ng-click="updateScore('true')" name="op_0" ng-value="true" ng-model="n1"> True
        <input type="radio" ng-click="updateScore('false')" name="op_0" ng-value="false" ng-model="n2"> False
        <input type="radio" ng-click="updateScore('true')" name="op_0" ng-value="true" ng-model="n3"> True
        <input type="radio" ng-click="updateScore('false')" name="op_0" ng-value="false" ng-model="n4"> False
      </div>


text:
Q: Terminology question regarding looping thru an NSArray in Objective-C When you have an NSArray and you want to evaluate and change the elements, you can't change the array from inside the loop. So, you create a mutable copy that can be changed.
code example:
NSMutableArray *bin = [NSMutableArray arrayWithObjects:@"0", @"1", @"2", @"3", @"4", @"5", @"6", @"7", nil];
NSMutableArray *list = [NSMutableArray arrayWithObjects:@"a1", @"b2", @"c3", @"e4", nil];

NSMutableArray *listHolder = list; // can't mutate 'list' within loop so create a holder

for (int i = 0; i < [list count]; i++) {
    [listHolder replaceObjectAtIndex:i withObject:[bin objectAtIndex:i]];
}

What is that second array listHolder called? I mean, what term is used to refer to an array in this context.

A: This is perfectly valid:
NSMutableArray *bin = [NSMutableArray arrayWithObjects:@"0", @"1", …, @"7", nil];
NSMutableArray *list = [NSMutableArray arrayWithObjects:@"a1", …, @"e4", nil];

// NSInteger should be used instead of int
for (NSInteger i = 0; i < [list count]; i++) {
    [list replaceObjectAtIndex:i withObject:[bin objectAtIndex:i]];
}

You're not allowed to change the array inside a for … in or NSEnumerate loop, but using an index is perfectly valid.
What troubles me is your misunderstanding of pointers.
If it were a loop in which you weren't allowed to mutate the array this wouldn't copy the array but only the pointer to the array, effectively modifying the array you're not allowed to. (I'm not even sure if this works.)
Instead of just copying the pointer
// can't mutate 'list' within loop so create a holder
NSMutableArray *listHolder = list;

make a true copy:
NSMutableArray *copy = [[list mutableCopy] autorelease];

In case I really have to make a copy I try to name it according to its content. For example:
NSMutableArray *views;
NSMutableArray *reorderedViews = [views mutableCopy];

// reorder reorderedViews

Sometimes it's hard to find a good enough name, then I usually just use nameCopy.

A: There is not specific stylistic or common name for this that is universally used, it is your code afterall, and if there appropriate terms for them use them.
Having said that generally if you don't have specific names in this sort of situation then people refer to the original list as the "source" (src) and the final list as "destination" (dst), just like in a memory blitting style operation.

A: In this context listHolder would be called a copy.
Your code has a bug though. This line is not actually making a copy, it is only letting listHolder and list both reference the same array object:
NSMutableArray *listHolder = list;

This would be an actual copy:
NSMutableArray *listHolder = [list mutableCopy];

Make sure that you use mutableCopy and not just copy if you want the copy to be mutable. The copy method will return immutable variants on all mutable classes such as NSMutableSet, NSMutableDictionary, and so forth.
Also as others have noted it is only inside the for (item in collection) loop that the enumerated collection can not be mutated. In a normal for (;;) mutation is perfectly ok, but can lead to strange result if the number of items in the collection changes.

A: A temporary mutable copy of the original NSArray would be how I would refer to it.


text:
Q: Connecting with Athena using Python and pyathenajdbc I am trying to connect to AWS Athena using python. I am trying to use pyathenajdbc to achieve this task. The issue I am having is obtaining a connection. When I run the code below, I receive an error message stating it cannot find the AthenaDriver. ( java.lang.RuntimeException: Class com.amazonaws.athena.jdbc.AthenaDriver not found).  I did download this file from AWS and I have confirmed it is sitting in that directory.
from mdpbi.rsi.config import *
from mdpbi.tools.functions import mdpLog
from pkg_resources import resource_string
import argparse
import os
import pyathenajdbc
import sys

SCRIPT_NAME = "Athena_Export"

ATHENA_JDBC_CLASSPATH = "/opt/amazon/athenajdbc/AthenaJDBC41-1.0.0.jar"
EXPORT_OUTFILE = "RSI_Export.txt"
EXPORT_OUTFILE_PATH = os.path.join(WORKINGDIR, EXPORT_OUTFILE)

def get_arg_parser():
    """This function returns the argument parser object to be used with this script"""
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)

    return parser

def main():
    args = get_arg_parser().parse_args(sys.argv[1:])
    logger = mdpLog(SCRIPT_NAME, LOGDIR)

    SQL = resource_string("mdpbi.rsi.athena.resources", "athena.sql")

    conn = pyathenajdbc.connect(
        s3_staging_dir="s3://athena",
        access_key=AWS_ACCESS_KEY_ID,
        secret_key=AWS_SECRET_ACCESS_KEY,
        region_name="us-east-1",
        log_path=LOGDIR,
        driver_path=ATHENA_JDBC_CLASSPATH
    )
    try:
        with conn.cursor() as cursor:
            cursor.execute(SQL)
            logger.info(cursor.description)
            logger.info(cursor.fetchall())
    finally:
        conn.close()

    return 0

if __name__ == '__main__':
    rtn = main()
    sys.exit(rtn)

Traceback (most recent call last):   File
  "/usr/lib64/python2.7/runpy.py", line 174, in _run_module_as_main
      "main", fname, loader, pkg_name)   File "/usr/lib64/python2.7/runpy.py", line 72, in _run_code
      exec code in run_globals   File "/home/ec2-user/jason_testing/mdpbi/rsi/athena/main.py", line 53,
  in
      rtn = main()   File "/home/ec2-user/jason_testing/mdpbi/rsi/athena/main.py", line 39,
  in main
      driver_path=athena_jdbc_driver_path   File "/opt/mdpbi/Python_Envs/2.7.10/local/lib/python2.7/dist-packages/pyathenajdbc/init.py",
  line 65, in connect
      driver_path, **kwargs)   File "/opt/mdpbi/Python_Envs/2.7.10/local/lib/python2.7/dist-packages/pyathenajdbc/connection.py",
  line 68, in init
      jpype.JClass(ATHENA_DRIVER_CLASS_NAME)   File "/opt/mdpbi/Python_Envs/2.7.10/lib64/python2.7/dist-packages/jpype/_jclass.py",
  line 55, in JClass
      raise _RUNTIMEEXCEPTION.PYEXC("Class %s not found" % name)

A: The JDBC driver requires Java 8. I was currently running Java 7. I was able to install another version of Java on EC2 instance.
https://tecadmin.net/install-java-8-on-centos-rhel-and-fedora/#
I had to also set the java version in my code. With these changes, the code now runs as expected.
from mdpbi.rsi.config import *
from mdpbi.tools.functions import mdpLog
from pkg_resources import resource_string
import argparse
import os
import pyathenajdbc
import sys

SCRIPT_NAME = "Athena_Export"

def get_arg_parser():
    """This function returns the argument parser object to be used with this script"""
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)

    return parser

def main():
    args = get_arg_parser().parse_args(sys.argv[1:])
    logger = mdpLog(SCRIPT_NAME, LOGDIR)

    SQL = resource_string("mdpbi.rsi.athena.resources", "athena.sql")

    os.environ["JAVA_HOME"] = "/opt/jdk1.8.0_121"
    os.environ["JRE_HOME"] = "/opt/jdk1.8.0_121/jre"
    os.environ["PATH"] = "/opt/jdk1.8.0_121/bin:/opt/jdk1.8.0_121/jre/bin"

    conn = pyathenajdbc.connect(
        s3_staging_dir="s3://mdpbi.data.rsi.out/",
        access_key=AWS_ACCESS_KEY_ID,
        secret_key=AWS_SECRET_ACCESS_KEY,
        schema_name="rsi",
        region_name="us-east-1"
    )
    try:
        with conn.cursor() as cursor:
            cursor.execute(SQL)
            logger.info(cursor.description)
            logger.info(cursor.fetchall())
    finally:
        conn.close()

    return 0

if __name__ == '__main__':
    rtn = main()
    sys.exit(rtn)

A: Try this :
    pyathenajdbc.ATHENA_JAR = ATHENA_JDBC_CLASSPATH

You won't be needing to specify the driver_path argument in the connection method


text:
Q: Java/Eclipse: How to configure Run Configuration's Classpath for JUnit test? I have an Eclipse project with the following directory structure:
MyProj/
    src/main/java/
        com.me.myproject.widgets
            Widget.java
    src/main/config
        widget-config.xml
    src/test/java
        com.me.myproject.widgets
            WidgetTest.java
    src/test/config
        widget-test-config.xml

The Widget class reads its config (XML) file in from anywhere on the classpath and uses it to configure its properties.
I am trying to just get WidgetTest's test cases (all written with JUnit) to run inside Eclipse when I right-click the file and go to Run As >> JUnit Test. I assume I'll have to actually run it as a customized Run Configuration with its own configured classpath, but I'm not sure about that as I've never done this before.
Does anybody know how I can get a custom Run Configuration to run WidgetTest.java as a JUnit test, and successfully place src/test/config/widget-test-config.xml on the classpath? Thanks in advance!
Please note, this question is not about how to read a resource from the runtime classpath, its about how to get it on Eclipse's JUnit Run Config classpath in the first place!

A: I was under the impression that as long as you have src/test/config/widget-test-config.xml inside what Eclipse considers to be a source folder, it should already be on the classpath.
Is src/test a source folder for Eclipse ? If it is and you still get the problem, try out the following experiment :
If you copy widget-test-config.xml to the src root can Widget class read it ?
If Yes
then it's a problem of the test folder not being on the classpath and you may wanna try adding it manually like so.
Right click WidgetTest and select Run As -> Junit Test. This should automatically create a Junit Run Configuration accessible at Run -> Run Configurations. You modify it's Classpath entry to add the project containing the .xml file like so :

If No
If, even after moving the .xml file to the src root (i.e. default package), your widget class cannot read it then there is something else wrong. In that case, it would be great if you could furnish the snippet of code in WidgetTest which is trying to read the .xml file.
 Working Code
Here is a bit of working code :
public class A {

    @Test
    public void test() {
        InputStream stream = A.class.getResourceAsStream("/SomeTextFile.txt");
        System.out.println(stream != null);
        stream = Test.class.getClassLoader()
            .getResourceAsStream("SomeTextFile.txt");
        System.out.println(stream != null);
    }

}

The above works for me in a simple JAVA project and runs fine. (Running fine means getting
'true' printed on the console)
I am in the process of creating a GITHub repo for you to try out this code painlessly.
 GIT Hub Repo with Test project
You should be able to import the project in this zip and see the code working. Right click on the Test class A and click Run As -> Junit Test, and you should see two true in the Console.

A: If your WidgetTest class is written as a JUnit test, eclipse will try to run it as a Junit test automatically. If it doesn't, you should right click on the class in the package explorer, choose Run As >> Run Configuration >> choose Junit
To run a Junit test:

*

*in JUnit3, the class should implement TestCase and all the method names should start "test"

*in JUnit4, all the methods should be preceded by a @Test annotation
To place that config file in the classpath: when setting the Run Configuration as above, go to the Arguments tab in the upper right pane and in the VM arguments specify the classpath:
   -cp .:/path/to/the/config/file

However, if that file is in a package in the source directory, it should automatically be included in the classpath.


text:
Q: Voltage RMS and Voltage Spectral Density from ADC Sample are Not Consistent I have time series data from a 100 MS/s ADC, and I would like to calculate the RMS noise and the voltage spectral density (VSD), and see consistency between the two.
I'm using a 16-bit ADC, and the data is in bits, so data point can be any integer in [-32768, 32767]. The noise of the ADC channel is 3.6 LSB.
I calculate the VSD by taking the discrete Fourier transform (I use Fourier in Mathematica). I drop the data at frequencies above the Nyquist frequency (50 MHz), and take the magnitude of each term (because I don't care about the phase for this measurement).
I normalize the data FFT by calculating the FFT of a 1 MHz sine wave with 1 LSB RMS amplitude: SQRT(2)SIN(2 PI 10^6 t), then I use the height of that peak (which ends up equal to 127.867) as a normalization factor. So if f is the FFT magnitude of the data the normalize FFT is f/127.867.
I thought this normalization would take care of any factors of 2 or PI from the Mathematica Fourier function, but the VSD does not make sense. The VSD is flat, white noise; I don't sample at low enough rate to see the 1/f noise at low frequency. The noise level is 0.03 LSB. This is about 60 times larger than I expect the real VSD noise level to be, based on the 3.6 LSB RMS noise value since:
(RMS noise) ~= VSD noise level * SQRT(f1-f0) = 0.03*SQRT(50x10^6) = 218 LSB.
I feel like I'm missing something fundamental here, but I'm not quite sure what's going wrong. Any feedback on what I do here, and how to get closer to a consistent VSD?
Thank you.

A: Your sqrt(50M) assumes the VFD is in noise/sqrt(Hz).
What normalisations has Mathematica applied? Have you told it fs = 100M so it's giving you noise/sqrt(Hz), or is it giving you noise/bin_width, which will be much higher?
What's the length of your FFT? If (for instance) 10k, then your bins are 10M/10k = 1 kHz wide. This factor doesn't appear (and doesn't need to appear) in the sinewave calibration you did.
What window did you use? They increase the noise bandwidth of a bin by a factor of typically 2, but can be more.
Do a noise calibration, as well as a sinewave calibration, then vary the length of the FFT, and the type of window, to see what's going on.
'Ground Truth' of an FFT operation can be established with Parseval's Theorem. This basically says 'you get the same total energy for a sequence whether you add up the energy per time sample, or do a FFT and then add up the energy per frequency sample', subject to any scaling factor of N that the transform happens to do.
If the noise bandwidth is your problem, I'd guess your factor of 60 times too much is consistent with an FFT length of around 4096. Am I right?


text:
Q: Batch w/ ftp transfer I tried getting a file off of my ftp server with a batch file. Here is what happens:
ftp> open files.000webhost.com 21
Connected to us-east-1.route-1000.000webhost.awex.io.
220 ProFTPD Server (000webhost.com) [::ffff:145.14.145.124]
500 OPTS UTF8 not understood
User (us-east-1.route-1000.000webhost.awex.io:(none)):
331 User ***** OK. Password required

230-Your bandwidth usage is restricted
230 OK. Current restricted directory is /
ftp> lcd C:\Users\micah\Desktop\MiniventureLauncher\Game
Local directory now C:\Users\micah\Desktop\MiniventureLauncher\Game.
ftp> cd public_html
250 OK. Current directory is /public_html
ftp> binary
200 TYPE is now 8-bit binary
ftp> recv miniventure.jar
200 PORT command successful
150-Connecting to port 50186
150 13336.1 kbytes to download

Then it just stops. Here's the code in my batch file:
@Echo Off
Set _FTPServerName=files.000webhost.com 21
Set _UserName=*****
Set _Password=*****
Set _LocalFolder=C:\Users\micah\Desktop\MiniventureLauncher\Game
Set _RemoteFolder=public_html
Set _Filename=miniventure.jar
Set _ScriptFile=transfer
:: Create script
 >"%_ScriptFile%" Echo open %_FTPServerName%
>>"%_ScriptFile%" Echo %_UserName%
>>"%_ScriptFile%" Echo %_Password%
>>"%_ScriptFile%" Echo lcd %_LocalFolder%
>>"%_ScriptFile%" Echo cd %_RemoteFolder%
>>"%_ScriptFile%" Echo binary
>>"%_ScriptFile%" Echo recv %_Filename%
>>"%_ScriptFile%" Echo quit
:: Run script
ftp -s:"%_ScriptFile%"
Del "%_ScriptFile%"

It connects to the server, but it won't download the file.

A: As @martin-prikryl suggests in the comments, this is almost certainly a Windows firewall issue.
While Windows ftp can connect to a remote host without special permission, to download files, incoming remote transfers need to be explicitly allowed through the Windows firewall.
Allowing Incoming Transfers
If there are no Windows firewall rules for Windows ftp, when you run it with the recv command, you should be prompted to add Incoming rules to the Windows firewall automatically. The box marked Private networks [...] should be checked by default. Press the Allow access button to add the appropriate rules to your Windows firewall.
ex. Allow downloads via Windows ftp.exe

You shouldn't need to check the box marked Public networks [...] unless you intend to use Windows ftp away from home. You'll need to be an administrator to adjust firewall rules.
Note that, unfortunately, this will not allow the current download to continue. You will need to abort the current operation (usually with Ctrl + C) and try again.
No Firewall Pop-up Is Displayed
If the transfer hangs and no firewall rules pop-up is displayed, this most likely means that there are already existing rules in the Windows firewall for Windows ftp (these are added even if you initially press Cancel in the dialog box above). Furthermore, it is likely these rules are set to block any incoming connections (indicated by circle icons with slashes through them).
ex. Windows ftp.exe blocked by the Windows firewall

To change this:

*

*Open Control Panel\System and Security\Windows Firewall and click the link marked Advanced settings on the left hand side.

*In the Windows Firewall with Advanced Security dialog (shown above), click the Inbound Rules link on the left and wait for the primary pane to populate. Look for the two rules marked File Transfer Program. You can click on the Name category heading to sort items alphabetically, as needed.

*For each rule, right-click it and select Properties. Under the General tab, change the Action from Block the connection to Allow the connection. Press OK at the bottom of the dialog when finished.
ex. Updating Windows firewall rules for Windows ftp.exe

*If done correctly, the cirles-with-slashes icons should be replaced with green check marks.
ex. Windows firewall rules for Windows ftp.exe - green check marks

Creating Your Own Rules
On the off chance you wish to manually add (create) these rules yourself, proceed through Steps 1 and 2, except click New rule... on the right-hand side after selecting Inbound Rules.
Make one rule for TCP connections and one rule for UDP connections (protocol options are listed under the Protocols and Ports tab). Make sure that All Ports are allowed. Adjust the Scope tab properties (usually set to Any IP Address ) and the Advanced tab Profiles (ususally  just Private) as needed.
Lastly, under the Programs and Services tab, put e.g. C:\windows\system32\ftp.exe as the program path (if in doubt, you can use where ftp from a command prompt to display the proper path).


text:
Q: How to remove a specific result within an list of results within an array I have the following function which is grabbing results from my database, and then passing some results to a mapbox geocoder. However i want to put some error catching in it so when the geocoder returns a null/undefined value for the address, it'll remove not only that undefined value but everything else attached to that result.
I'm trying to remove a specific element using the .splice method, whilst it's detecting that a undefined value exists, it'll then remove the whole addresses result from the array rather than just the one address and all the other results. (I'm assuming that say if address 3 is undefined, you can remove everything in the array that is at position 3 since that'll be the results that are attached to that address value),
So as described below
       let projects = values.map(elmt => elmt[5])

Is the bit i want to check for any undefined or null valyes coming back from the geocoder.
funciton
  function grabProjects() {
    sql = 'SELECT o.Name, o.Project_Type, o.sDate, o.eDate, p.Role, p.Project_Org_Address, p.Project_Org_Name,p.Country_Name, p.Country_Name, f.Funder_Name, per.Person_Name FROM project_name_table o INNER JOIN project_collaborators p ON o.Project_ID = p.Project_ID INNER JOIN project_funders f ON f.Project_ID = o.Project_ID INNER JOIN person per ON o.person_fk = per.Person_ID GROUP BY o.Project_ID LIMIT 20'
  projectsArray = []

    let query = conn.query(sql, (err, results) => {
      if (err) throw err;

      const geoPromise = param => new Promise((resolve, reject) => {
        geo.geocode('mapbox.places', param, function (err, geoData) {
          if (err) return reject(err);
          if (geoData) {
            resolve(geoData.features[0])
          } else {
            reject('No result found');
          }
        });
      });

      const promises = results.map(result =>

        Promise.all([
          result.Name,
          result.Project_Type,
          result.sDate,
          result.eDate,
          result.Role,
          geoPromise(result.Project_Org_Address),
          result.Project_Org_Name,
          geoPromise(result.Country_Name),
          result.Country_Name,
          result.Funder_Name,
          result.Person_Name

        ])

      );

      Promise.all(promises)
        .then((values) => {

          let pNames = values.map(elmt => elmt[0])
          let pType = values.map(elmt => elmt[1])
          let sDate = values.map(elmt => elmt[2])
          let eDate = values.map(elmt => elmt[3])
          let roles = values.map(elmt => elmt[4])
          let projects = values.map(elmt => elmt[5])
          let collabNames = values.map(elmt => elmt[6])
          let countryNames = values.map(elmt => elmt[7])
          let countryProjects = values.map(elmt => elmt[8])
          let names = values.map(elmt => elmt[9])
          let person_name = values.map(elmt => elmt[10])

          projectsArray.push(pNames, pType, sDate, eDate, roles, projects, collabNames, countryNames, countryProjects, names, person_name)
          console.log(projectsArray.length)

          for (i = 0; i < projectsArray.length; i++) {
            console.log(projectsArray[5][i])
            if (projectsArray[5][i] === undefined) {
              console.log('true')
              projectsArray.splice(i, 1)
              console.log('new length', projectsArray.length)

            }
            else {
              console.log('false')
            }
          }
        })

    });

    return projectsArray

  }

A: I think this code can be refactored better to achieve what you want to do. As noted in my comment you'd be better off not adding the new row unless it passes your test. Something along the lines of:
function grabProjects() {
    // ...
    projectsArray = []

    let query = conn.query(sql, (err, results) => {
      ...//
      results.forEach(async (result) => {
           const parsedResult = result
           const address = await geoPromise(result.Project_Org_Address;
           const country = await geoPromise(result.Country_Name);
           result.address = address;
           result.country = country;

           const propUndefined = Object.keys(result).filter((key) => result[key] === undefined).length > 0;

           if (!propUndefined) {
               projectsArray.push(Object.keys(result).map((key) => result[key]);
           }

        //...

    return projectsArray;
});


text:
Q: tcsh 6 gives error for quote marks I run software that generates following script.
#!/bin/tcsh -f
setenv 'CDS_LIC_FILE' '5280@sjflex5'
setenv 'LM_LICENSE_FILE' '5280@mammoth.xyz.xyz'

This works fine on RedHat EE50.
On RedHat EE60 it is broken and gives following error.
setenv: Variable name must begin with a letter.

I have no control over the script generation process nor can I change the RedHat EE60 installation on the targeted machine. Any other way to patch this and make it work?
Thanks,
Gert

A: I'm not familiar with character classes in regular expressions but you'll get the idea and can add completeness and elegance ;-):
software_that_generates_following_script \
  | sed "s/setenv[ \t]* '\([0-9A-Za-z_]*\)'/setenv \1/" \
  > generated_shell_script

Perhaps that helps...


text:
Q: jQuery and XML, find object that contains children with multiple specific values For a project I have data stored in XML like this:
<xml>
    <sprites>
        <sprite>
            <name>Tile1</name>
            <lat>1</lat>
            <lng>2</lng>
        </sprite>
        <sprite>
            <name>Tile2</name>
            <lat>3</lat>
            <lng>4</lng>
        </sprite>
    </sprites>
<xml>

Through jQuery I want to get a tile object that matches two child values, the lat and lng values.
I found this post which was of great help, but sadly it only has an example of how to search for one matching value. Here's the code I have up to now:

// xml stored in 'xml' var

var findLat = 3;
var findLng = 4;

var mapSprites = $(xml).find("sprites");

var getSprite = $(mapSprites).find("sprite").filter(
    function() {
        return $(this).find('lat').text() == findLat;
    },
    function() {
        return $(this).find('lng').text() == findLng;
    }
);

Sadly getSprite is undefined, as I'm guessing you can't use the filter function as I've tried to use it? The example I linked to has one function as filter and seems to work, but comma separating doesn't seem to work as an AND, which is what I need.
The goal is to be able to give the function a lat and lng value and me being able to extract the <name> value.
Would be thankful for a push in the right direction, I'm pretty new to XML and parsing it through jQuery.

A: filter does not take multiple arguments. So combine it into one using "and".
var findLat = 3;
var findLng = 4;

var mapSprites = $(xml).find("sprites");
var getSprite = mapSprites.find("sprite").filter(
  function() {
    const node = $(this);
    return Number(node.find('lat').text()) === findLat &&
      Number(node.find('lng').text()) === findLng;
  }
);


text:
Q: ActiveMQ/STOMP Clear Schedule Messages Pointed To Destination I would like to remove messages that are scheduled to be delivered to a specific queue but i'm finding the process to be unnecessarily burdensome.
Here I am sending a blank message to a queue with a delay:
self._connection.send(body="test", destination=f"/queue/my-queue", headers={
    "AMQ_SCHEDULED_DELAY": 100_000_000,
    "foo": "bar"
})

And here I would like to clear the scheduled messages for that queue:
self._connection.send(destination=f"ActiveMQ.Scheduler.Management", headers={
    "AMQ_SCHEDULER_ACTION": "REMOVEALL",
}, body="")

Of course the "destination" here needs to be ActiveMQ.Scheduler.Management instead of my actual queue. But I can't find anyway to delete scheduled messages that are destined for queue/my-queue. I tried using the selector header, but that doesn't seem to work for AMQ_SCHEDULER_ACTION type messages.
The only suggestions I've seen is to write a consumer to browser all of the scheduled messages, inspect each one for its destination, and delete each schedule by its ID. This seems insane to me as I don't have just a handful of messages but many millions of messages that I'd like to delete.
Is there a way I could send a command to ActiveMQ to clear scheduled messages with a custom header value?
Maybe I can define a custom scheduled messages location for each queue?
Edit:
I've written a wrapper around the stomp.py connection to handle purging schedules destined for a queue. The MQStompFacade takes an existing stomp.Connection and the name of the queue you are working with and provides enqueue, enqueue_many, receive, purge, and move.
When receiving from a queue, if include_delayed is True, it will subscribe to both the queue and a topic that consumes the schedules. Assuming the messages were enqueued with this class and have the name of the original destination queue as a custom header, scheduled messages that aren't destined for the receiving queue will be filtered out.
Not yet testing in production. Probably a lot of of optimizations here.
Usage:
stomp = MQStompFacade(connection, "my-queue")

stomp.enqueue_many([
  EnqueueRequest(message="hello"),
  EnqueueRequest(message="goodbye", delay=100_000)
])

stomp.purge() # <- removes queued and scheduled messages destined for "/queues/my-queue"

class MQStompFacade (ConnectionListener):

    def __init__(self, connection: Connection, queue: str):
        self._connection = connection
        self._queue = queue
        self._messages: List[Message] = []
        self._connection_id = rand_string(6)
        self._connection.set_listener(self._connection_id, self)

    def __del__(self):
        self._connection.remove_listener(self._connection_id)

    def enqueue_many(self, requests: List[EnqueueRequest]):
        txid = self._connection.begin()
        for request in requests:
            headers = request.headers or {}

            # Used in scheduled message selectors
            headers["queue"] = self._queue

            if request.delay_millis:
                headers['AMQ_SCHEDULED_DELAY'] = request.delay_millis
            if request.priority is not None:
                headers['priority'] = request.priority

            self._connection.send(body=request.message,
                                  destination=f"/queue/{self._queue}",
                                  txid=txid,
                                  headers=headers)
        self._connection.commit(txid)

    def enqueue(self, request: EnqueueRequest):
        self.enqueue_many([request])

    def purge(self, selector: Optional[str] = None):
        num_purged = 0
        for _ in self.receive(idle_timeout=5, selector=selector):
            num_purged += 1
        return num_purged

    def move(self, destination_queue: AbstractQueueFacade,
             selector: Optional[str] = None):

        buffer_size = 500
        move_buffer = []

        for message in self.receive(idle_timeout=5, selector=selector):
            move_buffer.append(EnqueueRequest(
                message=message.body
            ))

            if len(move_buffer) >= buffer_size:
                destination_queue.enqueue_many(move_buffer)
                move_buffer = []

        if move_buffer:
            destination_queue.enqueue_many(move_buffer)

    def receive(self,
                max: Optional[int] = None,
                timeout: Optional[int] = None,
                idle_timeout: Optional[int] = None,
                selector: Optional[str] = None,
                peek: Optional[bool] = False,
                include_delayed: Optional[bool] = False):
        """
        Receiving messages until one of following conditions are met

        Args:
            max: Receive messages until the [max] number of messages are received
            timeout: Receive message until this timeout is reached
            idle_timeout (seconds): Receive messages until the queue is idle for this amount of time
            selector: JMS selector that can be applied to message headers. See https://activemq.apache.org/selector
            peek: Set to TRUE to disable automatic ack on matched criteria. Peeked messages will remain the queue
            include_delayed: Set to TRUE to return messages scheduled for delivery in the future
        """
        self._connection.subscribe(f"/queue/{self._queue}",
                                   id=self._connection_id,
                                   ack="client",
                                   selector=selector
                                   )
        if include_delayed:
            browse_topic = f"topic/scheduled_{self._queue}_{rand_string(6)}"
            schedule_selector = f"queue = '{self._queue}'"
            if selector:
                schedule_selector = f"{schedule_selector} AND ({selector})"

            self._connection.subscribe(browse_topic,
                                       id=self._connection_id,
                                       ack="auto",
                                       selector=schedule_selector
                                       )

            self._connection.send(
                destination=f"ActiveMQ.Scheduler.Management",
                headers={
                    "AMQ_SCHEDULER_ACTION": "BROWSE",
                    "JMSReplyTo": browse_topic
                },
                id=self._connection_id,
                body=""
            )

        listen_start = time.time()
        last_receive = time.time()
        messages_received = 0
        scanning = True
        empty_receive = False
        while scanning:
            try:
                message = self._messages.pop()
                last_receive = time.time()
                if not peek:
                    self._ack(message)
                messages_received += 1
                yield message
            except IndexError:
                empty_receive = True
                time.sleep(0.1)

            if max and messages_received >= max:
                scanning = False
            elif timeout and time.time() > listen_start + timeout:
                scanning = False
            elif empty_receive and idle_timeout and time.time() > last_receive + idle_timeout:
                scanning = False
            else:
                scanning = True

        self._connection.unsubscribe(id=self._connection_id)

    def on_message(self, frame):
        destination = frame.headers.get("original-destination", frame.headers.get("destination"))
        schedule_id = frame.headers.get("scheduledJobId")

        message = Message(
            attributes=MessageAttributes(
                id=frame.headers["message-id"],
                schedule_id=schedule_id,
                timestamp=frame.headers["timestamp"],
                queue=destination.replace("/queue/", "")
            ),
            body=frame.body
        )
        self._messages.append(message)

    def _ack(self, message: Message):
        """
        Deletes the message from queue.
        If the message has an scheduled_id, will also remove the associated scheduled job
        """
        if message.attributes.schedule_id:
            self._connection.send(
                destination=f"ActiveMQ.Scheduler.Management",
                headers={
                    "AMQ_SCHEDULER_ACTION": "REMOVE",
                    "scheduledJobId": message.attributes.schedule_id
                },
                id=self._connection_id,
                body=""
            )
        self._connection.ack(message.attributes.id, subscription=self._connection_id)

A: In order to remove specific messages you need to know the ID which you can get via a browse of the scheduled messages.  The only other option available is to use the start and stop time options in the remove operations to remove all messages inside a range.
MessageProducer producer = session.createProducer(management);
Message request = session.createMessage();
request.setStringProperty(ScheduledMessage.AMQ_SCHEDULER_ACTION, ScheduledMessage.AMQ_SCHEDULER_ACTION_REMOVEALL);
request.setStringProperty(ScheduledMessage.AMQ_SCHEDULER_ACTION_START_TIME, Long.toString(start));
request.setStringProperty(ScheduledMessage.AMQ_SCHEDULER_ACTION_END_TIME, Long.toString(end));
producer.send(request);

If that doesn't suit your need I'm sure the project would welcome contributions.


text:
Q: Apache Gone Down, Can't Restart I've recently setup a LAMP (Fedora 18) server to serve a website on a local network. It was all working, then I made a minor change to php.ini, restarted, and it failed. The only thing that had changed since apache was last started was that a DNS entry was added on the network.
systemctl status httpd.service
httpd.service - The Apache HTTP Server
      Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled)
      Active: failed (Result: exit-code) since Fri, 2013-08-30 09:02:42 BST; 44min ago
     Process: 9769 ExecStop=/usr/sbin/httpd $OPTIONS -k graceful-stop (code=exited, status=0/SUCCESS)
     Process: 9767 ExecStart=/usr/sbin/httpd $OPTIONS -DFOREGROUND (code=exited, status=1/FAILURE)
      CGroup: name=systemd:/system/httpd.service

Aug 30 09:02:42 an648robt.parragon.com systemd[1]: httpd.service: main process exited, code=exited, status=1/FAILURE
Aug 30 09:02:42 an648robt.parragon.com httpd[9769]: httpd (no pid file) not running
Aug 30 09:02:42 an648robt.parragon.com systemd[1]: Failed to start The Apache HTTP Server.
Aug 30 09:02:42 an648robt.parragon.com systemd[1]: Unit httpd.service entered failed state

# vi /var/log/httpd/error_log
[Fri Aug 30 09:02:42.497697 2013] [suexec:notice] [pid 9767] AH01232: suEXEC mechanism enabled (wrapper: /usr/sbin/suexec)
[Fri Aug 30 09:02:42.568620 2013] [unique_id:alert] [pid 9767] (EAI 2)Name or service not known: AH01564: unable to find IPv4 address of "an648robt.parragon.com"
AH00016: Configuration Failed

# vi /etc/hosts
127.0.0.1               localhost.localdomain localhost
::1             localhost6.localdomain6 localhost6
192.168.126.200         an648robt@parragon.com bugagon.parragon.com

# vi /etc/hostname
an648robt.parragon.com

httpd.conf has contained

ServerName 192.168.126.200

and

NameVirtualHost 192.168.126.200

<VirtualHost *:80>
ServerAdmin rich.owen@parragon.com
DocumentRoot /var/www/bugagon
ServerName bugagon.com
ServerAlias www.bugagon.com
ErrorLog /var/log/httpd/bugagon/error_log
CustomLog /var/log/httpd/bugagon/access_log common
</VirtualHost>

SElinux is disabled, the change in php.ini was just changing SMTP localhost to SMTP and the IP address of the MTA server.  I've changed it back, didn't have any visible effect.
...I'm not a Linux expert, but I've looked at all the forums I can find and I haven't been able to fix the issue. Can anyone offer any suggestions?
Thanks in advance, Richard.

A: 192.168.126.200         an648robt@parragon.com bugagon.parragon.com

Replace "@" with "." :)


text:
Q: Blazor app not maintainintg its state on IIS, but works fine on IISExpress I have an issue where I am trying to obtain the context userID and display it. This works great on IISExpress from within VS but has an issue on IIS.
When the page first loads, it displays the username properly. Then a second later it shows the "not authorized" message. I am assuming this is an issue with pre-render/postback of some kind that doesn't happen in VS, but I'm at a loss as to what is causing this. :
@inherits LayoutComponentBase
@inject IHttpContextAccessor httpContextAccessor
@inject AuthenticationStateProvider GetAuthenticationStateAsync
@inject Data.LoginState loginState

<PageTitle>Tools</PageTitle>

        <NavMenu />

            @if (loginState.IsLoggedIn.Equals(false))
            {

You are not authorized

            }
            else{

Welcome: @loginState.username

            }

            @if (loginState.IsLoggedIn.Equals(false)){}
            @Body

@code{
    string? username = String.Empty;
    protected override void OnInitialized()
    {
        try
        {
            username = (httpContextAccessor.HttpContext.User.Identity.Name).Substring(httpContextAccessor.HttpContext.User.Identity.Name.IndexOf(@"\") + 1);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        if (!String.IsNullOrEmpty(username))
        {
            loginState.SetLoginAsync(true, username);
        }
    }
}

LoginState is in Program.cs
builder.Services.AddScoped<LoginState>();

This is using Windows Authentication
Also I get the standard:

Warning: Failed to connect via WebSockets

even with the appsettings.config entry line

A: I have resolved this issue. It requires Windows feature Web Sockets to be installed and then suddenly pre-render or whatever was causing it no longer breaks the functionality.
Web Sockets


text:
Q: Why is this family of measures tight? I am studying a paper where the author is trying to optimize a cost $C$ on the set of probability measures $\gamma\in P(\Omega \times \Omega)$ such that $\pi^{1}_{\sharp}(\gamma) = \mu$, where

*

*$\pi^1(x,y) = x$ for all $x,y\in \Omega$, is the projection onto the first component,

*$\sharp$ symbol denotes the push-back measure,

*$\mu\in P(\Omega)$ is a probability measure, and

*$\Omega$ is the closure of an open, bounded and convex subset of $\mathbb{R}^d.$
To put everything together, is the following family of measures is tight:
\begin{align}
\{\gamma \in P(\Omega \times \Omega): \pi^{1}_{\sharp}(\gamma) = \mu\}?
\end{align}
In the article the author says that we can solve the minimization problem since $\Omega$ is compact, but I don't understand how this works, exactly since if we denote,
\begin{align}
\alpha = \inf\{C(\gamma): \gamma \in P(\Omega \times \Omega), \pi^{1}_{\sharp}(\gamma) = \mu\}
\end{align}
and take a sequence $\gamma_n$ such that $C(\gamma_n)\to \alpha$ then how do we extract a subsequence $\gamma_{n_k}$ that will allow us to proceed further as we apply the direct method from calculus of variations?


text:
Q: Show that $2$ is not prime in $\mathbb Z[\sqrt{-d}]$ for odd prime $d$ I have to show that if $d > 2$ is a prime number, then $2$ is not prime in $\mathbb Z[\sqrt{-d}]$.
The case when $d$ is of the form $4k+1$ for integer $k$ is quite easy: $2\mid (1+\sqrt{-d})(1-\sqrt{-d})$, because the product is equal to $1+d$ and this is even of course. However $2 \nmid 1 \pm \sqrt{-d}$, because we can calculate the norm: $N(2) = 4$, $N(1 \pm \sqrt{-d}) =1+d = 4k+2$ and $4 \nmid 4k+2$.
This argument fails when the remainder after dividing by $4$ is $3$ as far as I can see. So how could I prove the statement in this case?
[EDIT]: The norm is given by $N(a+b\sqrt{-d}) = a^2+b^2d$.

A: I assume that by $\mathbb{Z}\left[\sqrt{-d}\right]$ you mean the numbers of the form $a+b\sqrt{-d}$, where $a$ and $b$ are integers. Note that $a+b\sqrt{-d}$ is divisible by $2$ in this ring if and only if both $a$ and $b$ are even.

A: I'm afraid your assertion is false: $2$ is inert in the ring of integers of $\mathbf Q(\sqrt{ -d})$ if $-d\equiv 5 \mod8$, which is the case for $d=3$.


text:
Q: A deep understanding of javascript closures I'm trying to grasp this bit of code, I know it's a closure but I'm not getting the result I think I should get.
This code returns me an [object MouseEvent], I can't understand why?
I'm adding a function call (updateProduct) to an .addEventListener using this code, and it returns an [object MouseEvent]
function addEventListenerToMinPlus(){
    var x, y
    for(var i = 0; i < productItemAll.length; i++){
        x = productItemAll[i].querySelector(".boxNumbers-min")
        x.addEventListener("click", function(i){return function(i){updateProduct(i)}}(i))
        console.log(x)
    }
}

function updateProduct(jow){
    alert(jow)
}

jsFiddle

A: The browser invokes the event handler with an event object as the first parameter. Your function is declared to take a single parameter ("i"), so when you display it, that's what it is.
I suspect that what you meant was for the "i" inside the event handler to refer to the "i" in the outer function (the loop index). That also won't work, because the various handlers the loop creates will all refer to the same shared variable "i". See this old SO question.

A: The line
x.addEventListener("click", function(i) { return function(i) { updateProduct(i); }(i) }

produces a closure of the inner function
function(i) { updateProduct(i); }

The outer i is in the scope of this inner function, but it is shadowed by its parameter. So, in effect, the inner i represents the first argument passed to the click handler (the MouseEvent). If you want it to retain the value of the index, you have to change its name. Something like this:
x.addEventListener("click",
    function(i) { return function(e) { updateProduct(i); }(i)
}

Now, in the inner function, e is the MouseEvent, and i is the outer index. I have updated the JSFiddle: http://jsfiddle.net/Cdedm/2/. Clicking the minus alerts 0 for the first item and 1 for the second, as expected.

A: that is because you are sending the element as parameter.
You should try doing this:
function addEventListenerToMinPlus(){

    var x, y

    for(var i = 0; i < productItemAll.length; i++){

        x = productItemAll[i].querySelector(".boxNumbers-min")
        x.addEventListener("click", function(){return updateProduct(i)})

        console.log(x)

    }

}

Hope this works,
Regards,
Marcelo

A: I think you are trying to do something like this. Your i will change by the time the click happens so it needs to be set to another local variable, in this case through the parameter on the new function. The click event handler will pass the event object you are getting currently
 function addEventListenerToMinPlus() {
        var x, y;
        for(var i = 0; i < productItemAll.length; i++) {
            x = productItemAll[i].querySelector(".boxNumbers-min");
            x.addEventListener("click", function(i){return function(){updateProduct(i)}}(i));
        }
    }

    function updateProduct(jow) {
        alert(jow);
    }

A: Unless you really really really know what you're doing, you can play about with closures all day and still not get it right with this sort of thing.
A more understandable appraoch by far, with more readable code for most people, is to use jQuery's .data() method to associate data (i in this case) with the element in question so it can be read back when the click event fires, for example :
function addEventListenerToMinPlus() {
    var x, y;
    for(var i = 0; i < productItemAll.length; i++) {
        x = productItemAll[i].querySelector(".boxNumbers-min");
        x.data('myIndex', i);//associate `i` with the element
        x.addEventListener("click", function(i) {
            var i = $(this).data('myIndex');//read `i` back from the element
            updateProduct(i);
        });
        console.log(x);
    }
}

For the record, a working closure would be as follows :
function addEventListenerToMinPlus() {
    var x;
    for(var i = 0; i < productItemAll.length; i++) {
        x = productItemAll[i].querySelector(".boxNumbers-min");
        x.addEventListener("click", function(i) {//<<<< this is the i you want
            return function() {//<<<< NOTE: no formal variable i here. Include one and you're stuffed!
                updateProduct(i);
            }
        }(i));
        console.log(x);
    }
}


text:
Q: How to get songs actual duration like "mm:ss" formate? assetURL = [item valueForProperty: MPMediaItemPropertyAssetURL];
NSLog(@"%@", assetURL); // asset url declares the song url and song path

AVURLAsset* audioAsset = [AVURLAsset URLAssetWithURL:assetURL options:nil]; // declare the audio asset url
CMTime audioDuration = audioAsset.duration; // get duration in cm time
double audioDurationSeconds = CMTimeGetSeconds(audioDuration); // convert audio duration in double

But here is a problem because I get audio duration only in seconds but I need the "MM:SS" format for the song duration.
Please help me. Thanks in advance.

A: NSUInteger audioDurationSeconds = (long)CMTimeGetSeconds(audioDuration);
NSUInteger minutes = floor(audioDurationSeconds % 3600 / 60);
NSUInteger seconds = floor(audioDurationSeconds % 3600 % 60);
NSString *time = [NSString stringWithFormat:@"%02ld:%02ld", minutes, seconds];


text:
Q: /quiet and /qn options don't seem to work for /x{guid} for an installer created with WIX Edited as I found out it does work when executed As Administrator
Please be kind as I'm still very new to Wix installers so it's not wholly clear to me how to ask this efficiently.
Having said that....
I created a .wixproj and it's working fine. When I run the .msi it generates, it installs the product and all the files are there. The product Id is set to a {guid}.
When I run msiexec.exe /x{guid} it works fine. It shows the UI to ask the user whether they want to uninstall the product and when they confirm, it uninstalls it.
When I run msiexec.exe /x{guid} /passive it works fine. The UI pops up and shows the user that it's uninstalling the product.
As Administrator:
When I run msiexec.exe /x{guid} /q it works as long as I run it with elevated privileges, for example from a Command Prompt launched "As Administrator".
Not As Administrator:
When I run msiexec.exe /x{guid} /qn or /quiet or /qn /passive .... it just returns straight to the command line, and the product remains installed, even though I installed the product without elevated privileges.
Is there some property I can set in my .wxs file to get msiexec /x{guid} /q to work, even if it's called by a user without elevated privileges?
I'll be very happy to add code snippets from my .wxs file here but I'm not sure what to include. Here's one part:
<Product Id="guid here"
         Name="our name here"
         Language="1033"
         Version="5.9.2.65"
         Manufacturer="our company here"
         UpgradeCode="a different guid here">
    <Package InstallerVersion="500"
             Compressed="yes"
             InstallScope="perMachine"
             Platform="x86" />

A: Your MSI is declared perMachine (see the Package/@InstallScope). If you want the package to be able to be managed by non-administrators then you'll need to change that to perUser.
Note: per-user packages will not prompt for elevation thus will not be able to install to per-machine locations.
It isn't clear to me what you did to install a perMachine package without administrative rights or an elevation prompt but you didn't provide details about that in your question.
PS: None of this is about the WiX Toolset. This is all about Windows Installer behavior.


text:
Q: Using parentheses in query manager of ArcGIS to define query order? I would like to make a nested query in a single table by means of parentheses in the Query Builder of ArcGIS.
More specific: I only want to select those Columns which start with TR- and in those I want to select those columns that have the attribute 0 (FieldD) and V and E (FieldB) or own (FieldC).

I used the following Syntax:
SELECT * FROM Table WHERE:
FieldA LIKE 'TR_%' AND FieldD = 0 AND FieldB in ('V','B') OR FieldC = 'own'

the problem is that when I use the Operator OR for fieldC ArcGIS also considers KS-

A: You can use the brackets within the query builder to create multiple query's for the same dataset. By using "OR" in between the brackets, this will show the different results within the same layer.
For more information on query building, please see the following link on the ESRI website.
For example:
(FieldA LIKE 'TR_%' AND FieldD = 0 AND FieldB in ('V','B')) OR (FieldA LIKE 'TR_%' AND FieldD = 0 AND FieldB in ('V','B') AND FieldC = 'own')

A: Just put parentheses around the groups that you want to consider together, and everything you want always considered leave separate (or in their own set of parentheses):
FieldA LIKE 'TR_%' AND (FieldD = 0 AND FieldB in ('V','B') OR FieldC = 'own')

Which will select everything that starts TR_ and also meets the criteria within the parentheses.

You might also need to consider whether you need to further break this down:
FieldA LIKE 'TR_%' AND ((FieldD = 0 AND FieldB in ('V','B')) OR FieldC = 'own')

Which will select everything with TR_ that has FieldD = 0 and FieldB in ('V', 'B') OR everything with TR_ that has FieldC = 'own'
or this:
FieldA LIKE 'TR_%' AND FieldD = 0 AND (FieldB in ('V','B') OR FieldC = 'own')

Which will select everything with TR_ and FieldD = 0 and either FieldB in ('V','B') or FieldC = 'own'


text:
Q: Javascript spinning wait hourglass-type thing I'd like to indicate to the user of a web app that a long-running task is being performed.  Once upon a time, this concept would have been communicated to the user by displaying an hourglass. Nowadays, it seems to be an animated spinning circle. (e.g., when you are loading a new tab in Firefox, or booting in Mac OS X. Coincidentally, the overflowing stack in the stackoverflow logo looks like one quarter of the circle).
Is there a simple way to create this effect using Javascript (in particular, JQuery)? Ideally, I'd like to have one of these little spinners as elements in a table, to indicate to the user that the system is still active in processing a pending task (i.e., it hasn't forgotten or crashed). (Of course, I realize it's possible that the back-end has crashed and the front-end still show as an animating spinning thing, it's more for the psychological purpose of the user seeing activity).
And what do you call that spinning thing, anyways?

A: this site will do it for you:
ajaxload
and on OS X it's called the "Beachball" and I like to add "Of Death".

A: http://preloaders.net/en/letters_numbers_words is nice and has lots of categories down the left hand menu that offer more than http://ajaxload.info does, plus options of size and background... ajaxload is looking pretty outdated these days.

A: Google Ajax activity indicator to find lots of images and image generators (the "spinning" image itself is an animated GIF).
Here is one link to get you started.
With the image in hand, use JQuery to toggle the visibility of the image (or perhaps its parent DIV tag). See this link for some more info.
rp

A: I assume you meant something to indicate background activity during an Ajax call.
I tend to have a CSS class which sets the background image to a little animated GIF, with appropriate padding and positioning (remember to turn background-repeat off), and then add and remove that class using a couple of JavaScript helpers called when the Ajax call is started, and when the response callback runs.


text:
Q: How can I enable colored completion in Vim? I understand that this questions could be a bit unclear, but I think an example will help.
I'm in Vim and want to open a file. There are a few files in my directory and some have the same prefix. I used wildmode=longest,list. For
example: Common.pm, Context.pm and Controller.pm. There are more files, but lets keep the example simple.
I want to open Controller.pm, so I type :e and C, followed by <tab>.
So now I see a list like this (pipe | is cursor):
Common.pm      Context.pm      Controller.pm
:e Co|

I need to type the next character that's different to choose the file I want, I need to type the ntr to choose the file. To make it easier to know which characters to type, Vim could highlight the next differing characters like this, but with a bright color instead of brackets.
Co[m]mon.pm      Co[nte]xt.pm      Co[ntr]oller.pm
:e Co|

Does this exist? Or is there a way to make this work with options or scripts?

A: You might want to take a look at NERDTree

The NERD tree allows you to explore your filesystem and to open files and
  directories. It presents the filesystem to you in the form of a tree which you
  manipulate with the keyboard and/or mouse. It also allows you to perform
  simple filesystem operations.


text:
Q: Solr Distributed Search vs. Solr Cloud For Solr 4.3 users, what would be the benefit of using  Solr Distributed Search over Solr Cloud?
Or should all Solr deployment after 4.x just use Solr Cloud, and forget about Solr Distributed Search?

A: *

*Benefit:

There won't be any benefit of Distributed search over solr Cloud. Solr Cloud is currently the most efficient way to deploy solr cluster. It takes care of all your instances using zookeeper and is very efficient for high availability.

*

*Efficient management

Zookeeper decides which of your documents go to which instance.
I have used Solr Cloud in production also and it work wonderfully for high traffic scenarios.

A: Solr cloud it self resembles distributed search via solr.
No you can still use all deployments after 4.x as normal standalone solr instance.Just avoid zkHost parameter in bootstrap for that.

A: JOINs are not supported in SOLR cloud which is a big drawback.
If you want to control shards yourself, means which shard will contain which record, go for distributed search otherwise go for cloud search. Cloud manage all shards itself.
We can have multiple instances of SOLR so in case if one fails, we can move to other in distributed search. In cloud search, ZK manage all these things so if ZK fail, system will be down.


text:
Q: Applying CLT to DCT transform $ x_n $ is a discrete uniform variable on [-128, 127]. I use this function to derive DCT coefficients of $x_n$:
$$ X_k=\sum_{n=0}^{N-1} x_n \cos[\frac{\pi}N (n+\frac{1}2) k] \qquad k=0,...,N-1 $$
The histogram of coefficients ($X_k$) shows a Gaussian distribution. Could anyone please bring a theoretical justification for it? I couldn't apply Central Limit Theorem (and even Lyapunov and Lindeberg CLT) to it.
Thanks in advance.
Added information:
This simple Matlab code represents my experiment:
signal_length = 8192;
data = randi([-128, 127], 1, signal_length);
fdata = dct(data);

subplot(211);
hist(data,signal_length);
title('Histogram of data');
subplot(212);
hist(fdata,signal_length);
title('Histogram of DCT coefficients');

I couldn't add the image of the code output to this post!


text:
Q: How to extract frequency from 32-bit float array using FFT in c++ I'm writing a small sound recognition program in C++. So I have an mp3 file which I sampled using mpg123 and got a 32-bit float array. Now I passed this array to FFT function and got some data. How do I extract frequencies?

A: "Some data" returned by FFT, must be a signal frequency spectrum. Probably it is an array of complex numbers, and to find "most powerful" frequency, you need to find an element with maximum absolute value (modulus). To calculate frequency, ... here was my mistake ... follow a link in Paul R's comment.


text:
Q: How I can Bootstrap data table filter with php foreach Table 1 and 2 picture it work only table 1 data filter:

I want to short data after click on table title when I try with while loop SQL data result can filter the data. If I try on PHP function foreach data table can't filter and I unable to click on edit and delete buttom...
Code For table 1 I use like this

              Courses ID
              Photo
              Name

              <?php
              include 'dbconn/conn.php';
              $sql = "SELECT *, students.id AS id FROM students LEFT JOIN position ON position.id=students.course_id LEFT JOIN schedules ON schedules.id=students.schedule_id";
                $query = $conn->query($sql);
                while($row = $query->fetch_assoc()){
                  ?>

                      <?php echo $row['cardid']; ?>
                      <img src="<?php echo (!empty($row['photo']))? 'images/'.$row['photo']:'./images/profile.jpg'; ?>" width="30px" height="30px"> <a href="#edit_photo" data-toggle="modal" class="pull-right photo" data-id="<?php echo $row['id']; ?>">
                      <?php echo $row['firstname'].' '.$row['lastname']; ?>

                  <?php
                }
              ?>

Code for second table that data pull from function but filter icon didn't show

              Students ID
              Photo
              Name
              Course
              Semester
              Admittion On
              Update

             <?php
              $cust_list = $dbquery->studentinfo();
              foreach($cust_list as $custDetails){
                echo '

                      '.$custDetails['cardid'].'

                      '.$custDetails['firstname'].' '.$custDetails['lastname'].'
                      '.$custDetails['description'].'
                      '.date('M d, Y', strtotime($custDetails['created_on'])).'

                         Edit</button>

                        Delete</button>

                ';
              }
             ?>

A: <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.13.1/css/jquery.dataTables.css">

            Column 1
            Column 2

            Row 1 Data 1
            Row 1 Data 2

            Row 2 Data 1
            Row 2 Data 2

More Info -> https://datatables.net/


text:
Q: how to fixboot and fixmbr on another drive I have builtin SSD which I cannot detach before doing bootrec /fixboot and bootrec /fixmbr
So this commands result in fixing boot sector on builtin SSD not the drive i want.
How to change drive for  bootrec /fixboot and bootrec /fixmbr commands?

A: You cannot change drive for bootrec /fixboot and bootrec /fixmbr commands.
There is some Microsoft logic which determines the drive for fixing MBR, boot sectors and boot files.
You can use bootsect.exe for fixing MBR and boot sectors by specifying the exact drive.
bootsect fixes the specified drive boot sector and the MBR of the disk where the drive is placed.
bootsect /nt60 f: /mbr

writes a Windows 7/8/10 boot sector to drive f: and updates MBR code for booting Windows 7/8/10.
For fixing boot files you can use bcdboot.exe. It creates or fixes boot files on specified drive.
See for example "Repair Windows BCD" for use of bcdboot command.


text:
Q: Google Place Automplete box doesn't display anything I'm trying to implement a Google places Autocomplete field on my website, but it doesn't work. I tried to copy/paste the sample given by Google on a .html file, it perfectly works, like other samples found on the web, like this one So I probably make a mistake on my project (ASP.NET MVC), but I don't know where...
Here is what I've done :
//Loading places library
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>

$(document).ready(function () {
    initialize();

    //Some other asynchronous methods loading some partial views, but with no rapport with Google Maps
}

function initialize() {
    var myOptions = { /*various options*/ };
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

    //4 next lines are given by Autocomplete doc
    var input = document.getElementById('pac-input');
    map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
    var autocomplete = new google.maps.places.Autocomplete(input);
    autocomplete.bindTo('bounds', map);

    /* Implementation of other tools, like
     * DrawingManager
     * MarkerClusterer
     * and OverlappingMarkerSpiderfier
     */

     //This event is given by google
     google.maps.event.addListener(autocomplete, 'place_changed', function() {
        console.log("place_changed"); // Never goes here
        var place = autocomplete.getPlace();
        if (!place.geometry) {
            return;
        }

        // If the place has a geometry, then present it on a map.
        if (place.geometry.viewport) {
            map.fitBounds(place.geometry.viewport);
        } else {
            map.setCenter(place.geometry.location);
            map.setZoom(17);  // Why 17? Because it looks good.
        }
        var address = '';
        if (place.address_components) {
            address = [
              (place.address_components[0] && place.address_components[0].short_name || ''),
              (place.address_components[1] && place.address_components[1].short_name || ''),
              (place.address_components[2] && place.address_components[2].short_name || '')
            ].join(' ');
        }
    });
}

And the HTML is just
<input id="pac-input" class="controls" type="text" placeholder="Enter a location">

This WORKS on a simple .html file. I can see the request to Google's servers in the "Network" tab of my console, like  :

But in my project, the field appears with the placeholder, but when I type in, there's just ... Nothing. Like a simple text field. Anything in the console, just... anything, except the library places script which is correctly downloaded.
I tried to change z-index, but the problem is still the same. I also tried to put the Autocomplete field elsewhere on the page (not on the Google Map itself) it doesn't care.
I also tried to change the $(document).ready by google.maps.event.addDomListener(window, 'load', initialize); and the problem is ... the same !
Oh, and by the way, I also try with the Autocomplete Search Box, the problem is exactly the same.
Is there something obvious I'm missing ? Something to activate in Google Developpers console, to include in my project, anything... I'm new to javascript and jquery, so maybe I forget a fundamental thing ?


text:
Q: Change chosen SQL Server database in distributed database with Invantive Data Hub We run a daily job to load Exact Online into a SQL Server database for reporting purposes with Sumatra.
We now want to redirect the SQL insert statement to another database on the same SQL Server.
Connections are:
<connection name="EOLIN_MUT" ...>
  <database order="20" alias="eol" provider="ExactOnlineAll" connectionString="apiUrl=https://start.exactonline.nl;api-client-id=SOMETHING;apiredirecturl=https://eolclientredirect.invantive.com" />
  <database order="10" alias="sql" provider="SqlServer" connectionString="Data Source=something;UID=datahub;PWD=moresecrets" AllowConnectionStringRewrite="false" />

I've already change the name of the connection from EOLIN to EOLIN_MUT but without result.
How can I redirect to another database?

A: You have three alternatives that you can use:

*

*Change default database of user

*Change default database on connection

*Switch database.

To change default database of the user, have you SQL Admin change it in SQL Server. There is no database listed yet in your connection string.
To change default database of connection, see connectionstrings.com on SQL Server. Add database=NAME; to your connection string in settings.xml.
To switch database, change the Invantive SQL script you use by adding:
use XYZ@sql

where XYZ is the intended default database on SQL Server and sql is the alias on the SQL Server data container.
With use, you can also select multiple data containers, such as:
use XYZ@sql, 123123@eol, 456456@eol

which select XYZ on SQL Server and companies/administrations/divisions 123123 and 456456 on Exact Online with alias eol. More documentation on use statements.
Please note that the default SQL Server provider of Invantive does NOT allow you to select multiple database to be used for a query. So when using Exact Globe or Navision, you will need to explicitly include all companies in your query.


text:
Q: Characters of the fundamental representations of $SU(3)$ Let us denote $3$ and $\bar{3}$ the fundamental representations of $SU(3)$.
According to my lecture notes, the characters read as follows:
$\chi_{[3]} = e^{\omega_1} + e^{\omega_1 - \alpha_1} + e^{\omega_1 - \alpha_1 - \alpha_2}$
$\chi_{[\bar{3}]} = e^{\omega_2} + e^{\omega_2 - \alpha_1} + e^{\omega_2 - \alpha_1 - \alpha_2}$
How does one derive that result?
I know that it is somehow related to the Weyl-character formula, and that $\omega_1, \omega_2$ are the weights and $\alpha_1 , \alpha_2$ are the roots, but I am having big trouble understading those concepts and applying them to a specific example.
(I would also appreciate a clarification on which are the fundamental representations of $SU(3)$, i.e., what do exactly $3$ and $\bar{3}$ stand for).


text:
Q: What's the best way to change the working tree to a specific commit before bisecting? My usual workflow when starting a git bisect session is:
git bisect start          # start a bisect session
git bisect bad            # I noticed that the current state is broken

Now, often I know that things worked in the past, but I don't know yet which version was good, so I usually want to revert my working tree to an older state, build, test, repeat until I find a working version which I can mark with git bisect good.
What's the best way to do the "revert my working tree to an older state" step? git reset --hard <some_good_rev>? git checkout <some_good_rev>? Something else? Please justify your answer.

A: I usually don't know where the good rev is, so I've got to find it.  Guess how far back might be good.  Let's say, 32 revs.  Starting from the tip of a branch, and with clean working directories:
$ git checkout HEAD~32

Run the test.  If it's a good rev, start bisecting.  If it's not, go back some more:
$ git checkout HEAD~32

Rinse, lather, repeat.
Why "git checkout?"  Because "git reset" will change which commit the branch points to as its "tip", but git checkout will not.

A: If you don't know for sure any version where the functionality worked (the commit that introduced the functionality?), you seem to lose a lot (all?) of the benefit of a bisect.  If you do know that there was at least one commit where the functionality worked, even if it isn't necessarily the most recent commit where the functionality worked, just flag that one as good.  Otherwise, you're basically doing a bisect yourself.


text:
Q: gephi cannot find java 1.8 or higher with JDK 16 I've installed JDK 16.0.1 (folder C:\Program Files\Java) and tried to run Gephi but it appears the error "cannot find java 1.8 or higher" so I searched for how to solve this and every answer involves doing something with the JRE directory, so I installed the JRE 8u291, it installed on the same folder as JDK (C:\Program Files\Java), but the solutions say it's supposed to be on the program files (x86) and I tried it so many times i'm so angry please help

A: please look at https://github.com/gephi/gephi/issues/1787
I've faced with the same problem.
After pointing gephi to jdk home folder got swing exception after gephi start, UI was not loaded properly.
After installing JRE8 and pointing gephi to JRE home everything is ok.


text:
Q: Ansible configuration files I'm just starting out with Ansible and I'm having some issues with the configuration file.
Initially, I wasn't being able to ping hosts because my ansible socket path file was too long. I changed this by referring to: Ansible: SSH Error: unix_listener: too long for Unix domain socket and changed my path to control_path=~/%%h‐%%r.
What are these escape sequences (%%h and %%r) for? Is there any documentation available? Is there a way to make my path smaller? Is there an escape sequence for IP address?
Thanks!

A: This is not really related to Ansible. The control path is where SSH stores its sockets for multiplex sessions.
http://man.openbsd.org/ssh_config.5

ControlPath
  Specify the path to the control socket used for connection sharing as described in the ControlMaster section above or the string "none" to disable connection sharing. In the path, '%L' will be substituted by the first component of the local host name, '%l' will be substituted by the local host name (including any domain name), '%h' will be substituted by the target host name, '%n' will be substituted by the original target host name specified on the command line, '%p' the destination port, '%r' by the remote login username, '%u' by the username and '%i' by the numeric user ID (uid) of the user running ssh(1), and '%C' by a hash of the concatenation: %l%h%p%r. It is recommended that any ControlPath used for opportunistic connection sharing include at least %h, %p, and %r (or alternatively %C) and be placed in a directory that is not writable by other users. This ensures that shared connections are uniquely identified.

So, there is no placeholder for the hosts IP. Making the path shorter always is a compromise. ~/%%h‐%%r already is the shortest possible solution that is not unsafe. If you can guarantee you do not ever use another remote user to connect to the host it might be safe to drop %r and only use %h.
If the problem is that your hostname is too long, maybe creating an alias in your .ssh/config is a solution?
host short-name
    hostname very-long-name-that-makes-control-path-location-exceed-the-possible-length-limitation

%n then should refer to short-name which can be used instead of %h.

A: Add this to your ansible.cfg file. It may be beside your project or in /etc/ansible/ansible.cfg
[ssh_connection]
control_path = %(directory)s/%%C

In new ansible versions no need for this variable.


text:
Q: How to get the highest page number using xpath? I've written an xpath expression to get the highest value of page number from some html elements. However, with the below xpath I'm getting the last text which is Next Page in this case. I wish my xpath act in such a way so that I can get the highest number, as in 6 using it.
The elements upon which the xpath should be applied:
content = """

Page 1
Page 2
…
Page 6
Next Page

"""

What I've tried so far:
from lxml.html import fromstring

root = fromstring(above_content)
pagenum = root.xpath("//*[contains(@class,'page-numbers')][last()]/span")[0].text
print(pagenum)

Output I'm having:
Next Page

Output I wish to have:
6

A: You can use exact class name to avoid fetching Next link:
//a[@class="page-numbers"][last()]

Note that contains(@class,'page-numbers') will return you links with numbers and Next while @class="page-numbers" numbers only