text:
Q: MYSQL display all records and count related records I have 3 tables teacher subject and assignments.  When a teacher logs in, I want to display all the subjects regardless if he is the teacher and regardless if there is related records or not.  If there is no related records (assignments) i want it to display 0.
Teacher Table: Teacher_PK, Teacher_name
Subject Table:  Subject_PK, Teacher_fk, Subject_name,
Assignments Table: Assignment_PK, Subject_fk, assignment_name

Right now i have it like this:
"SELECT *, count(a.subject_fk)
        FROM assignment AS b
        LEFT OUTER JOIN subject AS a
        ON a.subject_fk = b.subject_PK
        WHERE a.teacher_fk = $sessionVar
        GROUP BY b.subject_fk
        ORDER BY b.subject_name ASC";

The problem with this query is that it does not show all subjects, it only shows the subject if there are related tables.
English (3)
Math(2)

What i want it to display is
English(3)
Math(2)
Gym(0)
Science(0)

Thank you for any help.
All subjects in the Subject table

A: SELECT
  s.*,
  count(a.assignment_pk) as numAssignments
FROM
  Subject s
   LEFT OUTER JOIN Assignments a ON
    s.Subject_pk = a.Subject_fk AND
    a.teacher_fk = $sessionVar
GROUP BY
  s.*
ORDER BY
  s.subject_name ASC

edit - moved the filter on teacher id to the outer join section


text:
Q: div wont fill 100% width on mobile Chrome/Safari Browser I'm trying to make a simple website where the header is stretching 100% wide of the browser, then have the content below the header to be 1100px wide centered. This is working perfectly fine on desktop browsers (Chrome, Safari, Firefox). On mobile however there is issues. I haven't done any responsive CSS, but the image in the header should still fill the width of the browser. Here is my code related to this header.
HTML:

Headline

Some text goes here

CSS:
.featured {
  width: 100%;
  height: 500px;
  position: relative;
  background-size: cover;
  background-position:center center;
  overflow: hidden;
  cursor: pointer;
  box-sizing: border-box;
  z-index: 100;
}

.featured-details {
  color: #ebebeb;
  bottom: 10px;
  width: 1100px;
  left: 0;
  right: 0;
  margin-left: auto;
  margin-right: auto;
  position: absolute;
  z-index: 150;
}

As you can see it works fine on desktop: http://sistestopp.com/uploads/desktop.png
But on mobile the header isn't 100%: http://sistestopp.com/uploads/mobile.png
(the footer is doing the same stuff).
Any suggestions?

A: Your problem is in div.container. Its width is fixed at 1100px. In mobile device has resolution width smaller than that number, browser must scale to show the whole page and then your problem appear. If you add this line to header, you will see it clearly.
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no" />

Solution is very simple
.container{
    /*width: 1100px;*/
    max-width: 1100px;
}

Hope this help.

A: As far as i got your point then solution for that.
Add this css with background image
background-repeat: no-repeat;
background-size: 100% auto;

and your this class .featured-details should have width:100% or else the heading text will disturb your header image..
chech this screenshot..
Hope i was able to help or else if any issue then let me know..
Thank you :)

A: Better to use CSS 3 vh and vw here.
width:100vw;

Check more about vh and vw in the below links.

http://www.w3.org/TR/css3-values/#lengths
http://snook.ca/archives/html_and_css/vm-vh-units

redpajama_set_name: RedPajamaStackExchange


text:
Q: Duplicity with GPG 2.1 I am trying to configure daily backups from my computer to a remote server using duplicity, but for some reason duplicity does not want to cooperate with GPG at all. I have never consciously used GPG before and I am experiencing some behaviors which I do not understand.
I generated a key pair using gpg:
gpg --quick-gen-key myName

Then I use duplicity to backup some directory:
duplicity --encrypt-key myName some-directory file://backup

this seems to work fine because I get no errors.
if I now run the exact same command again, which should make an incremental backup and encrypt the increment with the same public key, I get the following gpg errors:
===== Begin GnuPG log =====
gpg: ebncrypted with 1024-bit RSA key, ID FA5B21B4E274D59A, created 2019-08-14 "myName"
gpg: public key decryption failed: No passphrase given
gpg: decryption failed: No secret key
===== End GnuPG log =====

I have looked around and found a question about something similar on superuser but after creating and editing the gpg.conf and gpg-agent-conf files I am still getting the same errors.
Is anyone using duplicity with gpg keys succesfully and can tell me what I am doing wrong?
gpg version is 2.2.4 and duplicity 0.7.17.


text:
Q: Printing row of a list I'm trying to label rows and columns of my matrix.
I can create columns but I can't seem to properly create rows
Here's what I've done:
matrix = [[1,0,1],[1,0,1],[1,0,1]]
row = 0
col = 0
dim = len(matrix)
for i in range(dim):
    print "\t", "col",i,

for r in range(0,dim):
    print
    for c in range(0,dim):
        print "\t", matrix[r][c],

Anyone have a good idea?
This is the result i get
col 0   col 1   col 2
1       0       1
1       0       1
1       0       1

I'm looking to print:
      col 0     col 1   col 2
row0    1       0       1
row1    1       0       1
row2    1       0       1

A: matrix = [[1,0,1],[1,0,1],[1,0,1]]
print '\t' + '\t'.join('col{}'.format(i) for i in xrange(len(matrix[0])))
for i,row in enumerate(matrix):
    print 'row{}\t'.format(i) + '\t'.join(str(x) for x in row)


text:
Q: How to make a menu looking like the one in QuizUp I gave a look on QuizUp and I would like to make a similar menu on my iphone application.
I don't understand how they made the menu. It looks like a table view controller, but a new menu appears under the cell when the user tap on it.
Can someone give me some clues. Is it possible to do that with the native iOS SDK ? How ?

A: According to the developer of Quiz Up, the app was made using Cocos2D.
That being said, it is also possible to do it using a UITableView. Theres just a couple things you would need to do. The first is get tableView:heightForRowAtIndexPath: to return a different height for the row(s) you want to be expanded. For example, if you only want one row expanded you could use the following.
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([[tableView indexPathForSelectedRow] isEqual:indexPath]) {
        return 100.0f;
    }
    return 44.0f;
}

Then what you need to do is call beginUpdates and endUpdates on your tableview whenever you want the height to update.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView beginUpdates];
    [tableView endUpdates];
}

After that, you just need to layout your cell so that when it's expanded, it shows the additional view and when its collapsed it should hide that view.


text:
Q: How do I locate and disable background PGP and Kapersky start up programs? I had to uninstall Kapersky by deleting the application but the item still shows up on my task bar when I restart.
Also, I have PGP installed on my mac, but when I telnet to port 25 of another server, I get a "PGP Universal Proxy" service that I want to disable.
I don't see any way to disable either of these in the default GUI and assume this is buried in some OSX specific configuration.  Where should I look?


text:
Q: Merging multiple nested dictionaries but taking only the last one in python3 For each file/doc, I print out the result in dictionary format, there are 2 dictionaries for each file/doc, I want to merge them into 1 dictionary without overwriting, but after merge, it prints out only the second dictionary.
Thanks a lot in advance!
Solution before merge:
defaultdict(<class 'list'>, {'edu_02_blond_dejouer': defaultdict(<class 'list'>, {'ImageFieldCheckers': defaultdict(<class 'list'>, {"['print', 'GRAPHIQUE 2\\xa0: Qualification des aspects de l'activité GG par les institutions d'accueil (en %). Source\\xa0: LISER, Base de données «\\xa0GG_institutions\\xa0», 2020. (N=54\\xa0/ 32 femmes, 22 hommes)\\n[C3. Comment qualifiez-vous les aspects suivants de l'activité GG\\xa0?] \\nGuide de lecture / L'aspect pédagogique du GG est qualifié de «\\xa0bon\\xa0» par 88 % et de «\\xa0moyen\\xa0» par 11 % des répondant·e·s\\xa0: 2 % de non réponse', 'graphique2.png]]]']": ['Add 3 square brackets at beginning', '4 fields are required'], "['[[[image', 'print', 'SCHEMA 1\\xa0: Méthodologie de la mesure de l'impact du GG', 'schema.png']": 'Add 3 square brackets at end', 'graphique.png': 'Image not existing in assets'})})})

defaultdict(<class 'list'>, {'edu_02_blond_dejouer': defaultdict(<class 'list'>, {'MetadataCheckers': defaultdict(<class 'list'>, {'ENG Abstract': 'The content is missing (it is required)'})})})

Wrong solution after merge:
defaultdict(<class 'list'>, {'edu_02_blond_dejouer': defaultdict(<class 'list'>, {'MetadataCheckers': defaultdict(<class 'list'>, {'ENG Abstract': 'The content is missing (it is required)'})})})

Solution that I expect after merge:
defaultdict(<class 'list'>, {'edu_02_blond_dejouer': defaultdict(<class 'list'>, {'ImageFieldCheckers': defaultdict(<class 'list'>, {"['print', 'GRAPHIQUE 2\\xa0: Qualification des aspects de l'activité GG par les institutions d'accueil (en %). Source\\xa0: LISER, Base de données «\\xa0GG_institutions\\xa0», 2020. (N=54\\xa0/ 32 femmes, 22 hommes)\\n[C3. Comment qualifiez-vous les aspects suivants de l'activité GG\\xa0?] \\nGuide de lecture / L'aspect pédagogique du GG est qualifié de «\\xa0bon\\xa0» par 88 % et de «\\xa0moyen\\xa0» par 11 % des répondant·e·s\\xa0: 2 % de non réponse', 'graphique2.png]]]']": ['Add 3 square brackets at beginning', '4 fields are required'], "['[[[image', 'print', 'SCHEMA 1\\xa0: Méthodologie de la mesure de l'impact du GG', 'schema.png']": 'Add 3 square brackets at end', 'graphique.png': 'Image not existing in assets'})})}), defaultdict(<class 'list'>, {'MetadataCheckers': defaultdict(<class 'list'>, {'ENG Abstract': 'The content is missing (it is required)'})})})


text:
Q: Longest increasing subsequence using 2-3 tree While preparing for my data structures final I came across this problem:
A - a given array of integers of length n.
Propose data structure with supports the following operations:
Init(A) - initialisation of the structure given the array A. Worst case complexity: O(nlogn).
LengthOfLongest() - returns the length of the longest monotonically increasing s of A (elements). Worst case complexity: O(1).
I know that it is a well known problem, and I'm aware of the relevant wiki article. However the solution provided there is not intuitive to me.
I was given a hint that this problem can be solved as well with 2-3 rank tree for instance.
Can someone explain me the solution using 2-3 tree?
Example:
For array A = {10,9,11,8,12,7,13}
The longest subarray is {10, 11, 12, 13} and its length is 4.

A: This is a well-studied problem called longest increasing subsequence, which could be solved in O(n log n) time. See http://en.wikipedia.org/wiki/Longest_increasing_subsequence


text:
Q: Having trouble getting NUnit's Assert.Throws to work properly I could have sworn that I've used NUnit's Assert.Throws to determine whether or not a particular exception gets thrown from a method, but my memory has failed me before.  I read this post here on SO, but it didn't answer my question, as I know the correct syntax, and I don't want to do anything with the exception that gets returned (I don't want to look at the Exception's members, though this could be useful down the road).
I wrote unit tests to prove my lack of understanding in the use of Dictionary, and couldn't get it handle the KeyNotFoundException that gets thrown.  Instead of NUnit catching it and passing the test, I get an unhandled KeyNotFoundException error when I run.  I verified that I don't have the VS IDE set up to break on thrown .NET exceptions.
I've tried this two ways:
Assert.Throws( typeof(KeyNotFoundException), () => value = prefs["doesn't exist"]);

and
Assert.Throws<KeyNotFoundException>( () => value = prefs["doesn't exist"]);

but both result in an unhandled exception.  What am I missing here?
UPDATE seems like others can't reproduce this.  Here's a screenshot:

A: This is an old thread, but try turning off Enable Just My Code in Visual Studio under Tools->Options. With that on, the debugger is trying to be helpful and stops at the last possible point within your code before the exception gets swallowed.
Or, at least that's my understanding of it.
If you turn off Enable Just My Code, the Assert.Throws should work correctly.

A: Not a direct answer, but I personally prefer to tag my tests with
[ExpectedException(typeof(KeyNotFoundException))]
public Test ShouldDoTheStuff() {

  ...

}

Does this work for you?  I don't actually see anything wrong with your code per se.

A: The debugger is stating that your exception is not being handled by user code, which is technically true.  To demonstrate, I'll use the sample test sgreeve provided
[Test]
public void demonstrateThatExceptionThrown()
{
    string value;
    Dictionary<string, string> test = new Dictionary<string, string>();
    Assert.Throws(typeof(KeyNotFoundException), () => value = test["h"]);
}

When you execute it, you will receive a warning in VisualStudio that the exception is unhandled in user code. If you look at the callstack, you will see something like
[External Code]
CodeTests.DLL!CodeTests.MiscTests.demonstrateThatExceptionThrown.AnonymousMethod()
[External Code]
CodeTests.DLL!CodeTests.MiscTests.demonstrateThatExceptionThrown()
[External Code]

Because you have specified a delegate, the exception is happening within the "AnonymousMethod" that was created. This is being called by the .Net framework. The debugger is stopping because your delegate isn't handling the exception before it gets passed back to the framework. It doesn't care that further up the stack it might be handled in your code (perhaps since there is no way to guarantee that the external code will handle the exception correctly.)
To have VisualStudio see this as a handled exception, use the ExpectedException attribute and remove the delegate, like so:
[Test]
[ExpectedException(typeof(KeyNotFoundException))]
public void demonstrateThatExceptionThrown()
{
    string value;
    Dictionary<string, string> test = new Dictionary<string, string>();
    value = test["h"];
}

A: EVEN MORE RECENTLY UPDATED ANSWER!
After our conversation in the comments added to this answer, I suspect that the nunitit test runner is the problem here. I don't believe there's anything wrong with your test as I have no problem executing it either using NUnit GUI or the excellent Resharper test runner.
UPDATED ANSWER
After seeing your screen shot, I tried stepping through my test with the debugger and saw exactly the same prompt about the unhandled exception. If I carry on stepping past that error, the test passes when I reach the end of the assertion.
When I run the test in none-debug mode using either the NUnit GUI or the Resharper 4.5 test runner, the test passes as expected every time.
Sorry to ask the obvious question, but what are you executing your test with? i.e. which test runner?
The exact code I've executed is:
using System;
using System.Collections.Generic;
using NUnit.Framework;

namespace ClassLibrary1
{
    [TestFixture]
    public class DictionaryTest
    {

        [Test]
        public void demonstrateThatExceptionThrown()
        {
            string value;
            Dictionary<string, string> test = new Dictionary<string, string>();
            Assert.Throws(typeof(KeyNotFoundException), () => value = test["h"]);
        }
    }
}


text:
Q: ObservableCollection.Remove doesn't work, even if the object is in the list I'm working in C#. I want to remove a Catalog (an object type i've defined earlier) from an ObservableCollection<Catalog>.
I know that when you call Remove,Contains or Add... the VM calls Equals to "locate" the object you want to add or remove. So here are my Catalog.Equals definitions :
public override bool Equals(object obj)
{
    Catalog cat = (Catalog)obj;
    return (this.Name.Equals(cat.Name));
}

public bool Equals(Catalog cat)
{
    return (this.Name.Equals(cat.Name));
}

But when I execute myCollection.Remove(catlg) (catlg is of type Catalog), I get an InvalidCastException on the following line : Catalog cat = (Catalog)obj.
Why an invalid cast here ? And why Equals(Catalog cat) isn't called here, instead of Equals(object obj) definition ?
Of course, Remove doesn't work, even if Console.WriteLine(myCollection.Contains(catlg)) is true.

A: Try implementing the IEquatable<Catalog>.
And get rid of the override perhaps?

A: One Solution could be to use the linq extension methods.
var catalogToRemove = Catalogs.Single(p => p.Name == catalogName);
Catalogs.Remove(catalogToRemove);

An other could be to implement IEquatable
public class Catalog : IEquatable<Catalog>
{
    public string Name { get; set; }

    public bool Equals(Catalog other)
    {
        return Name == other.Name;
    }
}

The second sulotion is good if you do not have the exact object you want to remove.
For example you could create a new Catalog object, set the name to the object you want to remove and use that new object in the Remove method of the collection. If you do not implement IEquatable this will not work since the new object is not exactly the same object that is contained in your collection.

A: Since you didn't implement IEquatable, the default for the Remove method is to use the Object.Equals method, and not your generic Equals(Catalog);
This is what the documentation states for IList.Remove:

If type T implements the IEquatable generic interface, the equality
  comparer is the Equals method of that interface; otherwise, the
  default equality comparer is Object.Equals.

This is what the MSDN documentation states about the IEquatable<T>.Equals:

If you implement Equals, you should also override the base class
  implementations of Object.Equals(Object) and GetHashCode so that their
  behavior is consistent with that of the IEquatable.Equals method.
  If you do override Object.Equals(Object), your overridden
  implementation is also called in calls to the static
  Equals(System.Object, System.Object) method on your class. In
  addition, you should overload the

There might be a compare somewhere in your code, where Equals(object) is called with another type that is not a Catalog, via the Equals(System.Object, System.Object), which causes the InvalidOperationException.
Use the as keyword instead of an explicit cast, and make sure you implement IEquatable<Catalog>:
public override bool Equals(object obj)
{
    Catalog cat = obj as Catalog;
    if (cat == null)
    {
       return;
    }
    return (this.Name.Equals(cat.Name));
}

A: You must implement GetHashCode (link)
public override bool Equals(object obj)
{
    Catalog cat =  obj as Catalog;
    if (cat == null)
    {
        return false;
    }

    return (this.Name.Equals(cat.Name));
}

I'm using a different cast than you. With the as, you can check if it'is correct.
public bool Equals(Catalog cat)
{
    return (this.Name.Equals(cat.Name));
}

public int GetHashCode(object obj)
{
    // implement your hash code logic here
    return obj.ToString().GetHashCode();
}


text:
Q: What is the benefit of multiple people working in a store? In the game Tiny Tower, you can assign up 3 people to work in a store. What are the benefits of having a store fully staffed?

A: Fully staffed stores allow you to fully stock stores. Each additional stock increases in value and quantity available.  This allows you to keep a store open longer, sell more stuff, and make more money.
Additionally, staffing stores with 3 dream jobs will give you the x2 stock per slot.
Outside of Food Floors, which typically carry low stock and generate low profits, every other type of floor should have 3 workers to maximize profits.

A: I know this is kinda late, but depending on the number on the bitizen for the floor type you employ them in, will make each item cheaper by that number as a percent.  This number is added to the others for the bitizens employed there.  That added percentage is universal to each 3 items on that floor.

A: Having more people work at stores allows you to get more items for the store.

A: Once a store is fully stocked, there is no benefit to keeping the Bitizens there.  Keep the floor fully-staffed until it is fully-stocked, then you are free to shuffle the Bitizens around as you please with no penalty while the supply runs down.  I do this when I have more job openings than Bitizens.
In general though, it's best to leave the Bitizens with their dream job at their dream job, or else you may forget about the matchup.


text:
Q: Push notification on ios9 app My app communicates with a backend nodejs server (node, express and mongoose).
I store users and messages in MongoDB.
When a user sends a new message to another one:

*

*I update the messages DB

*I send to the destination user a push notification

I have few questions regarding push notifications handling and performance:

*

*Is it a better way to have an APN server separate from my backend server (with node-pushserver for example: https://www.npmjs.com/package/node-pushserver) and request for a push notification with a REST api call from my iOS app

or

*

*Is it a better way to directly implement the push notification in my nodejs server when the messages MongoDB is updated (with node-apn for example: https://github.com/argon/node-apn)

I precise thay my backend server will be host by AWS soon.
If there is another solution better than above, feel free to correct me :)
Thank you for any feedback


text:
Q: changing the button name when clicked I have a bootstrap button which displays "Show User Information" as the button lable. When user click on the button, i want to change the label to "Display Only Users" and again when user click on "Display Only Users" it has to change the button label to "Show User Information".
 <button class="btn btn-primary" type="button" onclick="myFunction()" id="myButton1">Show User Information</button>

js code:
  function myFunction() {
        var elem = document.getElementById("myButton1");
         if (elem=="Show User Information") elem.value = "Display Only Users";
        else elem.value = "Show User Information";
}

The above js code is not changing the button label when clicked. Any inputs?

A: Add value attribute to the button ,
value="Show User Information"

and retrieve in js using and compare
ele.value=="Show User Information"

A: You need to check the text of the button, not the element itself

function myFunction() {
  var elem = document.getElementById("myButton1"),
      text = elem.textContent || elem.innerText;

  if (text === "Show User Information")
    elem.innerHTML = "Display Only Users";
  else
    elem.innerHTML = "Show User Information";
}
<button class="btn btn-primary" type="button" onclick="myFunction()" id="myButton1">Show User Information</button>


text:
Q: jquery Form - Data im currently trying to learn forms and save the value in a database. And i found "jquery form" from malsup very easy to use.
But i now i have a problem.
I want to send additional data with the informations from the form.
So how i understand it, it should work like that. using 'data'. But the information within data(key1, key2). I cant "read" them in my php file.
Here are the jquery form options and the php file.
var options = {

        data: {
    "key1": "value1",
    "key2": "value2"
},
        beforeSend: function()
        {
            console.log("beforeSend");
        },
        uploadProgress: function(event, position, total, percentComplete)
        {
            console.log("uploadProgress")
        },
        success: function(responseText, statusText, xhr, $form, response)
        {
            console.log("success")
        },
        complete: function(data, response)
        {
            //response text from the server.
            console.log("complete")
        }

    };

<?PHP

    $adress = $_POST['searching_adress'];
    $productname = $_POST['searching_productname'];
    $city = $_POST['searching_city'];
    $description = $_POST['searching_description'];
    $searchingfloor = $_POST['searching_floor'];
    $mail = $_POST['searching_email'];

    $key1 = $_POST['key1'];

    var_dump($_POST);

    $response = array('adress' => $adress, 'productname' => $productname,'city'=>$city,'description'=>$description,'searchingfloor'=>$searchingfloor,'mail'=>$mail,'pathid'=>$xhr,'type'=>$key1);
    echo json_encode($response);

?>

A: According to Jquery Form plugin When form is submitted the form fields according to thier names will be posted to respective server file.
So here if you want to add extra parameters then you can simply add some hidden fields in your form and try to execute  your code.
When form is posted you will get the extra fileds too.

A: If you extra parameter to passed with jquery form. Use hidden field inside the form. So when form is submitted, it send extra parameter to php file

A: Check if the keyvalues are really posted from the other page. If not you can create a hidden input to post the values. This also works for aditional information.
Here is the code:
<input type="hidden" value="test" name="test" />


text:
Q: Typescript type declaration for a complex function that returns itself I have the following javascript function that returns a function containing additional methods given in the object arguments.
I think the code will be more understandable than an explanation:
var scopeFunction = (object) => {

  // create main function if it doesn't exist
  if (!object.main) object.main = function(){
    alert("No main function for this scopeFunction");
  };

  // add all object keys to the main function that will be return
  _.each(object, function(d,i){ object.main[i] = d; });

  // return main function
  return object.main;

};

I want to define properly this code in typescript, this is what I did, but atom typescript (that's where I've tested it) throws errors when I try to access the keys of my returned function object.
This is how my current code look:
// TYPES
namespace ScopeFunction {

  export interface Function<Obj extends MakerObject, Key extends keyof Obj>  {
    (): Obj["main"];
    [key: Key]: Obj[Key];
  }
  export interface MainFunction {
    (...args:any[]) : any;
  }
  export interface MakerObject {
    [key: string]: any;
    main?: MainFunction;
  }

  export type Maker = <Obj extends MakerObject, Key extends keyof Obj>(object:Obj) => ScopeFunction.Function<Obj, Key>;

}

// FUNC
var scopeFunction:ScopeFunction.Maker = (object) => {

  // create main function if it doesn't exist
  if (!object.main) object.main = function(){
    alert("No main function for this scopeFunction");
  };

  // add all object keys to the main function that will be return
  _.each(object, function(d,i){ object.main[i] = d; });

  // return main function
  return object.main;

};

// TEST
var test = scopeFunction({
  a: 1,
  b: "3",
  main: () => { console.log("testLog"); return 0; }
})

var test1 = test(); // WORKS OK
var test2 = test.main(); // ALERT: Property 'main' doesn't exist on type 'Function<{ a: number; b: string; main: () => number }, "main" | "a" | "b">'
var test3 = test.a; // ALERT: Property 'a' doesn't exist on type 'Function<{ a: number; b: string; main: () => number }, "main" | "a" | "b">'

Any idea where the problem is in my definition?

A: There are several problems with your code:

*

*The definitions don't compile [key: Key]: Obj[Key] is not valid, and indexer argument must be either number or string (those and only those types are valid). You need to use a mapped type instead.

*(): Obj["main"] will not be a call signature of the same type as Obj["main"] is will be a function that returns whatever the property of main is.

*The type of the main function is too generic, and it will not preserve any argument types.

A solution that does what you expect might be:
namespace ScopeFunction {

    export type Function<Obj extends MakerObject<(...args: any[]) => any>> = Obj['main'] & {
        [P in keyof Obj]: Obj[P];
    }
    export interface MakerObject<TMain extends (...args: any[]) => any> {
        main?: TMain;
    }

    export type Maker = <TObj extends MakerObject<(...args: any[]) => any>>(object: TObj) => ScopeFunction.Function<TObj>;

}

// FUNC
var scopeFunction: ScopeFunction.Maker = (object) => {

    // create main function if it doesn't exist
    if (!object.main) object.main = function () {
        alert("No main function for this scopeFunction");
    };

    // return main function
    return Object.assign(object.main, object);
};

// TEST
var test = scopeFunction({
    a: 1,
    b: "3",
    main: (param: number) => { console.log("testLog"); return param; }
})

var test1 = test(10);
var test2 = test.main(10);
var test3 = test.a;


text:
Q: creating a entity relationship with user (jhiUser) in Jhipster I have two entities "user" which is already created by jhipster and "car" the car have Many-to-one(bidirectional) relation with user
my queries are :
1> when I type yo jhipster:entity user it is creating new user entity rather then updating existing one I have also tried  yo jhipster:entity jhiUser
2> Where to use what ? either to use "user" or "jhiUser" and where?

A: This is normal you cannot create an entity which already exists especially User which is used for access control and basically this is what you tried by running yo jhipster:entity user.
You can't do bi-directional relations with user using entity sub generator, you could create many-to-one relation from car to user and then modify User manually.
Alternatively you could create a one-to-one relation between User and another entity CarOwner which would have a bi-directional one-to-many relationship with Car.
There are many questions about relations with User that you could search in stackoverflow.


text:
Q: CSS - Share a gradient with multiple Divs Hi I'm trying to create a gradient that starts at a first div and ends at the last div.
Much like the Instagram Messaging App:

I tried using Multiple.js but I was unable to get it to work:
Here's my HTML Code:

Hello!

8:54 PM

I tried running this javascript code with Multiple.js but nothing happen.:
var multiple = new Multiple({
  selector: '.messageFromRecipient',
  background: 'linear-gradient(#273463, #8B4256)'
});
multiple.update();

So now I'm wondering, is there a pure javascript/css method to achieve this? Could anyone advice please. Thanks!

A: You must not have included the links to the multiple CSS and Javascript properly. In the below snippet you can see your code working as expected...

var multiple = new Multiple({
  selector: '.messageFromRecipient',
  background: 'linear-gradient(#273463, #8B4256)'
});
// multiple.update(); /* not required */

<link href="https://cdnjs.cloudflare.com/ajax/libs/multiple.js/0.0.1/multiple.css" rel="stylesheet"/>

Hello!

8:54 PM

Hello!

8:54 PM

Hello!

8:54 PM

Hello!

8:54 PM

Hello!

8:54 PM


text:
Q: Check box read only in a gridview asp.net I have a gridview with a checkbox field . I need to make the checkbox read only
<asp:GridView ID="grdExam"
              CssClass="grid"
              runat="server"
              AutoGenerateColumns="false"
              DataKeyNames="Id">
    <Columns>
        <asp:BoundField DataField="ID"
                        HeaderText="ID"
                        SortExpression="ID" />
        <asp:BoundField DataField="Name"
                        HeaderText="Name"
                        SortExpression="Name" />
        <asp:BoundField DataField="Type_Id"
                        HeaderText="Type"
                        SortExpression="Type" />
        <asp:TemplateField>
            <ItemTemplate>
                <asp:CheckBox ID="chkSelect"
                              runat="server"
                              Checked='<%# Eval("Enabled")%>' />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

There  is no server side property to make the Checkbox readonly. IS there any server side code that i can use to make the checkbox read only.

A: You can't set it to readonly for checkbox but you can use alternate way...
<asp:CheckBox ID="xxx" runat="server" onclick="return false" />

Anyway why you didn't use Enabled="false" ?
If you don't let the user to check.... just use Enabled="false"

A: <asp:CheckBox runat="server" ID="chkReadOnly" Checked="true" OnClick="return false;" />


text:
Q: implicit declaration of function 'runProcessForOneTimeStep' - Multi Level Queue Schedular I have been stuck with this code for some time and wanted some expert help. Below is part of my code and where the error is coming from:
char* simulateNextTimeStep( schedule *ps ) {
    queueType temp, queueFront;
    char *newProcessName = NULL;

    if( !( isEmpty(ps->foreQueue) ) )
    {
        queueFront = ps->foreQueue->qFront->qt;
        newProcessName = runProcessForOneTimeStep(queueFront->processName, queueFront->pData);
        ps->timesteps++;
        queueFront->timeStepsTaken++;
        queueFront->timeStepsTakenInReturn++;
        if( queueFront->timeStepsTaken == queueFront->runtime )
        {
             temp = dequeue(ps->foreQueue);
             freeProcessData(temp->pData);
              free(temp->processName);
               free(temp);
        }
         else if( queueFront->timeStepsTakenInReturn % 5 == 0 && queueFront->timeStepsTaken != 0 && queueFront->timeStepsTakenInReturn != 0 && queueFront->timeStepsTakenInReturn != queueFront->returnStep)
        {
             queueFront->returnStep = queueFront->timeStepsTakenInReturn;
             temp = dequeue(ps->foreQueue);
             enqueue(ps->foreQueue, temp);
         }
     }
     else if( !( isEmpty(ps->backQueue) ) )
     {
          queueFront = ps->backQueue->qFront->qt;
          newProcessName = runProcessForOneTimeStep(queueFront->processName, queueFront->pData);
          ps->timesteps++;
          queueFront->timeStepsTaken++;
          if( queueFront->timeStepsTaken == queueFront->runtime )
          {
               temp = dequeue(ps->backQueue);
               freeProcessData(temp->pData);
               free(temp->processName);
               free(temp);
          }
    }
    if( !( isEmpty(ps->backQueue) ) )
   {
       queueFront = ps->backQueue->qFront->qt;
       if( (ps->timesteps - queueFront->startingTimeStep) >= 50 )
       {
              temp = dequeue(ps->backQueue);
              promoteProcess(temp->processName, temp->pData);
              enqueue(ps->foreQueue, temp);
       }
   }
   return newProcessName;
}

This is a Multi Level Queue Schedular that I have been trying to resolve but not able to understand where I can make adjustments and resolve the issue. Although I like to work on just problems on my own, I feel expert help and explanation would be very handy.
Below is the image of the error output:


text:
Q: Amount using input I just started my journey in vue, how to make the input data take a number into itself, and then display it in a variable, and if you enter 2 times, then add them up.
<template>

                    <input id="txtName" @keyup.enter="addMessage" v-model="myMoney" type="text">
                    <button @click="addMoney">Sum</button>

$: {{myMoney}}

</template>

<template>
  <input v-model.number="myMoney" />
  <button @click="addMoney">Add
  </button>

    dollar: {{this.dollar}}

</template>

If you want to use enter, wrap it in a form and listen for @submit.prevent, like this:
<form @submit.prevent="addMoney">
  <input v-model.number="myMoney" />
  <button type="submit">Add</button>
</form>


text:
Q: Python: Find constants from mathematical model to reconstruct measured data I try to calculate the constants of a known mathematical model for my measured (and already filtered) data.
A little bit of pseudo code:
#my data is saved in y_data and x_data
#my model is a function of constants (a,b,c) and the x_data
model = f(x_data, a, b, c)

#set model equal to data
y_data != model
calculate(a, b, c)

Is there any way to find the constants? I know there will be no exact result...but is it possible for a deviation (e.g. 5%) of y_data?
An alternative would be to calculate the constants for each index. Then have len(x_data) equations and somehow find the best fitting model and its constants.
I tried to simplify my issue, furthermore this is my first question, so let me know when I could to something better.
Thanks in advance!

A: If your model is linear, the simplest methods would be least squares (linear regression).  There is a nice tutorial with examples here.
Since it appears your model is non-linear (and assuming you can't or don't want to find an analytical solution), you might want to try numerical optimization.
Scipy has a function called minimize which you could use to try to find the best solution.  But it is not guaranteed to find the global minimum.  So you may have to try different initial conditions.
Your code might look something like this:
from scipy.optimize import minimize

# Initial guess
x0 = [1.3, 0.7, 0.8]
res = minimize(cost_function, x0, tol=1e-5)
print(res.x)

The trick is, you need to define the function cost_function that you give to the solver, first.
It's common to use quadratic errors (sum of squared-errors or mean-squared error).  Something like this:
def cost_function(x):
    a, b, c = x
    model_predictions = f(x_data, a, b, c)
    return sum((model_predictions - y_data)**2)

You might also have to try different solvers which are built into scipy.optimize.minimize.  Refer to the documentation on the pros and cons of each method.
Maybe get familiar with the examples in the Scipy documentation first, then try to set it up on your actual problem.


text:
Q: Chainlink external adapter fetch data from my own api server I have some problems with using an external adapter to fetch my data on my own API server.
I'm using a template from https://github.com/PatrickAlphaC/CL-EA-NodeJS-Template
Then I modify some of the code, these are where I modify:
//parameter
const customParams = {
  action: ['action'],
  value: ['value'],
  endpoint: false
}

//end point
  if (action=='user') {
    endpoint = `user`
  }

//url
  const url = `http://localhost:9000/${endpoint}`
  console.log(url)

//respond
response.data.result = Requester.validateResultNumber(response.data, url)

request I send
curl -X POST -H "content-type:application/json" "http://localhost:8080/" --data '{ "id": 0, "data": {"action": "user","value": "5fc95ebeb0d8daafdabd105a" } }'

This is the error message I got in the external adapter:
SyntaxError: Unexpected token " in JSON at position 2
    at JSON.parse (<anonymous>)
    at parse (/Users/apple/code/back/CL-EA-NodeJS-Template/node_modules/body-parser/lib/types/json.js:89:19)
    at /Users/apple/code/back/CL-EA-NodeJS-Template/node_modules/body-parser/lib/read.js:121:18
    at invokeCallback (/Users/apple/code/back/CL-EA-NodeJS-Template/node_modules/raw-body/index.js:224:16)
    at done (/Users/apple/code/back/CL-EA-NodeJS-Template/node_modules/raw-body/index.js:213:7)
    at IncomingMessage.onEnd (/Users/apple/code/back/CL-EA-NodeJS-Template/node_modules/raw-body/index.js:273:7)
    at IncomingMessage.emit (events.js:326:22)
    at endReadableNT (_stream_readable.js:1252:12)
    at processTicksAndRejections (internal/process/task_queues.js:80:21)

I'm quite confused about this problem, where should I find this JSON file?
It looks like I got a " syntax error in my JSON file.
But I can send this request directly to my API server
http://localhost:9000/user/5fc95ebeb0d8daafdabd105a

this is the respond
  "global_stats": {
    "duo": {
      "kd": 1.1,
      "kills": 20,
      "score": 100
    },
    "solo": {
      "kd": 1.2,
      "kills": 21,
      "score": 101
    }
  },
  "_id": "5fc95ebeb0d8daafdabd105a",
  "name": "mark1",
  "age": 211,
  "__v": 0
}

Here is the update for comments
In CL-EA-NodeJS-Template/node_modules/raw-body/index.js:213:7
    // mark complete
    complete = true

    if (sync) {
      process.nextTick(invokeCallback)
    } else {
      invokeCallback() // this function is the line 213
    }

In CL-EA-NodeJS-Template/node_modules/raw-body/index.js:273:7
  function onEnd (err) {
    if (complete) return
    if (err) return done(err)

    if (length !== null && received !== length) {
      done(createError(400, 'request size did not match content length', {
        expected: length,
        length: length,
        received: received,
        type: 'request.size.invalid'
      }))
    } else {
      var string = decoder
        ? buffer + (decoder.end() || '')
        : Buffer.concat(buffer)
      done(null, string). // this is the line 273
    }
  }

I'm not sure what is the means of log the URL, But now I'm trying to figure out once the external adapter request the API server, whether the API server fetch the data, and what it is responding to the adapter. And now I'm using Wireshark trying to do it. I already find that the external did request the API server.
Here is the update2 for answer
Hi Patrick, Thank you for your response. I think  I want to use the GET  request because I want to get the value from my API server just like what you present in the youtube video to get the weather of Boston.
When I directly access this URL http://localhost:9000/user/5fc95ebeb0d8daafdabd105a
And I got
{"global_stats":{"duo":{"kd":1.1,"kills":20,"score":100},"solo":{"kd":1.2,"kills":21,"score":101}},"_id":"5fc95ebeb0d8daafdabd105a","name":"mark1","age":211,"__v":0}
My aim is to let my external adapter to fetch all the data, and respond to me when I use this
curl -X GET -H "content-type:application/json" "localhost:8080" --data '{ "user": 0, "data": {"action": "user","value": "5fc95ebeb0d8daafdabd105a" } }'
And I just follow your advice but I still got the error
SyntaxError: Unexpected token " in JSON at position 2
    at JSON.parse (<anonymous>)
    at parse (/Users/apple/code/back/CL-EA-NodeJS-Template/node_modules/body-parser/lib/types/json.js:89:19)
    at /Users/apple/code/back/CL-EA-NodeJS-Template/node_modules/body-parser/lib/read.js:121:18
    at invokeCallback (/Users/apple/code/back/CL-EA-NodeJS-Template/node_modules/raw-body/index.js:224:16)
    at done (/Users/apple/code/back/CL-EA-NodeJS-Template/node_modules/raw-body/index.js:213:7)
    at IncomingMessage.onEnd (/Users/apple/code/back/CL-EA-NodeJS-Template/node_modules/raw-body/index.js:273:7)
    at IncomingMessage.emit (events.js:326:22)
    at endReadableNT (_stream_readable.js:1252:12)
    at processTicksAndRejections (internal/process/task_queues.js:80:21)

Do you think this error is on my API server? Or it is on the other place. Thank you so much!!!

A: Ah, so you're looking to make a POST request and not a get.

*

*Add this to your config object:

method = 'post'

*Fix how you add the parameters

const fsym = validator.validated.data.base.toUpperCase()
  const action = validator.validated.data.action
  const value = validator.validated.data.value
  const url = `http://localhost:8080/${action}/${value}`

  const params = {
  }

*Remove this part entirely

  if (action=='user') {
    endpoint = `user`
  }

A: It seems like you used wrong unicode characters. Instead of " (U+0022) you used " (U+201C) and " (U+201D) characters in id, user, value and 5fc95ebeb0d8daafdabd105a.  It often happens when you copy/paste code from websites.
Even though they look the same/similar they are completely different and are not interpreted as you expected.
In order to fix the error you should replace them with " (U+0022).


text:
Q: How do I change an attribute or class using only Javascript? I would like to change the styling attribute values of all elements that have the class "post-feature" and contain an attribute value of "http"
So the div element will look like the following:

So far the http check works. But I am not able to set the attribute value.
I have the following code
var features = document.getElementsByClassName(".post-feature")
[0].getAttribute("style");

if (features.includes("http")) {
features.setAttribute("background-color", "orange");

} else {

  alert('no change');

}

A: You can use querySelectorAll('.post-feature[style*="http"]') to find those elements.
Then simply iterate through them and i.e. set their background color with
element.style.backgroundColor = 'orange';
Now, if you want to make sure you only target elements having a background-image and http, you can use this selector:
querySelectorAll('.post-feature[style*="http"][style*="background-image"]')
Also, by adding an i (or I) just before the end bracket [style*="http"i], the value will be compared case-insensitively.

window.addEventListener('load', function() {
  var elements = document.querySelectorAll('.post-feature[style*="http"]');
  for (var i = 0; i < elements.length; i++) {

      elements[i].style.backgroundColor = 'orange';   /* add propert value */

      /*  replace class
      elements[i].className = 'myClass';
      */

      /*  add a class
      elements[i].classList.add('myClass');
      */
  }
  /* temp log */
  console.log('Found ', elements.length,' element(s)');
})
div {
  height: 40px;
  background-color: gray;
}
div + div {
  margin-top: 10px;
}

Updated
To only change styling, like colors etc., you don't even need a script, you can use CSS alone

div {
  height: 40px;
  background-color: gray;
}
div + div {
  margin-top: 10px;
}
/*  for elements that contain "http" and "background-image"  */
.post-feature[style*="http"i][style*="background-image"i] {
  background-color: orange;
}

As a note, and as discussed in a few comments, if to make sure it is the background-image property that also contain the http in its url(), you can adjust the selector to this, which as well can be used without any script, as a CSS rule
.post-feature[style*="background-image:url(http"i] {
  background-color: orange;
}

The above selector can of course also be used in the first sample, like this
querySelectorAll('.post-feature[style*="background-image:url(http"i]')

A: First, you can use querySelctorAll() with a CSS query that selects the elements with the class you desire and, in most cases, you should use this instead of getElementsByClassName() as that returns a "live node list" that causes the DOM to be re-scanned every time you access it.
Next, setAttribute() is for setting HTML element attributes. You are asking to change the value of a CSS property. While that could be accomplished with setAttribute('style', value), it is very "old-school" and not the best approach, nor is getAttribute('style') the best way to read a CSS property value (it won't work if the CSS was set from a style sheet).
Also, your code is trying to access: backgroundimage, but the property is accessed as background-image when working in CSS and backgroundImage when accessing it via JavaScript.
To access the inline styles applied to an HTML element, just access the style property of that element, followed by the name of the CSS property you are interested in. For example:
var bColor = element.style.backgroundColor;

If the style has been applied to the element from an internal style sheet or an external style sheet, the above approach won't work for you and you'll need to get it another way, via window.getComputedStyle():
var bColor = window.getComputedStyle(element, null).backgroundColor;

But, note that getComputedStyle() doesn't always return the same value that you set - - it's the value after the browser has computed all factors. In this case, even paths that you wrote as relative references (without the "http") will be returned as absolute paths (with the http).
So, here is a modern approach that correctly checks only the background-image CSS property for the presence of http.
NOTE: This solution tests for http specifically in the background-image property. Unlike most of the other answers given, this code will correctly ignore http in other CSS properties besides background-image. Examine the CSS of the last div to see this in action.

// querySelectorAll() is more efficient than getElementsByClassName()
var features = document.querySelectorAll(".post-feature");

// Loop over the list
for(var i = 0; i < features.length; i++){

  // Get access to the background-image property (called backgroundImage from JavaScript) value,
  // convert that value to lower case and check to see if "http" is in that value
  if(features[i].style.backgroundImage.toLowerCase().indexOf("http") > -1){

    // Set the CSS background-color property (called "backgroundColor" in JavaScript) to orange:
    features[i].style.backgroundColor = "orange";

    // Just for testing:
    features[i].textContent = features[i].style.backgroundImage;

  } else {

    alert("No change");

  }
}
.post-feature { width:100%; height:50px; border:1px solid black; background-color:gray; color:yellow; }

I have "http" in one of my CSS properties, but not "background-image", so I shouldn't be orange.

A: Use element.style.backgroundColor and indexOf
var features = document.getElementsByClassName(".post-feature")[0].getAttribute("style");

if (features.indexOf("http") > -1) {

  features.style.backgroundColor = "orange";

} else {

  alert('no change');

}

A: i think some wrong in your code, try this code
element.setAttribute("style", "background-color: orange;"); // bad

or
element.style.backgroundColor = "orange"; // good

A: check this fiddle
https://jsfiddle.net/vywk72j8/2/

tt

var feature = document.getElementsByClassName("post-feature")[0];
if (feature.style.backgroundImage.indexOf("http") !== -1) {
    feature.style.backgroundColor = "orange";
} else {
    alert('no change');
}

In your code, you are fetching the attribute value in features
var features = document.getElementsByClassName(".post-feature")
[0].getAttribute("style");

Here features is a string containing attribute value, not an element so you cannot use it to set value.


text:
Q: Spring Data Rest 2.4 Intermittent Error (ClassCastException) Working with Spring Data Rest continues. Moving to 2.4.0 gave me more of the behavior I want, however now I am getting a strange intermittent exception.
About. . . 2/3 of the time when I reload or deploy my application, every SDR endpoint with data throws a 500, and gives the following:
GET /api/departments
--------------------

HTTP Status 500 - Could not write content: org.springframework.data.rest.webmvc.json.PersistentEntityJackson2Module$ProjectionResourceContentSerializer
cannot be cast to com.fasterxml.jackson.databind.ser.impl.UnwrappingBeanSerializer
(through reference chain:
org.springframework.hateoas.PagedResources["_embedded"]
->java.util.UnmodifiableMap["departments"]
->java.util.ArrayList[0]
->org.springframework.data.rest.webmvc.json.ProjectionResource["content"]);

nested exception is com.fasterxml.jackson.databind.JsonMappingException:
org.springframework.data.rest.webmvc.json.PersistentEntityJackson2Module$ProjectionResourceContentSerializer
cannot be cast to com.fasterxml.jackson.databind.ser.impl.UnwrappingBeanSerializer

(through reference chain:
org.springframework.hateoas.PagedResources["_embedded"]
->java.util.UnmodifiableMap["departments"]
->java.util.ArrayList[0]
->org.springframework.data.rest.webmvc.json.ProjectionResource["content"])

(Full error report available: http://pastebin.com/xzzXkFiR )
Like I said, this does not occur every time I reload/deploy the app, but if it is occuring it's completely stuck, and a reload is the only way to fix it. Very odd behavior, wondering if anyone has any insight.
Issue does not occur if I roll back to Spring Data Rest 2.3.2
Thanks for the help, and please let me know what other relevant information I can provide.

*

*SDR: 2.4.1

*SFW: 4.2.1

*SDJPA: 1.9.0

Some further testing
Issue also occurs with latest (2.5.0 SNAPSHOT).

A: I can observe the same issue after updating to Spring Data Rest 2.4.0. The issue is not deterministically reproducible. I do not have any statistics so far, but it occurs less frequently after updating Jackson dependencies from 2.4.0 to 2.6.0. Sometimes it still pops up, but then a reload is sufficient in my case. A minimal example would help to dive deeper into it.

A: Bugs in jackson-databind library. Upgrade to release train Gosling-SR3 once released.
See https://jira.spring.io/browse/DATAREST-716 and https://jira.spring.io/browse/DATAREST-743


text:
Q: how to retrive max product_id count from order_detail table? select max(count(od_product_id)) as no from order_detail group by od_product_id

above the query doen't work.

A: You are trying to group by the column you are aggregating
Try this:
select max(counted)
from
(
select od_product_id, count(*) as counted
from order_detail
group by od_product_id
) x1

A: You can use HAVING for this
SELECT od_product_id, COUNT(od_product_id) AS c
FROM order_detail
GROUP by od_product_id
HAVING count(od_product_id) >= ALL
(
    SELECT count(od_product_id)
    FROM order_detail
    GROUP by od_product_id
)


text:
Q: Could not get mongodb connectivity with nodejs I have tried this in nodejs but  i am getting undefined as output in my console
// Connect using a MongoClient instance
const MongoClient = require("mongodb").MongoClient;
const test = require("assert");
// Connection url
const url = "mongodb://localhost:27017";
// Database Name
const dbName = "test";
// Connect using MongoClient
const mongoClient = new MongoClient(url);
mongoClient.connect(function (err, client) {
  const db = client.db(dbName);
  try {
    db.collection("employeeDetails")
      .find({})
      .toArray(function (err, res) {
        console.log(res);
      });
  } catch (e) {
    console.log(e);
  } finally {
    client.close();
  }
});

I have data in mongodb :

How do i get my employee details in my console Any help would be appreciated

A: You're closing the connection before getting the results. If you print err inside toArray() along with result, you will see below error -
MongoExpiredSessionError: Cannot use a session that has ended

This is happening because the db.collection("employeeDetails")... is getting called but waits for results in callback, till then it moves ahead and since after that statement you are exiting try-catch, you enter into finally which closes the session. When the db.collection... call is processed, this session is already ended and you see this error.
You can use async await. Modify your code as below -
// Connect using a MongoClient instance
const MongoClient = require("mongodb").MongoClient;
const test = require("assert");
// Connection url
const url = "mongodb://localhost:27017";
// Database Name
const dbName = "test";
// Connect using MongoClient
const mongoClient = new MongoClient(url);
mongoClient.connect(async function (err, client) {
  const db = client.db(dbName);
  try {
    const result = await db.collection('employeeDetails').find({}).toArray();
    console.log(result);
  } catch (e) {
    console.log(e);
  } finally {
    client.close();
  }
});

In the line mongoClient.connect(async function (err, client).. we're using async before the callback function and later inside, we can just get the result using -
const result = await db.collection('employeeDetails').find({}).toArray();

After this console.log will print your results correctly.

A: This works for me
let result = await collection(collection).find(query).toArray()


text:
Q: Inserting number into random array I need some help inserting the number 8 into an array that gives me random values. The array must be in order. For example if I had an array of (1,5,10,15), I have to insert the number 8 between 5 and 10. I am having a problem on how I can figure our a way to find the index where 8 will be placed because the array is random, it can be anything. Here is my code so far :
public class TrickyInsert {

public static void main(String[] args) {

    int[] mysteryArr = generateRandArr();

    //print out starting state of mysteryArr:
    System.out.print("start:\t");
    for ( int a : mysteryArr ) {
        System.out.print( a + ", ");
    }
    System.out.println();

    //code starts below

    // insert value '8' in the appropriate place in mysteryArr[]
    int[] tmp = new int[mysteryArr.length + 1];
    int b = mysteryArr.length;
    for(int i = 0; i < mysteryArr.length; i++) {
        tmp[i] = mysteryArr[i];

    }
    tmp[b] = 8;
    for(int i =b ; i<mysteryArr.length; i++) {
        tmp[i+1] = mysteryArr[i];
    }
    mysteryArr = tmp;

any tips? thanks!

A: Simply add the number then use Arrays.sort method,
int b = mysteryArr.length;
int[] tmp = new int[b + 1];
for(int i = 0; i < b; i++) {
    tmp[i] = mysteryArr[i];
}
tmp[b] = 8;
mysteryArr = Arrays.sort(tmp);

A: In your example the random array is sorted. If this is the case, just insert 8 and sort again.

A: Simply copy the array over, add 8, and sort again.
        int[] a = generateRandArr();

        int[] b = Arrays.copyOf(a, a.length + 1);

        b[a.length] = 8;

        Arrays.sort(b);

A: I will suggest using binary search to find the appropriate index. Once you locate the index, you can use
System.arraycopy(Object src, int srcIndex, Obj dest, int destIndex, int length)

to copy the left half to your new array (with length one more than the existing one) and then the new element and finally the right half. This will stop the need to sort the whole array every time you insert an element.
Also, the following portion does not do anything.
for(int i =b ; i<mysteryArr.length; i++) {
    tmp[i+1] = mysteryArr[i];
}

since int b = mysteryArr.length;, after setting int i =b ;, i<mysteryArr.length; will be false and hence the line inside this for loop will never execute.

A: int findPosition(int a, int[] inputArr)
 {
  for(int i = 0; i < inputArr.length; ++i)
   if(inputArr[i] < a)
    return i;
   return -1;
 }

int[] tmpArr = new int[mysteryArr.length + 1];
int a = 8;   // or any other number
int x = findPosition(a, mysteryArr);
if(x == -1)
 int i = 0;
 for(; i < mysteryArr.length; ++i)
   tmpArr[i] = mysteryArr[i];
 tmpArr[i] = a;
else
 for(int i = 0; i < mysteryArr.length + 1; ++i)
  if(i <  x)
   tmpArr[i] = mysteryArr[i];
  else if(i == x)
   tmpArr = a;
  else
   tmpArr[i] = mysteryArr[i - 1];


text:
Q: What should I be aware of when opening a Lenovo X201 to look at the fan? My Lenovo X201's fan has been making a lot of noise on occasion recently (buzzing, sawing even); also, I've been getting shut-downs due to max temperature reached, although not at the same time as the noisy fan.
So, I was thinking of trying to open it up and having a look - at the fan at least - as suggested in answers on noisy fan questions.
Now, I want to be super-careful here, so:

*

*Do I need any special tools/implements other than the appropriate-size screwdriver?

*Is there any glue in there which I will need to undo?

*Anything special to watch out for?

I'm also not sure how to clean the fan or to determine whether the fan noise is related to the power-downs, but I guess that should go on a different question, unless there's some "pick your laptop apart guide" which covers all that.
Notes:

*

*A while ago I upgraded my Laptop memory to 2 x 4GB instead of 1 x 2GB; it used to be much slower before but didn't have power-outs.

A: Based on @Tetsujin's suggestion, this seems to cover the basics:
https://www.youtube.com/watch?v=IJZZSD8x9_8
It's a step-by-step video of disassembling the X201 and examining the fan.


text:
Q: Dropdown menu hidden behind slideshow container? We have a main index page with a dropdown menu and slide show, and the z-index works fine, but in our other pages, we removed the slideshow and left the dropdown menu. But for some reason in the pages without the slideshow, the dropdown menu gets hidden behind the container the slideshow used to be, despite the removal of all slideshow HTML. This leads me to believe it is a CSS issue.
Any suggestions would be well appreciated!
Here's the HTML
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Stigler Public Schools</title>
  <link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css">
  <link rel="stylesheet" type="text/css" href="\\stigler-web\web\New Website\caleab\stiglerstylesheet.css"/>

Stigler Public Schools

      District

High School

Middle School

Grade School

Administration

      Resources

School Calender

Menus

Employment

Counseling

Grade Book

Yearbook

      Organizations

Athletics

Music

Drama

FFA

A-Z

      Board Of Education

Information

Meetings

Policies

And Here's the CSS
* {
  margin: 0px;
  padding: 0px;
  outline: none;
  border: 0px;
}

body {
  background-image: url(background.png);
  background-repeat: no-repeat;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  background-size: cover;
  margin: 0px auto;
  padding: 0px;
  width: 100%;
  overflow: hidden;
}

h1 {
  border-top: none;
  border-left: none;
  border-bottom: 5px groove red;
  border-right: none;
  color: #e60000;
  font-family: century gothic;
  text-align: center;
  color: #FF000;
}

h2 {
  font-family: century gothic;
}

h3 {
  font-family: century gothic;
}

h5 {
  font-family: californian fb;
  font-szie: 1.15em;
}

p {
  border-top: none;
  border-left: none;
  border-bottom: none;
  border-right: none;
  font-family: californian fb;
  font-size: 1.15em;
}

table#sitelinks td {
  font-size: 1.15em;
}

table#sitelinks tr:nth-child(odd) {
  background-color: #fff
}

table tr:nth-child(even) {
  background-color: #fff
}

table tr:nth-child(odd) {
  background-color: #eee
}

hr {
  border-top: none;
  border-left: none;
  border-bottom: 5px groove red;
  border-right: none;
  font-family: californian fb;
  font-size: 1.15em;
}

th {
  text-align: left;
  font-family: century gothic;
  padding: 10px 0px 0px 0px;
  font-size: 1.15em;
}

td {
  font-family: century gothic;
  border: 1px solid black;
  padding: 5px 5px 5px 5px;
  text-align: center;
  font-size: 1em;
}

.center {
  text-align: center;
}

.blue {
  color: blue;
}

.bottomborder {
  text-align: center;
  border-bottom: 5px groove red;
}

a:link {
  color: #e60000;
  text-decoration: none
}

a:visited {
  color: #e60000;
  text-decoration: none
}

a:hover {
  color: #e60000;
  text-decoration: none
}

a:active {
  color: #e60000;
  text-decoration: none
}

.logo {
  display: block;
  margin: 0 auto;
  height: 160px;
  width: 160px;
}

.header {
  padding-left: 140px
}

a {
  display: block;
  text-decoration: none;
  width: 100%;
  height: 100%;
  color: #999;
}

.navwrapper {}

.nav {
  width: 79.31%;
  text-align: center;
  margin: 0px auto;
  z-index: 2;
  position: relative;
}

a:hover {
  color: #FF0000;
}

/* NAVIGATION */

.navigation {
  list-style: none;
  margin: 0;
  padding: 0;
  height: 40px;
  margin: 10px auto;
  background: #FF0000;
  float: left;
  position: relative;
  z-index: 10
}

.navigation,
.navigation a.main {
  border-radius: 0px;
  -webkit-border-radius: 0px;
  -moz-border-radius: 0px;
}

.navigation:hover,
.navigation:hover a.main {
  border-radius: 0px 0px 0 0;
  -webkit-border-radius: 0px 0px 0 0;
  -moz-border-radius: 0px 0px 0 0;
}

.navigation a.main {
  display: inline-block;
  height: 40px;
  font: bold 15px/40px arial, sans-serif;
  text-align: center;
  text-decoration: none;
  color: #FFF;
  -webkit-transition: 0.2s ease-in-out;
  -o-transition: 0.2s ease-in-out;
  transition: 0.2s ease-in-out;
}

.navigation:hover a.main {
  color: rgba(0, 0, 0, 0.6);
  background: rgba(0, 0, 0, 0.04);
}

.navigation li {
  width: 250px;
  height: 40px;
  background: #F7F7F7;
  font: normal 12px/40px arial, sans-serif !important;
  color: #999;
  text-align: center;
  margin: 0;
  -webkit-transform-origin: 50% 0%;
  -o-transform-origin: 50% 0%;
  transform-origin: 50% 0%;
  -webkit-transform: perspective(350px) rotateX(-90deg);
  -o-transform: perspective(350px) rotateX(-90deg);
  transform: perspective(350px) rotateX(-90deg);
  box-shadow: 0px 2px 10px rgba(0, 0, 0, 0.05);
  -webkit-box-shadow: 0px 2px 10px rgba(0, 0, 0, 0.05);
  -moz-box-shadow: 0px 2px 10px rgba(0, 0, 0, 0.05);
  position: relative;
  z-index: 30;
  overflow: visible;
}

.navigation li:nth-child(even) {
  background: #F5F5F5;
}

.navigation li:nth-child(odd) {
  background: #EFEFEF;
}

.navigation li.n1 {
  -webkit-transition: 0.2s linear 0.4s;
  -o-transition: 0.2s linear 0.4s;
  transition: 0.2s linear 0.4s;
}

.navigation li.n2 {
  -webkit-transition: 0.2s linear 0.3s;
  -o-transition: 0.2s linear 0.3s;
  transition: 0.2s linear 0.3s;
}

.navigation li.n3 {
  -webkit-transition: 0.2s linear 0.2s;
  -o-transition: 0.2s linear 0.2s;
  transition: 0.2s linear 0.2s;
}

.navigation li.n4 {
  -webkit-transition: 0.2s linear 0.1s;
  -o-transition: 0.2s linear 0.1s;
  transition: 0.2s linear 0.1s;
}

.navigation li.n5 {
  border-radius: 0px 0px 4px 4px;
  -webkit-transition: 0.2s linear 0s;
  -o-transition: 0.2s linear 0s;
  transition: 0.2s linear 0s;
}

.navigation:hover li {
  -webkit-transform: perspective(350px) rotateX(0deg);
  -o-transform: perspective(350px) rotateX(0deg);
  transform: perspective(350px) rotateX(0deg);
  -webkit-transition: 0.2s linear 0s;
  -o-transition: 0.2s linear 0s;
  transition: 0.2s linear 0s;
}

.navigation:hover .n2 {
  -webkit-transition-delay: 0.1s;
  -o-transition-delay: 0.1s;
  transition-delay: 0.1s;
}

.navigation:hover .n3 {
  -webkit-transition-delay: 0.2s;
  -o-transition-delay: 0.2s;
  transition-delay: 0.2s;
}

.navigation:hover .n4 {
  transition-delay: 0.3s;
  -o-transition-delay: 0.3s;
  transition-delay: 0.3s;
}

.navigation:hover .n5 {
  -webkit-transition-delay: 0.4s;
  -o-transition-delay: 0.4s;
  transition-delay: 0.4s;
}

.navigation:hover .n6 {
  -webkit-transition-delay: 0.5s;
  -o-transition-delay: 0.5s;
  transition-delay: 0.5s
}

/* End Navigation */

/*Slideshow */

* {
  box-sizing: border-box
}

body {
  font-family: Verdana, sans-serif;
}

.mySlides {
  display: none;
  overflow: hidden;
}

.slideshowimg {
  min-width: 100%;
  max-width: 100%;
  max-height: none;
  border: 2px solid #ffffff
}

/* Slideshow container */

.slideshow-container {
  max-width: 1000px;
  min-width: 1000px;
  min-height: 500px;
  max-height: 500px;
  position: fixed;
  margin: 0px auto;
  clear: both;
  z-index: 1;
  position: relative;
  overflow: hidden;
}

/* Caption text */

.text {
  color: #f2f2f2;
  font-size: 30px;
  padding: 8px 12px;
  position: absolute;
  bottom: 8px;
  width: 100%;
  text-align: center;
}

/* Number text (1/3 etc) */

.numbertext {
  color: #f2f2f2;
  font-size: 12px;
  padding: 8px 12px;
  position: absolute;
  top: 0;
}

/* The dots/bullets/indicators */

.dot {
  height: 15px;
  width: 15px;
  margin: 0 2px;
  background-color: #bbb;
  border-radius: 50%;
  display: inline-block;
  transition: background-color 0.6s ease;
}

.active {
  background-color: #717171;
}

/* Fading animation */

.fade {
  -webkit-animation-name: fade;
  -webkit-animation-duration: 1.5s;
  animation-name: fade;
  animation-duration: 1.5s;
}

@-webkit-keyframes fade {
  from {
    opacity: .4
  }
  to {
    opacity: 1
  }
}

@keyframes fade {
  from {
    opacity: .4
  }
  to {
    opacity: 1
  }
}

/* On smaller screens, decrease text size */

@media only screen and (max-width: 300px) {
  .text {
    font-size: 11px
  }
}

/* End Slideshow */

A: I fixed this on my own. I realized that since there was no more content under the drop-down menu, the page technically ended, hence the disappearing menu. At least that's my conclusion. After adding the intended content to the page, they worked just fine.


text:
Q: How To Set "Account Operators" to AD User? For now I've got a script where I can see every user from my Active Directory who has the SID from AccountOperators (5-1-2-32-548) set and the ones who don't.
And now I want to that the user account without this SID, that they can be changed/edited from every other User with the SID set.
Not that they get the SID set.

A: Set-Acl can set AD permissions just fine, but you don't want to set an ACL or SID. You want to add a user to the (builtin) domain group "Account Operators":
Import-Module ActiveDirectory
Set-ADGroupMember -Identity 'Account Operators' -Members 'username'


text:
Q: Using a SQLAlchemy session from a separate python file I have created a sqlite DB using SQLAlchemy and am trying to query one of the tables from a class in a different file from the one that I instantiated the db in. However, whenever I make a query it doesn't do anything. So I'm wondering how do I properly make a query using SQLAlchemy in the function of a class in a separate file. A very generalized idea of what I'm doing is below.
main.py:
**imports here**
engine = create_engine('sqlite:///info.db')
Session = sessionmaker(bind=engine)
Base = declarative_base()

class User(Base):
    __tablename__ = 'users'

    user_id = Column(String, primary_key=True)
    hash_of_password = Column(String)
    display_name = Column(String)
    full_name = Column(String)
    confirmed_account = Column(Boolean, default=True)

Base.metadata.create_all(engine)

numRows = CountRows().returnNumRows()

CountRows.py:
from main import Session

class CountRows:
    def returnNumRows(self):
        dbSession = Session()
        numRows = dbSession.query(User).count()
        print(numRows) #This is just for testing purposes to see if I actually got anything
        return numRows

A: In CountRows.py, include:
 from main import Session, User


text:
Q: On GCD and LCM of elements in integral domain with Krull-dimension 1 Let $R$ be an integral domain with Krull dimension $1$. If $0\ne a \in R$ is such that for every $b \in R$ , the ideal $Ra \cap Rb$ is principal , then is it true that for every $b\in R$, the ideal $Ra+Rb$ is also principal ?
It is clear that if $0\ne a,b$ and $Ra+Rb=Rd$ , then $Ra \cap Rb=R(ab/d)$. So if we know $Ra \cap Rb =Rc$ and want to prove $Ra+Rb$ is principal, then the unique (upto aasociates) possible candidate for the generator is $ab/c$. I'm unable to say anything else.

A: This is only a comment about classes of rings in which no counter-examples can be found.
Since a one-dimensional GCD domain is a Bézout domain [1, Corollary 3.9], GCD domains will not provide any counter-example.
We will show that Dedekind domains will not provide any counter-example either. To do so, we will use the following well-known lemma (see e.g., Matsumura's "Commutative Ring Theory") and two subsequent claims.

Lemma. Let $R$ be a commutative ring with identity. Let $\mathfrak{a}, \mathfrak{b}, \mathfrak{c}$ be ideals of $R$. Assume that $\mathfrak{c}$ is co-maximal with both $\mathfrak{a}$ and $\mathfrak{b}$, i.e., $\mathfrak{a} + \mathfrak{c} = \mathfrak{b} + \mathfrak{c} = R$. Then $\mathfrak{c}$ is co-maximal with $\mathfrak{ab}$.
    Proof. $R = (\mathfrak{a} + \mathfrak{c})(\mathfrak{b} + \mathfrak{c}) \subseteq \mathfrak{ab} + \mathfrak{c} \subseteq R$.

The following claim is a general fact about commutative domains.

Claim 1. Let $R$ be a commutative domain with identity. Let $M(R)$ be the submonoid of $R \setminus \{0\}$ generated by the units of $R$ together with the prime elements $p$ such that $Rp$ is a maximal ideal of $R$. Let $S(R)$ be the subset of $R \setminus \{0\}$ consisting of the non-zero elements $a$ such that $Ra + Rb$ is principal for every $b \in R$. Then $M(R) \subseteq S(R)$.
Proof. Let $a = up_1^{\alpha_1} \cdots p_n^{\alpha_n} \in M(R)$ where $u$ is a unit of $R$ and where the elements $p_i$ are distinct prime elements such that $Rp_i$ is a maximal ideal for every $i$. Let us show by induction on $s = \alpha_1 + \cdots + \alpha_n$ that $a$ belongs to $S(R)$. If $s = 0$, it is immediate. Let us suppose that $s > 0$ and let $b \in R$. We can certainly assume that $b \neq 0$. Let $\beta_i$ be the largest integer such that $p_i^{\beta_i}$ divides both $a$ and $b$ and set $d = p_1^{\beta_1} \cdots p_n^{\beta_n}$. If $d$ is not a unit, then the induction hypothesis applies to $a/d$ and yields a Bézout relation with $b/d$ so that $a \in S(R)$. Otherwise, the element $b$ cannot be divided by any of the $p_i$. Thus $Rb$ is co-maximal with $Rp_i$ for every $i$. By the above lemma, we deduce that $Rb$ is co-maximal with $Ra$, and hence $a \in S(R)$.

Our last claim establishes that no counter-example to OP's condition can be found in a Dedekind domain.

Claim 2. Let $R$ be Dedekind domain and let $a \in R$ such that $Ra \cap Rb$ is principal for every $b \in R$. Then $a \in M(R)$.
Proof. Let $a$ be a non-zero element in $R \setminus M(R)$. By hypothesis, there is a maximal ideal $\mathfrak{m}$ appearing  in the decomposition of $Ra$ which is not principal. By the Chinese Remainder Theorem, we can find $b \in R$ such that $b \in \mathfrak{m} \setminus \mathfrak{m}^2$ and $b$ doesn't  belong to any of the other maximal ideals containing $a$. In the group of fractional ideals of $R$, we have $Ra \cap Rb = (Rab)\mathfrak{m}^{-1}$ so that $Ra \cap Rb$ cannot be principal.

[1] P. Sheldon, "Prime ideals in GCD domains".


text:
Q: Font changes when VF page is rendered as pdf I am creating a letter by getting the custom fields of a custom object(plan review__c). I was able to add a save button link to the bottom and save the letter as pdf in Notes and attachement section. below is my VF page for that:
<apex:page standardController="Plan_Reviews__c" showHeader="false" extensions="BuildingProCertObjectionSheet">
<apex:form >
<apex:image url="{!imageURL}" style="width:720px" ></apex:image>

<apex:panelGrid columns="2" width="720px">

 PRO-CERT CHECKLIST

</apex:panelGrid>

 <apex:panelGrid columns="2" width="720px">

   <apex:panelGrid columns="2" width="60%">

Premise: <apex:outputText value="{!Plan_Reviews__c.Establishment_Address__c}" style="font-size:18px;"/>

   </apex:panelGrid>
   <apex:panelGrid columns="2" width="40%">

Date:<apex:outputText value="{!currentdate}" style="font-size:18px;"/>

   </apex:panelGrid>
   <apex:panelGrid columns="2" width="60%">
           DOB Job Number:<apex:outputText value="{!Plan_Reviews__c.DOB_Job_Number__c}" style="font-size:18px;"/>

   </apex:panelGrid>
</apex:panelGrid>

Pro-Cert plans submitted to NYC Business Acceleration have been examined and found to be unacceptable at this time. This plan will be re-examined after the following defects are corrected:

 <apex:repeat value="{!objlist}" var="d">

    <apex:outputText value="{!d}" style="font-size:18px;" />

 </apex:repeat>

Additional Objection(s):<apex:outputText value="{!Plan_Reviews__c.Other_Violations__c}" style="font-size:18px;"/>

<apex:commandButton action="{!Savecopy}" disabled="false" value="Save"/>

</apex:form>

</apex:page>

When I hit save here I get an pdf in notes and attachment section of my page. The problem - the font in the pdf is very different from what I use in above VF force page. How does the font in pdf changes automatically , it differs from the font in VF page(above) from which is converted to that pdf. Any idea?
Here is the apex class which is related to this page:
public class BuildingProCertObjectionSheet {
   private final ApexPages.StandardController controller;
   private final Id                           planreviewID;
   public String imageURL{get;set;}
   public List<String> objlist {get;set;}
   public string currentdate {get; set;}
   public BuildingProCertObjectionSheet(ApexPages.StandardController stdController) {
        controller   = stdController;
        planreviewID = (Id)controller.getRecord().get('Id');
        Date dt = Date.today();
        currentdate = dt.format();
        list<Plan_Reviews__c> prlist = [select Pro_Cert_Objections_for_Letter__c from Plan_Reviews__c where id = :planreviewID limit 1];
        string obj;
        for(Plan_Reviews__c pr: prlist){
           obj = pr.Pro_Cert_Objections_for_Letter__c;
        }
        if(obj!=null){
           list<string> objections = obj.split(';');
           integer i =1;
           objlist = new list<string>();
           for(string o : objections){
              objlist.add(i++ +'. '+o);
           }
        }
        imageURL='/servlet/servlet.FileDownload?file=';
        List< document > documentList=[select name from document where Name='RangehoodObjectionLogo'];
        if(documentList.size()>0)
        {
           imageURL=imageURL+documentList[0].id;
        }
   }

   public PageReference Savecopy(){
      PageReference p = Page.RangehoodObjectionSheet;
      blob b = ApexPages.currentPage().getContentAsPDF ();

      Attachment a = new Attachment();
      a.body = b;
      a.name = 'Building Pro-Cert Objection Sheet '+currentdate+'.pdf';
      a.parentid = planreviewID;

      insert a;

      PageReference pref = new PageReference('/'+planreviewID);
      return pref;
   }
}

A: Here is a Salesforce documentation link for the supported fonts in PDF created by VisualForce. Make sure you are selecting one of them.


text:
Q: How to define a method for reading all InputStreams including ZipInputStream? I asked this once before and my post was deleted for not providing the code that uses the helper class. This time I have created a full test suite which shows the exact problem.
I am of the opinion that Java's ZipInputStream breaks the Liskov Substitution Principle (LSP) with regards to the InputStream abstract class. For ZipInputStream  to be a subtype of InputStream, then objects of type InputStream in a program may be replaced with objects of type ZipInputStream  without altering any of the desirable properties of that program (correctness, task performed, etc.).
The way in which LSP is violated here is for the read methods.
InputStream.read(byte[], int, int) states that it returns:

the total number of bytes read into the buffer, or -1 if there is no more data because the end of the stream has been reached.

The problem with ZipInputStream is that it has modified the meaning of a -1 return value. It states:

the actual number of bytes read, or -1 if the end of the entry is reached

(there is actually a hint to a similar problem with the available method in the Android documentation http://developer.android.com/reference/java/util/zip/ZipInputStream.html)
Now for the code that demonstrates the problem. (This is a cut down version of what I was actually trying to do so please excuse any poor style, multithreading problems, or the fact that the stream is advanced etc.).
Class that accepts any InputStream to generate a SHA1 of the stream:
public class StreamChecker {

    private byte[] lastHash = null;

    public boolean isDifferent(final InputStream inputStream) throws IOException {
        final byte[] hash = generateHash(inputStream);
        final byte[] temp = lastHash;
        lastHash = hash;
        return !Arrays.equals(temp, hash);
    }

    private byte[] generateHash(final InputStream inputStream) throws IOException {
        return DigestUtils.sha1(inputStream);
    }
}

Unit tests:
public class StreamCheckerTest {

    @Test
    public void testByteArrayInputStreamIsSame() throws IOException {
        final StreamChecker checker = new StreamChecker();
        final byte[] bytes = "abcdef".getBytes();
        try (final ByteArrayInputStream stream = new ByteArrayInputStream(bytes)) {
            Assert.assertTrue(checker.isDifferent(stream));
        }
        try (final ByteArrayInputStream stream = new ByteArrayInputStream(bytes)) {
            Assert.assertFalse(checker.isDifferent(stream));
        }
        // Passes
    }

    @Test
    public void testByteArrayInputStreamWithDifferentDataIsDifferent() throws IOException {
        final StreamChecker checker = new StreamChecker();
        byte[] bytes = "abcdef".getBytes();
        try (final ByteArrayInputStream stream = new ByteArrayInputStream(bytes)) {
            Assert.assertTrue(checker.isDifferent(stream));
        }
        bytes = "123456".getBytes();
        try (final ByteArrayInputStream stream = new ByteArrayInputStream(bytes)) {
            Assert.assertTrue(checker.isDifferent(stream));
        }
        // Passes
    }

    @Test
    public void testZipInputStreamIsSame() throws IOException {
        final StreamChecker checker = new StreamChecker();
        final byte[] bytes = "abcdef".getBytes();
        try (final ZipInputStream stream = createZipStream("test", bytes)) {
            Assert.assertTrue(checker.isDifferent(stream));
        }
        try (final ZipInputStream stream = createZipStream("test", bytes)) {
            Assert.assertFalse(checker.isDifferent(stream));
        }
        // Passes
    }

    @Test
    public void testZipInputStreamWithDifferentEntryDataIsDifferent() throws IOException {
        final StreamChecker checker = new StreamChecker();
        byte[] bytes = "abcdef".getBytes();
        try (final ZipInputStream stream = createZipStream("test", bytes)) {
            Assert.assertTrue(checker.isDifferent(stream));
        }
        bytes = "123456".getBytes();
        try (final ZipInputStream stream = createZipStream("test", bytes)) {
            // Fails here
            Assert.assertTrue(checker.isDifferent(stream));
        }
    }

    private ZipInputStream createZipStream(final String entryName,
            final byte[] bytes) throws IOException {
        try (final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                final ZipOutputStream stream = new ZipOutputStream(outputStream)) {
            stream.putNextEntry(new ZipEntry(entryName));
            stream.write(bytes);
            return new ZipInputStream(new ByteArrayInputStream(
                    outputStream.toByteArray()));
        }
    }
}

So back to the problem... LSP is violated since you can read to the end of the stream for an InputStream but not for a ZipInputStream and of course this will break the correctness property of any method that tries to use it in such a way.
Is there any way that this can be achieved or is ZipInputStream fundamentally flawed?

A: I see no LSP violation. The documentation for ZipInputStream.read(byte[], int, int) says 'Reads from the current ZIP entry into an array of bytes'.
At any one time, the ZipInputStream is really the input stream of the entry, not the whole ZIP file. And it's hard to see what else ZipInputStream.read() could possibly do at end of entry other than return -1.

this will break the correctness property of any method that tries to use it in such a way

Hard to see how the method would ever know.


text:
Q: Add new property to news documents on Firebase I'm creating a voting system. For this the client cannot send votes: 0 because he could modify this to any number.
How can I add votes: 0 for new documents or detect that this property is not 0 and cancel it (prefer the first approach) from Firestore?

A: You would use security rules different document methods such as using a certain rule for create and another for update.
service cloud.firestore {
    match /databases/{database}/documents {
        match /votes/{voteId} {
            allow create: if request.resource.data.votes == 0
            allow update: if request.resource.data.votes == resource.data.votes
        }
    }
}

This would mean a user could create a vote but they have to set votes to 0 and you can update a vote document but votes would need to equal the current value. You would also want to look at other rules such as
request.resource.data.size() == 1 to limit the fields in the document being added
request.resource.data.keys().hasAll(['field_1','field_2']) to ensure it has all the fields necessary to update/create the document.

A: This should be a fairly basic combination of reading data from the collection and then performing transactions of batched updates. If you're having trouble implementing this, show the minimal code that reproduces where you got stuck.
Definitely also implement Jack's security rules, as those will prevent having to do this again in the future.


text:
Q: If $p$, $q$ are two orthogonal projections, then all eigenvalues of $q \circ p$ are in $[0,1]$ Let $E$ be an euclidean vector-space.

Prove that if $p$, $q$ are two orthogonal projections, then all
  complex eigenvalues of $q \circ p$ are in $[0,1]$.

A projector is orthogonal iff it is symmetric.
If $p\circ q$ =  $q\circ p$, then the eigenvalues are in $\{0,1\}$.
Do you have hint for the general case? Thanks

A: Suppose $PQ x= \lambda x$, since $P$ is a projection we have $PQx = \lambda Px= \lambda x$.
Hence either $\lambda = 0$ or $x=Px$, in which case we have $PQPx = \lambda x$.
Since $P,Q$ are orthogonal, we have $P^*=P,Q^*=Q$ and so $(PQP)^* = PQP$ and
hence any eigenvalue is real.
It follows that any eigenvalue of $PQ$ is real.
Since any non zero eigenvalue is also an eigenvalue of $PQP=PQQP \ge 0$, we see that
the eigenvalues are non negative.
Since $\|PQ\| \le \|P\| \|Q\| \le 1$ we see that all the eigenvalues are in $[0,1]$.

A: Let $P$ and $Q$ be two orthogonal projections and let $\langle\cdot,\cdot\rangle$ be the usual inner product of a finite dimensional Euclidean space i.e. if $x,y\in E$ then
$$\langle x,y\rangle:=x_1\overline{y}_1+...+x_n\overline{y}_n$$
where $\overline{y}_k$ denotes the complex conjugate of $y_k$ for each $k$. Let $x\in E$ be a eigenvector of the operator $PQ$ i.e. $PQx=\lambda x$. Then
$$|\lambda|^2||x||^2=|\lambda|^2\langle x,x\rangle=\langle\lambda x,\lambda x\rangle=\langle PQx,PQx\rangle$$
Using the fact that both $P$ and $Q$ are idempotent ($P^2=P, Q^2=Q$) and self-adjoint then we get
$$\langle PQx,PQx\rangle=\langle Qx,P^*PQx\rangle=\langle Qx,P^2Qx\rangle=\langle Qx,PQx\rangle=\langle Qx,\lambda x\rangle=\overline{\lambda}\langle Qx,x\rangle$$
Analogue we obtain
$$\langle PQx,PQx\rangle=\langle P^*PQx,Qx\rangle=\langle P^2Qx,Qx\rangle=\langle PQx,Qx\rangle=\langle \lambda Q^*x,x\rangle=\lambda \langle Qx,x\rangle$$
Therefore we get $$|\lambda|^2||x||^2=\overline{\lambda}\langle Qx,x\rangle=\lambda \langle Qx,x\rangle$$
Therefore it must be the case that $\lambda\in\mathbb{R}$. Next notice that any $x\in E$ can be written as $x=Qx+(I-Q)x$ (the orthogonal decomposition of a vector) hence
$$\langle Qx,x\rangle=\langle Qx,Qx+(I-Q)x\rangle=\langle Qx,Qx\rangle=||Qx||^2$$ this in turn implies $\lambda\geqslant 0$ since $0\leqslant|\lambda|^2||x||^2=\lambda \langle Qx,x\rangle=\lambda||Qx||^2$. From this last equation another thing we obtain is $$\lambda ||x||^2=||Qx||^2$$ whenever $\lambda>0$. Hence
$$\lambda=\frac{||Qx||^2}{||x||^2}\leqslant \sup_{x\neq 0}\frac{||Qx||^2}{||x||^2}=||Q||^2=1^2=1$$
Note any orthogonal projection operator has operator norm equal to unity. Thus if $\lambda$ is an eigenvalue of $PQ$ then $0\leqslant\lambda\leqslant 1$.

A: This actually holds for two orthogonal projections $p,q$ in a $C^*$-algebra.
Namely, we have
$$\sigma(pq) = \sigma(pq^2) = \sigma((pq)q) \subseteq \sigma(q(pq)) \cup \{0\} \subseteq [0,+\infty\rangle$$
since $qpq = qppq = q^*p^*pq = (pq)^*(pq) \ge 0$ and hence has spectrum in $[0,+\infty\rangle$.
On the other hand, we have
$$\|pq\| \le \|p\|\|q\| \le 1$$
so $\sigma(pq)$ is contained in the unit disk around the origin. We conclude that $\sigma(pq) \subseteq [0,1]$.


text:
Q: Creating pandas series from a list eats up ram I am reading a list of numbers as strings from a txt file. It's not a big file, only 1 GB. Then  the numbers are converted to float and put in a list.
with open(...) as f:
    lines = f.read()
mylist = [float(x) for x in lines if x not in ['[',']',',', ' ']]

the end contents of my list are just simple floats in 1.0 format. However this takes up a lot of ram. I noticed if I convert them to int they don't take up as much space, but I need them to be float.
Then when I try to convert this to a pandas series my whole session crashes.
mylist = pd.Series(mylist)

I am using google colab with roughly 25 GB of ram and 15 GB of GPU. I can't believe only 1 GB of data can eat up 25 GB of ram, I must be doing something wrong, but I can't figure out what I should do. Any help is appreciated.

A: Did you try to use the standard method (with custom delimiter) to open this file?
import pandas as pd
df  = pd.read_csv('you_file.txt', delimiter='\t')
df = df[(df['some_column'] != '[') & (df['some_column'] != ']')]
df = df[(df['some_column'] != ',') & (df['some_column'] != ' ')]

UPD:
Maybe you can try to use a python generator, it is a great tool when we care about RAM.
def open_file():
    for row in open(file_name, "r"):
        yield row
lines = open_file()


text:
Q: Is it possible to create a platform independent self-contained single file app by using .NET 5? I have just read an article about Self-Contained Single file apps in .NET 5. It's a kind of deployment option which allows me to create a single file which consists of:

*

*Native executable launcher

*.NET runtime

*.NET libraries

*{your_app} + dependencies

Is this single file app pointed to a specific platform? I guess yes, because it should contain a version of a runtime specific to platform and the application should be compiled by using the architecture of the target machine. Am I right? Does it mean that I should know the target platform (Windows, Linux, MacOs), machine architecture before delivering my self-contained single file apps?

A: The single file self-contained executable is very very specific. It is specific to your Operating System (Linux, macOS or Windows). It is also specific to your architecture (arm64, x64, etc). If you build for win-x64 (Windows + x64) it will not work on linux-x64 (Linux + x64) and it will also not work on linux-arm64 (Linux + Arm 64).
You should know exactly what OS and architecture you are targeting to create a self-contained single file executable that will work there.
You could, of course, compile a single application multiple times, each time creating a single-file application specific to an OS/Architecture combination. Then your users could pick the single file executable that corresponds to their OS/Architecture. To do this, you just need to adjust your dotnet publish command; you don't need to redesign/re-architect your application (assuming it's not somehow tied to an OS/Architecture already).


text:
Q: Mat-button-toggle loses group styling if not a direct child of mat-button-toggle-group I have the Angular template code below, and I'm using some structural directives to display certain buttons on screen according to a value aspectChoice set elsewhere on the page.
What I want to do, is display all of the options of resolutionAssetMappings where the element's other.aspectRatio property matches the aspectChoice value. This is fine, it works properly.
The only issue is that since mat-button-toggle needs to be a direct child of mat-button-toggle-group in order to benefit from the styling applied to each button. Since the div element separates them, they aren't being styled properly.
However, Angular doesn't let you put more than one structural directive onto a single element. So having both the *ngFor and the *ngIf on the mat-button-toggle element is impossible. Meaning I need the div to separate them so I can iterate over the resAssetMappings array and THEN check whether or not the button element in question should be displayed or not.
<mat-button-toggle-group formControlName="resolutionChoice" class="button-group">
                <div *ngFor="let resolution of resolutionAssetMappings">
                  <mat-button-toggle *ngIf="resolution.other.aspectRatio === aspectChoice"
                                     class="option-button" value="{{resolution.name}}">
                    {{resolution.prettyName}}
                  </mat-button-toggle>
                </div>
              </mat-button-toggle-group>

Is there a way I can alter this so that I can have both the behaviour I want and the styling?

A: The answer to this was to replace the div element with the ng-container element. The ng-container isn't rendered to the DOM but also allows you to apply both structural directives.


text:
Q: Update stored procedure not working in SQL Server I have a stored procedure to update the status by changing the bool value from 1 to 0. I am passing the user id to the stored procedure. I just need to update the user status only. But now it's not doing that.
CREATE PROCEDURE [dbo].[UpdateStatus]
    @userID INT
AS
BEGIN
    UPDATE [dbo].[User]
    SET Status = 0
    WHERE Id = @userID
END

I am calling this stored procedure:
public User UpdateStatus(string UserId)
{
        User userDetails = new User();

        try
        {
            using (SqlConnection sqlConnection = new SqlConnection(connection.GetConnectionString()))
            {
                sqlConnection.Open();
                SqlCommand cmd = new SqlCommand("UpdateStatus", sqlConnection);
                cmd.Parameters.Add(new SqlParameter("@userID", UserId));
                cmd.CommandType = CommandType.StoredProcedure;

                using (SqlDataReader reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                           userDetails.DisplayName = reader["DisplayName"].ToString();
                    }
                }

                sqlConnection.Close();
            }
        }
        catch(Exception ex)
        {
            //ex.Message;
        }

        return userDetails;
}

I am calling the UpdateStatus function. But it's not updating the status in the database

A: I am basing this answer purely on guess work from this comment:

its not updating the database.so the return status is 0 and expected is 1

An UPDATE that updates 0 rows without an error is still a successful statement . I suspect you are passing a value for @userID where there is no row that has that value for an ID. That won't cause the RETURN status to be 1, or anything else. If you want a failure to occur when no rows are updated then check the value of @@ROWCOUNT. and then THROW or RETURN.
CREATE PROCEDURE [dbo].[UpdateStatus] @userID INT AS
BEGIN
    UPDATE [dbo].[User]
    SET Status=0
    WHERE Id = @userID;

    --RETURN example
    IF @@ROWCOUNT = 0
        RETURN 1; --Denote "failure"
    ELSE
        RETURN 0; --Denote Success

    --Or perhaps you want to THROW
    IF @@ROWCOUNT = 0
        THROW 89001, N'No rows were updated.',10; --USe a custom Error code appropriate for your application

END;


text:
Q: How to modify local variable within Invoke-Command I am trying to modify a variable within Invoke-Command in order to get out of a loop, however I'm having trouble doing that.
In the sample script below, I'm connecting to a host, grabbing information from NICs that are Up and saving the output to a file (Baseline). Then on my next iteration I will keep grabbing the same info and then compare Test file to Baseline file.
From a different shell, I've connected to the same server and disabled one of the NICs to force Compare-Object to find a difference.
Once a difference is found, I need to get out of the loop, however I cannot find a way to update the local variable $test_condition. I've tried multiple things, from Break, Return,  $variable:global, $variable:script, but nothing worked so far.
$hostname = "server1"
$test_condition = $false

    do {
        Invoke-Command -ComputerName $hostname -Credential $credential -ScriptBlock{

            $path = Test-Path -LiteralPath C:\Temp\"network_list_$using:hostname-Baseline.txt"

            if ($path -eq $false) {
                Get-NetAdapter | Where-Object Status -EQ "Up"  | Out-File -FilePath (New-Item C:\Temp\"network_list_$using:hostname-Baseline.txt" -Force)

            } else {
                Get-NetAdapter | Where-Object Status -EQ "Up" | Out-File -FilePath C:\Temp\"network_list_$using:hostname-Test.txt"
                $objects = @{
                    ReferenceObject = (Get-Content C:\Temp\"network_list_$using:hostname-Baseline.txt")
                    DifferenceObject = (Get-Content C:\Temp\"network_list_$using:hostname-Test.txt")
                    }
                $test_condition = (Compare-Object @objects).SideIndicator -ccontains "<="
                $test_condition #this is returning True <-----

            }

        }
    } until ($test_condition -eq $true)

Any tips? What am I doing wrong?
TIA,
ftex

A: You can pass variables into a remote script block with the $Using:VarName scope modifier, but you can't use typical $Global: or $Script to modify anything in the calling scope.  In this scenario the calling scope isn't the parent scope.  The code is technically running in a new session on the remote system and $Global: would refer to that session's global scope.
For example:
$var = "something"
Invoke-Command -ComputerName MyComuter -ScriptBlock { $Global:var = "else"; $var}

The remote session will output "else". However, after return in the calling session $var will output "something" remaining unchanged despite the assignment in the remote session.
Based on @SantiagoSquarzon's comment place the assignment inside the Do loop with a few other modifications:
$hostname = "server1"

do {
    $test_condition = $false
    $test_condition =
    Invoke-Command -ComputerName $hostname -Credential $credential -ScriptBlock{

        $path = Test-Path -LiteralPath C:\Temp\"network_list_$using:hostname-Baseline.txt"

        if ($path -eq $false) {
            Get-NetAdapter | Where-Object Status -eq "Up"  | Out-File -FilePath (New-Item C:\Temp\"network_list_$using:hostname-Baseline.txt" -Force)

        } else {
            Get-NetAdapter | Where-Object Status -eq "Up" | Out-File -FilePath C:\Temp\"network_list_$using:hostname-Test.txt"
            $objects = @{
                ReferenceObject = (Get-Content C:\Temp\"network_list_$using:hostname-Baseline.txt")
                DifferenceObject = (Get-Content C:\Temp\"network_list_$using:hostname-Test.txt")
                }

            (Compare-Object @objects).SideIndicator -contains "<=" # this is returning True <-----
        }

    }
} until ($test_condition -eq $true)

I don't know why you were using -ccontains considering "<=" has no casing implications.  Also it's very unusual to capitalize operators.
Notice there's no explicit return or assignment.  PowerShell will emit the Boolean result of the comparison and that will be returned from the remote session and end up assigned to the $test_condition variable.
An aside:
I'm not sure why we want to use -contains at all.  Admittedly it'll work fine in this case, however, it may lead you astray elsewhere. -contains is a collection containment operator and not really meant for testing the presence of one string within another. The literal meaning of "contains" makes for an implicitly attractive hazard, as demonstrated in this recent question.
In short it's easy to confuse the meaning, purpose and behavior on -contains.
This "<=" -contains "<=" will return "true" as expected, however "<==" -contains "<=" will return "false" even though the left string literally does contain the right string.
The answer, to the aforementioned question says much the same. My addendum answer offers a some additional insight for the particular problem and how different operators can be circumstantially applied.
So, as a matter of practice for this case wrap the Compare-Object command in the array sub-expression operator like:
@( (Compare-Object @objects).SideIndicator ) -contains "<="

Given the particulars, this strikes me as the least intrusive way to implement such a loosely stated best practice.