text:
Q: Different output in Lua and LuaLaTeX I'm using TeX Live 2020 (with LuaLaTeX 1.12.0) and Lua 5.3.

When I compile the following .tex file using lualatex --shell-escape the content of the resulting .pdf is a.
\documentclass{article}
\usepackage{luacode}

\begin{luacode}
T =
{
    { "a", 5 },
    { "b", 2 }
}
\end{luacode}

\begin{document}
\luaexec{tex.print(T[1])}
\end{document}

Further, T[1]=="a" and T[2]==5, T[3] does not output a value and does not throw an error in LuaLaTeX. T[1][1] and T[1][2] also do not do anything, but T[2][1] throws

attempt to index a number value (field '?')

Running similar code directly in Lua, namely this code:
T =
{
    { "a", 5 },
    { "b", 2 }
}

print(T[1])

I get the expected output, namely the adress of the table:

table: 0x559417e736b0

What is happening here, and what am I doing wrong?
I am very confused.

A: Looks like a 'feature' of luacode: if I either run everything into one line or use \directlua then all is well. Specifically, if you trace the TeX, the outer set of braces are being lost so Lua is seeing
T =

    { "a", 5 },
    { "b", 2 }

which gives the result you see.
That suggests a bug in luacode where a brace group is dropped, probably a delimited argument. In general, I'd avoid luacode and either use \directlua with 'safe' Lua snippets or put them in a separate file and use require(). (The Lua file could be part of the TeX source using `filecontents.)


text:
Q: How do I create a map with string key and array as value (brickhouse hive UDFs) I have a table with the following columns
transaction_id,
mode,
tag_name,
tag_type

There could be multiple tag names for a transaction_id and each tag name could have varying types (in the context of the transaction)
I'm trying to create a new table out of this
transaction_id,
mode
tagnametype map<tag_name, tag_type>
tagtypename map<tag_type, array<tag_name>>

using a single query
create table transaction_tags
select transaction_id, mode, collect(tag_name, tag_type), collect(tag_type, tag_name)
from transactions
group by trans
action_id, mode

The first map has no issues as tag_name's for a transaction are unique and it will have all the values. But the second has only one value for each type. Which tells me it is acting like a Java Map where latest overwrites existing. Is there a value to collect all of this in one array against the key?
Something like an inversion. Like for example inversion(map(k,v)) = map(v, [k])

A: Sadly, the following query should work, but is probably not what you want to do.
I'm not sure if the current Hive optimizer can do this query in a single MapReduce Job. (My guess is no.)
SELECT transaction_id,
       mode,
       tn.tagnametype,
       tt.tagtypename
FROM
  ( SELECT transaction_id, mode,
           collect( tag_name, tag_type ) as tagnametype
     FROM trans_table
     GROUP BY transaction_id, mode
  ) tn
JOIN
  ( SELECT transaction_id, mode,
          collect( tag_type, tag_name_array ) as tagtypename
    FROM
      ( SELECT transaction_id, mode,
               collect( tag_name ) as tag_name_array
         FROM trans_table
         GROUP BY transaction_id, mode
      ) tc
  ) tt
ON ( tn.transaction_id = tt.transaction_id
  AND tn.mode = tt.mode );

Perhaps we should add a 'gather' or 'accumulate' UDF, which creates an array with all values seen for a key.  Please add feature request on the github site ( http://github.com/klout/brickhouse/issues )

redpajama_set_name: RedPajamaStackExchange


text:
Q: REGEX - Extraction between range and also ignore certain word (python) I need to extract value of vehicle class that satisfies multiple scenarios, hence tried to extract between range class and date but for few sample data unwanted values like holder and tolder need to be ignored.
I have tried with or condition as well but unable to exclude those words
Tried Regex :

*

*(?<=Class\s)[a-z A-Z(-|\s|\)]*(?=Date|TOLDER)

*(?<=Class\s)[a-z A-Z(-|\s|\)]*(?=Date)

sample data 1 :
Vehicle Class
LMV
MCWG
Date of Issue
sample data 2 :
Vehicle Class MCWG
Date of issue
sample data 3 :
Vehicle Class LMV MCWG
Date of issue
sample data 4 :
Vehicle Class LMV MCWOG
TOLDER SIGNATURE
Date of Issue
sample data 5 :
Vehicle Class MCWG LMV LMV-GV PSVBUS
Date of issue
sample data 6 :
Vehicle Class LMY MCWG
HOLDER SIGNATURE
Date of Issue
Expected output : value between Class and Date (for eg : in sample data 1 : LMV MCWG, in sample data 6 : LMY MCWG, where it should ignore HOLDER SIGNATURE)

A: You can use the pattern (MC[A-Z]+).*(LM[A-Z]+)|(LM[A-Z]+).*(MC[A-Z]+)
see https://regex101.com/r/08lN88/1

A: You can match either HOLDER or TOLDER using a character class. Instead of lookarounds you can capture the data that you want in a capture group.
In the character class you are using \s which also matches a space, and if you want to match a pipe char you can use a single | (note that it does not mean OR in a character class)
To prevent a partial word match, you can add word boundaries \b
\bClass\s([a-zA-Z(|)\s-]*?)\s*(?:Date|[HT]OLDER)\b

See a regex demo.
import re

pattern = r"\bClass\s([a-zA-Z(|)\s-]*?)\s*(?:Date|[HT]OLDER)\b"

s = ("sample data 1 :\n"
            "Vehicle Class\n"
            "LMV\n"
            "MCWG\n"
            "Date of Issue\n\n"
            "sample data 2 :\n"
            "Vehicle Class MCWG\n"
            "Date of issue\n\n\n"
            "sample data 3 : \n"
            "Vehicle Class LMV MCWG\n"
            "Date of issue\n\n"
            "sample data 4 :\n"
            "Vehicle Class LMV MCWOG\n"
            "TOLDER SIGNATURE\n"
            "Date of Issue \n\n"
            "sample data 5 :\n"
            "Vehicle Class MCWG LMV LMV-GV PSVBUS\n"
            "Date of issue\n\n"
            "sample data 6 :\n"
            "Vehicle Class LMY MCWG\n"
            "HOLDER SIGNATURE\n"
            "Date of Issue ")

print(re.findall(pattern, s))

Output
['LMV\nMCWG', 'MCWG', 'LMV MCWG', 'LMV MCWOG', 'MCWG LMV LMV-GV PSVBUS', 'LMY MCWG']


text:
Q: php: how fgets works? I wanted to make html pages for writing easier, so I made a small PHP script.
It should be read from a text file and write them in html format.
html page says: ";} fclose ($ f);?>, although it should say:
Hi!
This is test.
My code:

Artikkelin nimi

<?php
    $f = fopen("Tekstilaatikko.txt", "r");
    while (!feof($f)) {
        echo fgets($f) . "
";
    }
    fclose($f);
?>

I am sorry for my bad english.

A: Make sure that you have the file Tekstilaatikko.txt in the folder that your .php file is located.
Note :
Also file should have the extension .php
(If you want to have your file as .html extension, you need to do some additional configuration)


text:
Q: WAMP 3.1.7 x64 my webpage accessible from anywhere in the world Before I give out my question, I'd like to tell you my reasons of why I need this to work. I am currently making a game and in the future I'll need people to test the game to help me look for bugs. The purpose of this website I am making is to be used as a guide/wiki and for people to report the bugs and later on when the game is near to be open to public, to be the official page with a proper server/domain. With this said, I would like to temporarily have my PC as my webpage server and to be able to allow only the IPs of the game testers to connect my PC.
Can someone help me on this, please? Thank you in advance.

A: Exposing your ports publicly on the internet is always very tricky because it poses a huge security threat - especially since you just notified the world that you want to do that!
Instead, you should use Ngrok, a secure tool used extensively in the industry build specifically for this. It basically serves, in one line of code, a server running locally in a public url looking like https://<some-code>.ngrok.io. The only think you'll have to worry about would be hostname mismatch, but believe me, that's still a thousand times easier than to securely expose your personal machine to the internet ;)


text:
Q: Deciding if sets are bounded and/or closed How do we find out if a given set is bounded or closed?
1) $\{(x,y,z)\in \mathbb R^3 : x^2+2y^2-3z^3=1\}$
2) $\{(x,y,z) \in \mathbb R^3 : |x|+2|y|+3|z|\le 1\}$
3) $\{(x,y)\in \mathbb R^2 : (x-1)^2+(y-2)^2=9\}
\cup\{(x,y)\in \mathbb R^2 : y=3\}$

A: For a continuous function $f: \mathbb R^n \to\mathbb R$, its level sets
$$M_\alpha := \{y \in \mathbb R^n | f(y) = \alpha\}$$
as well as the sets
$$N_\alpha^+ := \{y\in \mathbb R^n | f(y) \ge \alpha\}\\
N_\alpha^- := \{y\in\mathbb R^n | f(y) \le \alpha\}$$
are closed. A finite union of closed sets remains closed.
For boundedness, try to find $\sup_{y\in A} \|y\|$ in a suitable norm. If you can prove it is finite, the set is bounded. If it's infinite, the set $a$ is unbounded.
In your case you can find sequences with $\|y_n\|_\infty \to\infty$ fairly easy for sets $A$ and $C$, and for set $B$, you can show that $\|y\|_1 \le 1$ easily as well.


text:
Q: Unable to select "Use a NAT instance instead" in AWS VPC Wizard I am trying to use the VPC Wizard to create a VPC with Public and Private subnets.  However, during the set-up, I don't see an option for "Use a NAT instance instead", and only able to see the default option of "Specify the details of your NAT gateway".
Can someone tell me why I am not able to use a NAT instance instead?
Image attached for reference.

A: I think this is because the NAT Instance is based on Amazon Linux (v1) and that OS reached end of standard support on December 31, 2020 per this announcement. Also see the related blog post.
I don't see an Amazon Linux 2 replacement NAT.


text:
Q: SQL Query to select files with specific extensions on Local Drives only I'm looking for a way to get files with specific extensions on the local drives only from WMI database.
SELECT *
FROM CIM_DataFile
WHERE Extension = 'vbs'
      AND Drive = UCASE(SELECT Caption
                        FROM Win32_LogicalDisk
                        WHERE Description = 'Local Fixed Disk')

I've came up with this idea above but it does not return any results. Let me know if I'm doing something wrong or if there is an easier way to do this.

A: So I was trying to find a way to use a JOIN or IN operation on WMI with no success. Then I find this WQL (SQL for WMI) which seems to show the operations allowed on WMI queries.
So whitout this operations the only way I could do what you want was with two queries like this:
strComputer = "."

Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colItems = objWMIService.ExecQuery("Select name from "&_
                           " Win32_LogicalDisk where MediaType <> 0",,48)

For Each objItem in colItems

    Set colItems2 = objWMIService.ExecQuery("Select * " &_
                                            "  from CIM_DataFile " &_
                                            " where Extension='vbs' " &_
                                            "   and Drive ='" & objItem.Name & "' ",,48)

    For Each objItem2 in colItems2
        Wscript.Echo "Extension: " & objItem2.Extension
        Wscript.Echo "FileName: " & objItem2.FileName
        Wscript.Echo "FileSize: " & objItem2.FileSize
        Wscript.Echo "FileType: " & objItem2.FileType
        Wscript.Echo "Name: " & objItem2.Name
        Wscript.Echo "#################################################"
    Next

Next

When I was working with the WMI I've find out a simple tool which helps a lot and it is just a file HTA named ScriptomaticV2. You can find it here on Microsoft Download Center Scriptomatic 2.0. It is a self-extract file.

A: Try something like this:
SELECT CASE
WHEN RIGHT(RTRIM(FileName), 4) = '.vbs' THEN FileName
END
FROM CIM_DataFile

Make sure to change the paramater names for your specification.


text:
Q: JavaFx Include custom components in FXML i try to find a solution on how to include custom javafx objects to a fxml file.
For example
package myExtendedObjects;

import javafx.scene.control.Label;

public class MyLabel extends Label interface connected{

    MyLabel(){
        super();
    }
  //Custom Code ...
}

into fxml
<?import myExtendedObjects.myLabel?>
<myLabel text="Name" />

i alsways get error codes from the type javafx.fxml.LoadException:
Maybe there is a better solution then creating custom classes. But i need a Label with a custom Interface (connected). maybe a other solution would be to creata a fxml file wich includes only a label and set up a controller class for this with the interface.
EDIT:
try {
        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/fxml/Viewer.fxml"));
        Parent root = fxmlLoader.load();
        Scene scene = new Scene(root);
        controller = fxmlLoader.getController();
        primaryStage.setScene(scene);
        primaryStage.show();
    } catch(Exception e) {
        e.printStackTrace();
    }

EDITS 2:
After changing Names, i was able to import the custom object without error
but when i try to insert
<MyLabel fx:id="myLabel"/>

in my xml date i get this error
javafx.fxml.LoadException:
/C:/Users/TheOLGPC/Desktop/java/SolarimpactTelemety2/bin/fxml/Viewer.fxml:48

at javafx.fxml.FXMLLoader.constructLoadException(FXMLLoader.java:2601)
at javafx.fxml.FXMLLoader.access$700(FXMLLoader.java:103)
at javafx.fxml.FXMLLoader$InstanceDeclarationElement.constructValue(FXMLLoader.java:1013)
at javafx.fxml.FXMLLoader$ValueElement.processStartElement(FXMLLoader.java:746)
at javafx.fxml.FXMLLoader.processStartElement(FXMLLoader.java:2707)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2527)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2441)
at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2409)
at application.Main.start(Main.java:24)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.IllegalAccessException: Class sun.reflect.misc.ReflectUtil can not access a member of class myExtendedObjects.MyLabel with modifiers ""
at sun.reflect.Reflection.ensureMemberAccess(Unknown Source)
at java.lang.Class.newInstance(Unknown Source)
at sun.reflect.misc.ReflectUtil.newInstance(Unknown Source)
at javafx.fxml.FXMLLoader$InstanceDeclarationElement.constructValue(FXMLLoader.java:1009)
... 15 more

Exception in Application start method

A: Java has various naming conventions, including that class names should be capitalized, package names should be all lower case, and field and method names should begin lower case.
While the Java compiler and runtime regards these only as conventions, and will determine whether any entity is a class or property from the context, essentially regardless of name, the same is not true in FXML and for the FXMLLoader.
The FXML documentation states:

an element's tag is considered an instance declaration if the tag begins with uppercase letter

and later

Elements whose tag names begin with a lowercase letter represent object properties.

So if your classes fail to follow the usual naming conventions, they may fail to work correctly in FXML. Make sure the class and interface names are capitalized, property names are not capitalized, and package names are all lower case, and make sure they are used consistently in the Java code and in the FXML.
Additionally, the FXMLLoader will create an instance of your class by invoking (usually) the no-argument constructor. In order for that to work, the constructor must be public:
package myExtendedObjects;

import javafx.scene.control.Label;

public class MyLabel extends Label interface connected{

    public MyLabel(){
        super();
    }
  //Custom Code ...
}


text:
Q: Warning when opening xls file which is exported from html table I used the following code. I can download the file with extension .xls. When I open this downloaded file I receive this warning:

The file you are trying to open, 'Statement.xls', is in a different
  format than specified by the file extension. Verify that the file is
  not corrupted and is from a trusted source before opening the file. Do
  you want to open the file now?

Javascript Code:
var blob = new Blob([document.getElementById('exportable').innerHTML], {
        type: "application/vnd.ms-excel;" });
saveAs(blob, "Statement.xls");`

HTML code:
`

ColumnOne	ColumnTwo	ColumnThree

row1Col1	row1Col2	row1Col3

row2Col1	row2Col2	row2Col3

row3Col1	row3Col2	test

`

External library:
https://rawgithub.com/eligrey/FileSaver.js/master/FileSaver.js

A: Office and Excel are able to cope with two different file formats. As those formats are totally different from the inside (the old one is binary, the new one is simply zipped up XML) different extensions and mimetypes were assigned to these formats.
Obviously you are creating a file with the new format and assign it the old extension. Excel complains about that.
Change your code to look like this:
var blob = new Blob([document.getElementById('exportable').innerHTML], {
        type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
saveAs(blob, "Statement.xlsx");

For the sake of learning you might want to have a look at your created file with a hex editor.
Others had similar issues, have a look here: https://github.com/eligrey/FileSaver.js/issues/139

A: When saving file with *.xls extension,  file type should be set to "application/xls"
Since file type and extension will be matching, you shouldn't get any warning.


text:
Q: Having trouble with infinite scroll I've been trying to get this infinite scroll script to work for the past 8 hours and can't figure it out.
I uploaded the site here so you can see the problem: http://kevinellerton.com/meditationmagazine/article01/  as you scroll down, it's supposed to load article04, then 03, then 02, and then stop loading articles since article01 was loaded already. The problem is that it doesn't stop loading them... and if you track the console-logged variables in the console, it's really wonky. I think the problem might have to do with "scope" but I'm not sure :-(
Please help if you can!
Thank you so much!
$(document).ready(function() {

// DATABASE OF ARTICLES
var database = [
    "article04",
    "article03",
    "article02",
    "article01"
];

// THIS WHOLE SECTION CREATES THE INFINITE SCROLL EFFECT BY ACCESSING THE ARTICLES IN ORDER.
// IT'S NOT QUITE WORKING THOUGH.
// IF YOU FIGURE OUT THE BUGS, YOU CAN ACTIVATE INFINITE SCROLL!
// POST CODE ON STACKOVERFLOW... MAYBE YOU'LL GET SOME HELP!

// get initial page name
if (articleCounter == 0) {
    var pathArray = window.location.pathname.split('/');
    var pageName = pathArray[2];
    console.log(pageName);
}

// initialize variables
var win = $(window);
var articleCounter = 0;
console.log(articleCounter);

// Each time the user scrolls
win.scroll(function() {
    // End of the document reached?
    if ($(document).height() - win.height() == win.scrollTop()) {
        $('#loading').show();

        // if this article is the next one in the list, skip it and go to next one
        if (pageName == database[articleCounter]) {
            articleCounter++;
            var nextPage = database[articleCounter];
            pageName = nextPage;
            console.log(nextPage);
        } else {
            var nextPage = database[articleCounter];
            pageName = nextPage;
            console.log(nextPage);
        }

        // append nextPage to the end of the document
        if (nextPage !== undefined) {
            $.ajax({
                url: '../' + nextPage + '/index.php',
                dataType: 'html',
                success: function(html) {
                    $('body').append(html);
                    $('#loading').hide();
                    articleCounter++;
                        console.log(articleCounter);
                    // POSSIBLE TO CHANGE URL PATH NAME HERE???
                }
            });
        }
    }
});
});

EDIT:
I totally re-wrote it today and it's still having the exact same problems. I'm 90% sure that the problem has to do with SCOPE, but I'm not quite figuring it out. Here's my new code that's still not working:
$(document).ready(function() {
// DATABASE OF ARTICLES
var database = [
    "article04",
    "article03",
    "article02",
    "article01"
];

var articleCounter = 0;

// get initial page name
var pathArray = window.location.pathname.split('/');
var initialPage = pathArray[2];
alert("Initial page is " + initialPage);

// when you scroll
$(window).scroll(function() {
    // if you've reached the end of the document
    if ($(document).height() - $(window).height() == $(window).scrollTop()) {
        $('#loading').show();
         // if you've reached the end of the database
        if (articleCounter >= database.length) {
            // load ending footer
            alert("You've reached end of database! articleCounter is " + articleCounter);
            // quit program
        }
        else if (database[articleCounter] == initialPage) {
            articleCounter++;
            appendArticle();
            articleCounter++;
        }
        else {
            appendArticle();
            articleCounter++;
        }
    }
});

// end scroll function

function appendArticle() {
    $.ajax({
        url: '../' + database[articleCounter] + '/index.php',
        dataType: 'html',
        success: function(html) {
            $('body').append(html);
            $('#loading').hide();
            // POSSIBLE TO CHANGE URL PATH NAME HERE???
        }
    });
}

A: You have defined variable in if statement, that's not ok, and I'll suppose that your logic for getting next page and counter is OK, and btw you commented almost all the code with /* */ so:
$(document).ready(function() {
//you will return to page beginning if no article, so you don't have to include article1

// DATABASE OF ARTICLES
var database = [
    "article04",
    "article03",
    "article02"
];

// initialize variables
var win = $(window);
var articleCounter = 0;
var loaded = true;
// Each time the user scrolls
win.scroll(function() {
    if ($(document).height() - win.height() == win.scrollTop()) {
        if(articleCounter == database.length){
            window.scrollTo(0,0);
            return;
        }

        if(!loaded) return
        $('#loading').show();
        loaded = false;
            $.ajax({
                url: '../' + database[articleCounter] + '/index.php',
                dataType: 'html',
                success: function(html) {
                    $('body').append(html);
                    $('#loading').hide();
                    articleCounter++;
                    loaded = true;
                }
            });

    }
});

});

A: $(document).ready(function () {

// DATABASE OF ARTICLES
var database = [
    "article04",
    "article03",
    "article02",
    "article01"
];

var win = $(window);
ArticleLoad_Counter = database.length - 1;// Assuming that article01 is initialy loaded. ie, then we need to load remaing 3 articles.
articleCounter = 0;
var pathArray = window.location.pathname.split('/');
var pageName = pathArray[2];
console.log(pageName);

$(window).scroll(function () {
    if ($(win).scrollTop() + $(window).height() == $(document).height()) {

        // Scroll bar reached at bottom
        alert("reached bottm");
        if (ArticleLoad_Counter != 0) {
            $('#loading').show();

            if (pageName == database[articleCounter]) {
                articleCounter++;
                nextPage = database[articleCounter];
                pageName = nextPage;
                console.log(nextPage);
                LoadNewArticle(nextPage);  // Function for Ajax Call

            } else {
                nextPage = database[articleCounter];
                pageName = nextPage;
                console.log(nextPage);
                LoadNewArticle(nextPage); // Function for Ajax call
            }
        }
    }
});

});

   function LoadNewArticle(nextPage) {
   $.ajax({
    url: '../' + nextPage + '/index.php',
    dataType: 'html',
    success: function (html) {
        $('body').append(html);
        $('#loading').hide();
        ArticleLoad_Counter--;
        alert(nextPage);   // Loaded article name
        console.log(articleCounter);
        // POSSIBLE TO CHANGE URL PATH NAME HERE???
     }
    });

    }

Hope this code will works for your site!!


text:
Q: How to search a GitHub fork for code using the GitHub Search API? I can't figure out how to get search results from a fork of a GitHub repository.
I'm using the GitHub API for this, but I can reproduce the problem using the search dialogs on github.com. Here's an example: The repository PEZ/Sketch-Plugin-Testing-Repo is a fork of getflourish/Sketch-Mate. They both contain a manifest.json file with several mentions of the word shortcut. The GitHub Code Search documentation says:

Much like with repositories, you can opt to search code files that exist within forked repositories. However, to ensure better relevancy, repository forks will not be searchable unless the fork has more stars than the parent repository.
If you would like forked results to appear, add the fork:true qualifier. For example:
android language:java fork:true
Matches code in a forked repository with the word "android" that's written in Java.

Thus, a search for shortcut in:file filename:manifest.json repo:PEZ/Sketch-Plugin-Testing-Repo repo:getflourish/Sketch-Mate fork:true, should return results from both repos. But it contains no search results at all.
Omitting the fork:true qualifier - shortcut in:file filename:manifest.json repo:PEZ/Sketch-Plugin-Testing-Repo repo:getflourish/Sketch-Mate, we do get search results from the original (non-fork) repository.
What am I not understanding in this?
To make things a bit more mysterious consider the repository repo:TeamTwisted/external_chromium_org which is a fork of OptiPop/external_chromium_org. These two repositories also contain manifest.json files containing the word shortcut.
Searching for shortcut in:file filename:manifest.json repo:PEZ/Sketch-Plugin-Testing-Repo repo:getflourish/Sketch-Mate repo:TeamTwisted/external_chromium_org repo:OptiPop/external_chromium_org fork:true, includes results only from the TeamTwisted/external_chromium_org repository. While omitting the fork:true qualifier return results from all repositories except PEZ/Sketch-Plugin-Testing-Repo.
Anyone has a clue on what's going on? Is the PEZ/Sketch-Plugin-Testing-Repo just fully unsearchable for some reason? The only thing special with my testing repo would be that it is a freshly made fork. Maybe I forked it off on November 8 or some such (two days ago at the time of this writing).
Ideally I'd like to use one search query and get back results from a given set of repositories wether they are forks or not. But to just consistently get results from forks would be a good start...

A: You reached out to GitHub support as well, so I wanted to share the answer you got from Jess here, in case that helps.

When a fork has less stars than its parent, it is not indexed at all for code search. So it won't show up even when you use fork:true. The fork:true search filter is used to show results for forks that have been indexed for search.
In the example of the TeamTwisted/external_chromium_org fork, that code is searchable because it has more stars than its parent repo. However the PEZ/Sketch-Plugin-Testing-Repo fork does not, so it won't be searchable at all with any filter.


text:
Q: SwiftUI: Environment Object Publisher doesn't send updates in onReceive I have a Network Monitor from where I want to receive notifications when status has changed.
Looks like this:
 final class NetworkMonitor: ObservableObject {
    let monitor = NWPathMonitor()
    let queue = DispatchQueue(label: "Monitor")

    static let shared = NetworkMonitor()

    @Published var status: NetworkStatus = .connected

    func start() {
        self.monitor.pathUpdateHandler = { [weak self] path in
            guard let self = self else { return }
            DispatchQueue.main.async {
                self.status = (path.status == .satisfied) ? .connected : .disconnected
            }
        }

        self.monitor.start(queue: self.queue)
    }
}

I create in Home a @StateObject of Network monitor and send it by an environment object.
struct HomeView: View {
    @StateObject var networkMonitor = NetworkMonitor()

    var body: some View {
        NavigationView {
            ContentView().environmentObject(networkMonitor)
        }
     }
 }

And I want in ContentView to receive any changes occur.
struct ContentView: View {
  @EnvironmentObject var networkMonitor: NetworkMonitor
  var body: some View {
     VStack {
         Text("Example")
     }.onReceive(self.networkMonitor.$status, perform: { status in
            print("onReceive \(status)") // <---- this doesn't trigger
       })
   }
}

I can't figure it out why whenever a change occurs in network status, the onReceive doesn't trigger.
EDIT: I am using shared instance to start monitoring in AppDelegate.
     func application(_: UIApplication, didFinishLaunchingWithOptions _: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        NetworkMonitor.shared.start()
}

A: You're using a different instance in your AppDelegate (shared) than you are in your HomeView (NetworkMonitor()).
Usually, when you use a singleton pattern, you want to make the init private so that you can avoid this mistake:
final class NetworkMonitor: ObservableObject {
    let monitor = NWPathMonitor()
    let queue = DispatchQueue(label: "Monitor")

    static let shared = NetworkMonitor()

    @Published var status: NetworkStatus = .connected

    private init() { } //<-- Here

    func start() {
        self.monitor.pathUpdateHandler = { [weak self] path in
            guard let self = self else { return }
            DispatchQueue.main.async {
                self.status = (path.status == .satisfied) ? .connected : .disconnected
            }
        }

        self.monitor.start(queue: self.queue)
    }
}

struct HomeView: View {
    @StateObject var networkMonitor = NetworkMonitor.shared //<-- Here

    var body: some View {
        NavigationView {
            ContentView().environmentObject(networkMonitor)
        }
     }
 }


text:
Q: how to use session variable in Linq How to get Session["UserId"] value in Linq Query
 var result = (from c in db.UserMaster
                      where c.UserID == Session["vUSerID"].ToString()
                      select C ).ToList();

but when i execute it gives me error as follows

LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression.

Please guide me how to works with ToString()

A: You need to materialize the value before you send it off to be translated to SQL:
var userId = Session["vUSerID"].ToString();
var result = (from c in db.UserMaster
                  where c.UserID == userId
                  select C ).ToList();

A: Alternatively, you could try bringing entity into memory first, and then apply the condition to get the filtered result, although not recommended because of the potential performance issue.
var result = db.UserMaster.Select(x => x).ToList().Where(x => x.UserId == Session["vUSerID"].ToString()).ToList();


text:
Q: Objective-c/iOS - Open local html file with Safari I have an HTML file save in a temporary directory like that :
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *documentDirectory = NSTemporaryDirectory();
NSString *documentPath = [documentDirectory stringByAppendingPathComponent:@"mydocument.html"];
[fileManager createFileAtPath:documentPath contents:myHTMLDocumentData attributes:nil];

The document is created in my temporary file. After it, I want to open this document in Safari but it doesn't work :
NSURL *url = [NSURL fileURLWithPath:documentPath];
[[UIApplication sharedApplication] openURL:url];

Nothing happen at screen, no error...
However, if I replace "url" by @"http://google.fr", Safari is launched with google.fr and I can access to my temporary file by typing the url "file://localhost..../myHtmlDocument.html" in Safari.
Hope you can help me

A: You cannot open a document with resides in your app bundle through Safari (please, see iOS Security Model).
What you need is using an UIWebView to display your document content inside your app using – loadHTMLString:baseURL:; e.g.:
UIWebView* webView = [[[UIWebView alloc] initWithFrame:rect] autorelease];
[webView loadHTMLString:myHTMLSource baseURL:nil];
[self.view addSubview:webView];

A: i dont think you can achieve that, since both UIApplication openURL: and UIDocumentInteractionController will not open local files inside your bundle
Do the following instead, in your viewDidLoad
UIWebView *webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
[self addSubview:webView];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL fileURLWithPath: documentPath]];
[webView loadRequest:request];


text:
Q: QStyledItemDelegate how to make two widgets in one row? I'm created a QStyledItemDelegate class in which I want to make some item checkable and some with two widgets. But it is not working right. What am I missing? This is what it looks like:

See row 1, looks like the two widgets are there but they are not really showing. And I need some help to make item checkable (this is different than adding a checkbox?). Thank you.
Here is my QStyledItemDelegate class :
//! [0]
SpinBoxDelegate::SpinBoxDelegate(QObject *parent)
    : QStyledItemDelegate(parent)
{
}
//! [0]

//! [1]
QWidget *SpinBoxDelegate::createEditor(QWidget *parent,
    const QStyleOptionViewItem &option,
    const QModelIndex &index) const
{
    if (index.row()==1) {
    QLineEdit* lineBox;
    QCheckBox* checkBox;
    QWidget *panel;
    panel = new QWidget(parent);
    QHBoxLayout *layout = new QHBoxLayout;

    lineBox = new QLineEdit( );
    lineBox->setText("abc");
    checkBox = new QCheckBox( );

    layout->addWidget(checkBox);
    layout->addWidget(lineBox);
    panel->setLayout(layout);
    return panel;
}else if (index.row()==2) {
// need to make this check-able item?
}else{
    QLineEdit *editor = new QLineEdit(parent);
    return editor;
}
}
//! [1]

//! [2]
void SpinBoxDelegate::setEditorData(QWidget *editor,
                                const QModelIndex &index) const
{
int value = index.model()->data(index, Qt::EditRole).toInt();

if (index.row()==1) {
// need something here?
}else{
    QLineEdit *spinBox = static_cast<QLineEdit*>(editor);
    spinBox->setText("value");

}
}
//! [2]

//! [3]
void SpinBoxDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
if (index.row()==1) {
// need something here?
}else{
   QLineEdit *spinBox = static_cast<QLineEdit*>(editor);
   model->setData(index, spinBox->text(), Qt::EditRole);
}

}
//! [3]

//! [4]
void SpinBoxDelegate::updateEditorGeometry(QWidget *editor,
    const QStyleOptionViewItem &option, const QModelIndex &/* index */) const
{
editor->setGeometry(option.rect);
}
//! [4]

this is my main.cpp:
int main(int argc, char *argv[])
{
QApplication app(argc, argv);

QStandardItemModel model(4, 2);
//QTableView tableView;
QTreeView treeView;
treeView.setModel(&model);

SpinBoxDelegate delegate;
treeView.setItemDelegate(&delegate);
//! [0]

//tableView.horizontalHeader()->setStretchLastSection(true);
treeView.setRootIsDecorated(false);
treeView.setHeaderHidden(true);
treeView.setIndentation(20);
//! [1]
for (int row = 0; row < 4; ++row) {
    for (int column = 0; column < 2; ++column) {
        QModelIndex index = model.index(row, column, QModelIndex());
        model.setData(index, QVariant((row + 1) * (column + 1)));
    }
//! [1] //! [2]
}
//! [2]

//! [3]
treeView.setWindowTitle(QObject::tr("Spin Box Delegate"));
treeView.show();
return app.exec();
}
//! [3]

This is eventually what I want to achieve:

A: To maintain an order you must create a class that implements the custom widget.
On the other hand you must store the data in the roles since the editors can continuously be created and destroyed.
To obtain the correct size, use the sizeHint() that is stored in a role.
And finally so that you are always visible you must use the openPersistentEditor() method:
#include <QApplication>
#include <QHBoxLayout>
#include <QLineEdit>
#include <QCheckBox>
#include <QStyledItemDelegate>
#include <QStandardItemModel>
#include <QTreeView>
#include <QComboBox>
#include <QHeaderView>

enum CustomRoles{
    SelectRole = Qt::UserRole
};

class EditorWidget: public QWidget{
    Q_OBJECT
public:
    EditorWidget(QWidget *parent=nullptr)
        : QWidget(parent),
          checkBox(new QCheckBox),
          lineBox(new QLineEdit),
          comboBox(new QComboBox)
    {
        QHBoxLayout *layout = new QHBoxLayout(this);
        comboBox->addItems({"item1", "item2", "item3"});
        layout->addWidget(checkBox);
        layout->addWidget(lineBox);
        layout->addWidget(comboBox);
    }

    int currentIndex(){
        return comboBox->currentIndex();
    }
    void setCurrentIndex(int index){
        comboBox->setCurrentIndex(index);
    }
    QString text() const{
        return  lineBox->text();
    }
    void setText(const QString &text){
        lineBox->setText(text);
    }
    Qt::CheckState checkState() const{
        return checkBox->checkState();
    }
    void setCheckState(Qt::CheckState state){
        checkBox->setCheckState(state);
    }
private:
    QCheckBox *checkBox;
    QLineEdit *lineBox;
    QComboBox *comboBox;
};

class Delegate: public QStyledItemDelegate{
    Q_OBJECT
public:
    using QStyledItemDelegate::QStyledItemDelegate;
    void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const{
        Q_UNUSED(painter)
        Q_UNUSED(option)
        Q_UNUSED(index)
    }
    QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const{
        Q_UNUSED(option)
        Q_UNUSED(index)
        EditorWidget *editor = new EditorWidget(parent);
        return editor;
    }
    void setEditorData(QWidget *editor, const QModelIndex &index) const{
        EditorWidget *widget = static_cast<EditorWidget*>(editor);
        widget->blockSignals(true);
        widget->setText(index.data(Qt::DisplayRole).toString());
        Qt::CheckState state = static_cast<Qt::CheckState>(index.data(Qt::CheckStateRole).toInt());
        widget->setCheckState(state);
        widget->setCurrentIndex(index.data(CustomRoles::SelectRole).toInt());
        widget->blockSignals(false);
    }
    void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const{
        EditorWidget *widget = static_cast<EditorWidget*>(editor);
        model->setData(index, widget->text(), Qt::DisplayRole);
        model->setData(index, widget->checkState(), Qt::CheckStateRole);
        model->setData(index, widget->sizeHint(), Qt::SizeHintRole);
        model->setData(index, widget->currentIndex(), CustomRoles::SelectRole);
    }
    void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const{
        Q_UNUSED(index)
        editor->setGeometry(option.rect);
    }
    QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
    {
        QSize s =  index.data(Qt::SizeHintRole).toSize();
        return s.isValid() ? s: QStyledItemDelegate::sizeHint(option, index);
    }
};

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QTreeView treeView;
    QStandardItemModel model(4, 2);
    treeView.setModel(&model);

    Delegate delegate;
    treeView.setItemDelegate(&delegate);

    treeView.header()->setSectionResizeMode(QHeaderView::ResizeToContents);
    treeView.setRootIsDecorated(false);
    treeView.setHeaderHidden(true);
    treeView.setIndentation(20);
    for (int row = 0; row < 4; ++row) {
        for (int column = 0; column < 2; ++column) {
            QModelIndex index = model.index(row, column, QModelIndex());
            model.setData(index, QVariant((row + 1) * (column + 1)));
            treeView.openPersistentEditor(index);
        }
    }
    treeView.resize(treeView.sizeHint());
    treeView.show();

    return a.exec();
}

#include "main.moc"

The complete example can be found in the following link


text:
Q: Structure Group vs Gauge Group in Gauge Spontaneous Symmetry Breaking Recently I've been learning about spontaneous symmetry breaking (SSB) for gauge theories. I've stumbled across some really helpful resources, such as Hamilton's Mathematical Gauge Theory – With Applications to the Standard Model.
However I think I'm getting confused about the symmetries involved. In particular, I'm getting mixed up about when we want something to be $G$-invariant vs $\mathcal{G}$-invariant.
Suppose we have a gauge theory involving:

*

*A principal $G$-bundle $P \rightarrow M$ with structure group given
by a compact Lie group $G$.

*A complex representation $\rho: G \rightarrow \text{GL} \left( W \right)$, where $W$ is a finite
complex vector space with the standard Hermitian form.

*The associated vector bundle $E \rightarrow M$ with $E = P \times_{\rho} W$.

*Gauge group $\mathcal{G}$ of $P$.

In general, my question is this:
when do we expect objects in our theory to be $G$-invariant vs $\mathcal{G}$-invariant?
Let me give some examples which have confused me. I know connection 1-forms describe our gauge fields, and sections of $E$ describe our Higgs fields.

*

*If we introduce a potential function $V: \Gamma \left( E \right) \rightarrow \mathbb{R}$ for our Higgs fields, should $V$ be $G$-invariant or $\mathcal{G}$-invariant?

*Should our Lagrangian be $G$-invariant or $\mathcal{G}$-invariant?

*Given a vacuum vector $w_0 \in W$, which minimizes $V$, we can define the unbroken subgroup to be the isotropy group / stabilizer $H$ of $w_0$. If $H \subset G$ is a proper subgroup, then we have a spontaneously broken symmetry. However I thought the full initial symmetry we expected of our system was $\mathcal{G}$, not $G$?

I thought $\mathcal{G}$ was the symmetry group for our theory, so we always should expect objects to be $\mathcal{G}$-invariant. However I've often seen authors assume $G$-invariance instead.
Perhaps I've got something basic wrong here. Or maybe I'm confused because I am interested in SSB for arbitrary gauge theories, while texts like Hamilton often make assumptions I'm not accustomed to (due to their interest in physical applications). For example, Hamilton assumes $G$ is compact and $M$ is Minkowski space (so connected and simply connected) so $P$ is trivial. In this case, I know $\mathcal{G} \simeq \text{Map} \left( M, G \right)$. Perhaps this is why some objects can be said to be $G$-invariant rather than $\mathcal{G}$-invariant?

A: Before answering the full question, let me address the definition of $\mathcal{G}$ and connect to your last paragraph. For a generic principal $G$-bundle $\pi:P\to M$, the gauge group $\mathcal{G}(P)$ is defined as
$$\mathcal{G}(P) :=\left\{\vphantom{\int}\psi:P\to P\quad \middle|\quad \psi(p\, g) = \psi(p) g\quad  \text{and}\quad \pi(\psi(p)) = \pi(p),\ ^\forall p\in P,\ ^\forall g\in G\right\}.\tag{1}$$
You can see that if $P$ is the trivial bundle $P=M\times G$, then the equation
$$\psi(p) = (m, \varphi(m) g), \qquad ^\forall (m,g)\in P,$$
defines for all $\psi\in\mathcal{G}(P)$ a function $\varphi:M\to G$ and thus, indeed
$$\mathcal{G}(M\times G) \cong \operatorname{Maps}(M,G)\equiv C^\infty(M,G)\equiv \Omega^0(M;G).$$
Now, going back to the generic case, the subgroup of $\mathcal{G}(P)$ generated by constant maps1 is precisely $G$, the group of global transformations:
$$ \left\{\text{constant}\ \psi\in\mathcal{G}(P)\right\}\cong G \subset \mathcal{G}(P).$$
These are the global transformations.
Now, to answer your questions, the Lagrangian and hence also candidates for Higgs-type potentials, should be $\mathcal{G}(P)$-invariant. You can show, for example, from the definition (1) that the Yang-Mills action is $\mathcal{G}(P)$-invariant. This should always be the case when you're building a gauge theory.
Moving on to your last bullet, let me first make an aside on terminology. Gauge invariance is not a symmetry, but a redundancy in the description. It can therefore not break. The scenario you describe there is most commonly referred to as having Higgsed the gauge invariance, and the term spontaneous symmetry breaking is reserved for global symmetries. Nevertheless, in the usual treatment of Higgsing, in order to arrive at the Higgsed Lagrangian it was necessary to fix a gauge i.e. choose a very carefully picked $\psi\in\mathcal{G}(P)$ and stick with it. You no longer have a gauge transformation available and the remaining symmetry is exactly $H\subset G$, not a larger, infinite group of bundle isomorphisms over it.  This is explained (with a physics language) for example here.

1 in the trivial bundle case those are the ones that satisfy $\mathrm{d}\varphi = 0$, in the non-trivial case you can demand that patchwise and demand they glue nicely on overlaps


text:
Q: VB - show msgbox once a time(r) I have the following code :
Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        Dim mesaj As New Integer

        My.Computer.Network.DownloadFile("http://rotutorial.net/anunt.txt", "c:\classmate\msg1.txt", "", "", False, 60000, True)
        Dim readtext As New System.IO.StreamReader("c:\classmate\msg1.txt")
        Dim text As String
        text = readtext.ReadToEnd
        readtext.Close()
        Dim parti(10) As String
        parti = text.Split("_")

        Dim writetext1 As New System.IO.StreamReader("c:\classmate\msg.txt")
        Dim text1 As String
        Dim parti1(10) As String
        text1 = writetext1.ReadToEnd
        parti1 = text1.Split("_")

        writetext1.Close()
        Dim unic As New Integer
        unic = Val(parti(0))
        Dim unic1 As New Integer
        unic1 = Val(parti1(0))

        If unic <> unic1 Then
            If unic <> unic1 Then
                mesaj = MsgBox(parti(3), vbYesNo, "Mesaj")
            End If
            Dim writetext2 As New System.IO.StreamWriter("c:\classmate\msg.txt")
            Dim text2 As String
            text2 = text & "/" & text1
            writetext2.Write(text2)
            writetext2.Close()

            Timer1.Enabled = False
            Timer1.Enabled = True
        End If
        Timer1.Enabled = False
        Timer1.Enabled = True

    End Sub

The timer interval is set to 5000(5 seconds), but every time when the timer is ticking the msgbox appears on screen but the in the file msg.txt is writting once. So, The timer check if that unic is different from unic1, and if is different shows up a msg box, and it's writting the new line in msg.txt, but on next timer tick, even if the unic and unic1 are equals the msgbox shows up anyway, but it's more interesting because it doesn't write again in file, only shows up the msgbox. I don't understand this.
Sorry for my bad english, i'm from Romania.
Thank you!

A: A message box can be a bit dangerous when used for the right reasons in the wrong place.  This is one of them.  The problem is that it does the equivalent of calling DoEvents, in a loop, designed to keep the message loop operational.  So that Windows messages, like Paint events and input events for the message box get dispatched and processed as normal.  That prevents your UI from freezing.
That can however cause re-entrancy problems.  Message box solves the most severe ones by disabling all the windows in your application.  Note the beep you get when you click on one of those windows.  That however does not block Timer messages.  So after 5 seconds, your Timer1_Tick() method runs again.  Displaying another message box.  Wait long enough with dismissing them and your screen just fills up with message boxes.  You'll likely have additional problems from the file manipulation code running multiple times.
The workaround is simple, just disable the Timer at the start of the method.  Re-enable it at the end.  A BackgroundWorker is also a common choice in code like this, it prevents a slow file download from freezing your UI.


text:
Q: Understanding sequences in topological spaces Trying to understand what it means for a sequence to be in a topological space.
What are the possible sequences in $(\{1, 2, 3, 4\}, \tau_{triv})$ and $(\{1, 2, 3, 4\}, \tau_{disc})$? Do the sequences depend on the underlying topology?
I am thinking the only possible sequence in the given trivial space above is $\{1, 2, 3, 4\}$, unless $\{\}$ is also a sequence whereas there are $2^4$ possible sequences in the given discrete space above, among which are $\{1\}, \{1, 4\}, \{2, 3, 4\}$. Does that make sense?
The reason I ask this question is the following two proofs below:
In $(X, \tau_{triv})$, let $l \in X$ and $(x_n)$ be any sequence. If $N$ is 'any' neighborhood of $l$ then $N$ must, in fact, be the whole of $X$. So $n \ge 1 \implies x_n \in N \implies x_n \to l.$
In $(X, \tau_{disc})$, suppose $(x_n)$ converges to $l$. Now $\{l\}$ is open and is a neighborhood of $l$, so $\exists n_0 \in N$ s.t. $n \ge n_0 \implies x_n \in \{l\} \implies  x_n = l$. So $(x_n)$ is eventually constant (at $l$).
Why do they choose these particular neighborhoods in the proofs above? Likely because they are convenient for the conclusion. Then, why are these particular $N$ considered appropriately arbitrary? For example, do they choose $N$ to be $X$ in the first proof because there's possibly only one sequence ($\{1, 2, 3, 4\})$ for a limit to be in? What about $N = \{l\}$? Thanks.

A: If a topological space consists of a set $X$ and a topology $\tau$, a sequence in it is simply $(x_1,x_2,x_3,...),$ where $x_n\in X$ for all $n\in\mathbb N$.  There are infinitely many sequences in $X=\{1,2,3,4\}$, even though $X$ has only four elements. As spaceisdarkgreen commented, the possible sequences have nothing to do with the topology.  Whether or not a given sequence converges to a given point has to do with the topology.  A sequence converges to $l$ if the elements of the sequence are eventually in any neighborhood of $l$.  In the discrete topology, any subset of $X$ is open, so the elements of the sequence are eventually in any set containing $l$. In fact, $\{l\}$ itself is open, so the elements of the sequence are eventually in the singleton $\{l\}$; i.e., the sequence is eventually constant.  For example, $(1,2,1,1,1,1,1,1,1,...)$ converges in the discrete and in the trivial topology, whereas $(1,2,3,1,2,3,1,2,3,...)$ converges in the trivial but not in the discrete topology.


text:
Q: How to make object instance a hash key in Ruby? I have a class  Foo  with a few member variables. When all values in two instances of the class are equal I want the objects to be 'equal'.  I'd then like these objects to be keys in my hash.  When I currently try this, the hash treats each instance as unequal.
h = {}
f1 = Foo.new(a,b)
f2 = Foo.new(a,b)

f1 and f2 should be equal at this point.
h[f1] = 7
h[f2] = 8
puts h[f1]

should print 8

A: See http://ruby-doc.org/core/classes/Hash.html

Hash uses key.eql? to test keys for
  equality. If you need to use instances
  of your own classes as keys in a Hash,
  it is recommended that you define both
  the eql? and hash methods. The hash
  method must have the property that
  a.eql?(b) implies a.hash == b.hash.

The eql? method is easy to implement: return true if all member variables are the same. For the hash method, use [@data1, @data2].hash as Marc-Andre suggests in the comments.

A: Add a method called 'hash' to your class:
class Foo
  def hash
    return whatever_munge_of_instance_variables_you_like
  end
end

This will work the way you requested and won't generate different hash keys for different, but identical, objects.


text:
Q: Examining the convergence of $\sum\limits_{n=1}^{+\infty}(-1)^{n+1}\Bigl(1-2\exp\Bigl(\sum\limits_{k=1}^{n}\frac{(-1)^k}k\Bigr)\Bigr)$ Problem: Examine the convergence of the series$$\sum_{n=1}^{+\infty}(-1)^{n+1}\left(1-2\exp\left(\sum_{k=1}^n\frac{(-1)^k}k\right)\right).$$
Solution (part): For the sequence $\alpha_n=(-1)^{n+1}\Big(1-2\exp\Big({\textstyle\sum_{k=1}^{n}\frac{(-1)^k}{k}}\Big)\Big)\,,\; n\in\mathbb{N}\,,$ we have that

*

*$\alpha_{n}>0$ for all $n\in\mathbb{N}$. Indeed
\begin{alignat*}{2}
\log2+\sum_{k=1}^n\frac{(-1)^k}{k}&=\begin{cases}
>0\,, &n\;{\text{even}}\\
<0\,,&n\;{\text{odd}}
\end{cases}\quad&&\Rightarrow\\
\exp\big(\log2+\textstyle{\sum_{k=1}^n\frac{(-1)^k}{k}}\big)&=\begin{cases}
>1\,, & n\;{\text{even}}\\
<1\,,&n\;{\text{odd}}
\end{cases}\quad&&\Rightarrow\\
2\,\exp\big(\textstyle{\sum_{k=1}^n\frac{(-1)^k}{k}}\big)&=\begin{cases}
>1\,, & n\;{\text{even}}\\
<1\,,&n\;{\text{odd}}
\end{cases}\quad&&\Rightarrow\\
1-2\,\exp\big(\textstyle{\sum_{k=1}^n\frac{(-1)^k}{k}}\big)&=\begin{cases}
<0\,, & n\;{\text{even}}\\
>0\,,&n\;{\text{odd}}
\end{cases}\quad&&\Rightarrow\\
\alpha_n=(-1)^{n+1}\Big(1-2\exp\Big({\textstyle\sum_{k=1}^{n}\frac{(-1)^k}{k}}\Big)\Big)&>0\,.
\end{alignat*}

*$(\alpha_{n})_{n\in\mathbb{N}}$ is decreasing. ( This I wasn't able to prove fully.)

*$\lim(n\,\alpha_n)\neq0$. Indeed, for all $n\in\mathbb{N}$ we have
\begin{alignat*}{2}
\log2+\sum_{k=1}^{2n}\frac{(-1)^k}{k}&\stackrel{(*)}{>}\log\big(1+\tfrac{1}{20n}\big)>0\quad&&\Rightarrow\\
\exp\big(\log2+\textstyle{\sum_{k=1}^{2n}\frac{(-1)^k}{k}}\big)&>\exp\big(\log\big(1+\tfrac{1}{20n}\big)\big)=1+\frac{1}{20n}\quad&&\Rightarrow\\
-1+2\exp\big(\textstyle{\sum_{k=1}^{2n}\frac{(-1)^k}{k}}\big)&>-1+1+\frac{1}{20n}=\frac{1}{20n}\quad&&\Rightarrow\\
\alpha_{2n}=(-1)^{2n+1}\Big(1-2\exp\big(\textstyle{\sum_{k=1}^{2n}\frac{(-1)^k}{k}}\big)\Big)&>\frac{1}{20n}\quad&&\Rightarrow\\
\lim_{n\to+\infty}(2n\,\alpha_{2n})&\geqslant\lim_{n+\infty}2n\,\frac{1}{20n}=\frac{1}{10}\,.
\end{alignat*}
Because $\alpha_{n}>0$ for all $n\in\mathbb{N}$, we conclude that $\lim(n\,\alpha_n)\neq0$.

By Abel's-Pringsheim's theorem the series diverges.
(*) Proof?
Ideas about the monotonicity of the sequence?

A: By integrating the geometric series with remainder, we obtain
$$
 - \log 2 = \sum\limits_{k = 1}^n {\frac{{( - 1)^k }}{k}}  + ( - 1)^{n + 1} \int_0^1 {\frac{{x^n }}{{1 + x}}dx} .
$$
Now
\begin{align*}
\int_0^1 {\frac{{x^n }}{{1 + x}}dx} & = \int_0^{ + \infty } {\frac{{e^{ - nt} }}{{e^t  + 1}}dt}  = \frac{1}{{2n}} + \int_0^{ + \infty } {e^{ - nt} \left( {\frac{1}{{e^t  + 1}} - \frac{1}{2}} \right)dt} \\ & = \frac{1}{{2n}} + \int_0^{ + \infty } {e^{ - nt} \mathcal{O}(t)dt}  = \frac{1}{{2n}} + \mathcal{O}\!\left( {\frac{1}{{n^2 }}} \right).
\end{align*}
Thus
$$
\sum\limits_{k = 1}^n {\frac{{( - 1)^k }}{k}}  =  - \log 2 + \frac{{( - 1)^n }}{{2n}} + \mathcal{O}\!\left( {\frac{1}{{n^2 }}} \right).
$$
Consequently,
$$
2\exp \left( {\sum\limits_{k = 1}^n {\frac{{( - 1)^k }}{k}} } \right) = 2\exp \left( { - \log 2} \right)\exp \left( {\frac{{( - 1)^n }}{{2n}} + \mathcal{O}\!\left( {\frac{1}{{n^2 }}} \right)} \right) = 1 + \frac{{( - 1)^n }}{{2n}} + \mathcal{O}\!\left( {\frac{1}{{n^2 }}} \right)
$$
and therefore
$$
( - 1)^{n + 1} \left( {1 - 2\exp \left( {\sum\limits_{k = 1}^n {\frac{{( - 1)^k }}{k}} } \right)} \right) = \frac{1}{{2n}} + \mathcal{O}\!\left( {\frac{1}{{n^2 }}} \right).
$$
Since the harmonic series diverges, your series is divergent.


text:
Q: How to upsert record from one db connection to another in postgres using dbeaver? I have two connections in my dbeaver namely preproduction and postproduction. Both the database have a table called profiles.
I want to upsert data from my postproduction.profiles into preproduction.profiles
I tried using the import feature but it is not providing conditional insert
What is the correct way to do so?
(My preproduction.profiles already have some records that's why I need upsert)

A: In DBeaver during export or import process you can change some settings params, one of them - replace method. This method has 3 values:

*

*none

*ON CONFLICT DO NOTHING

*ON CONFLICT DO UPDATE

You can choose 2nd or 3rd for upsert.
For more detail information please visit these sites:
DBeaver Data Import and Replace
PostgreSQL Upsert Using INSERT ON CONFLICT statement


text:
Q: Keymap causes Readline Delay on `.` in Vi Mode When I press . in Vi/command mode there is always a delay (half a second) before the last action gets repeated.
I found that this is caused by my .inputrc:
set editing-mode vi
set keymap vi-command
"d-": kill-line

Why is the "d-" mapping causing this delay?

Repro:

*

*In Bash insert mode enter foo bar foobar

*press esc, type 0

*enter dw to delete foo

*press . to delete bar (there is a delay)

*press . to delete foobar (there is a delay)


text:
Q: Intercept every view element being inflated? I am trying to intercept every view widget that is being inflated in my activity and override the setText functionality of that view if it exists.
So if a TextView has a android:text="bla" in the XML layout i want to be able to intercept that and maybe add a ** at the end of all texts being set from the xml.
One way that seems to be close to what i need is to use a Custom Layout inflator.
 LayoutInflaterCompat.setFactory(layoutInflator, InflatorOnSteriods(this))

and the in my InflatorOnSteriods to override onCreateView and then intercept all views there.. this approach doesn't seem to work at all. onCreateView is never called.
I tried also to use cloneInContext
 LayoutInflaterCompat.setFactory(layoutInflater.cloneInContext(this), InflatorOnSteriods(this))

But no luck as well, maybe my approach is totally wrong i am also open to a different way where i can intercept all views being presented and to be specific set a certain attribute on that view. It is really important to make sure that i will be the last one changing that view and make sure the system respects my changes and wont override them later.
Update:
Although i don't think its relevant; Code of InflatorOnSteroids.kt
class InflatorOnSteriods(val appCompatActivity: AppCompatActivity) : LayoutInflaterFactory {

override fun onCreateView(parent: View, name: String, context: Context, attrs: AttributeSet): View {
    var result: View

    if (TextUtils.equals(name, "DebugDrawerLayout")) {
        result = ImageView(context, attrs)
    }
    result = appCompatActivity.onCreateView(name, context, attrs)
    if (result == null) {
        // Get themed views from app compat
        result = appCompatActivity.delegate.createView(parent, name, context, attrs)
    }
    return result
}
}

A: After some time troubleshooting my solution i finally managed to achieve what i wanted with the inflator factory solution.
First i create an abstract activity that has a custom inflator set to it.
abstract class SteroidsActivity : AppCompatActivity() {

var mInflater: LayoutInflater? = null
abstract fun getActivityLayout(): Int

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    mInflater = layoutInflater?.cloneInContext(this)
    LayoutInflaterCompat.setFactory(mInflater, InflaterOnSteroids(this))
    setContentView(getActivityLayout())
}

override fun getLayoutInflater(): LayoutInflater? {
    return mInflater
}

override fun getSystemService(name: String): Any? {
    if (name == LAYOUT_INFLATER_SERVICE) {
        if (mInflater == null) {
            mInflater = super.getSystemService(name) as LayoutInflater
        }
        return mInflater
    }
    return super.getSystemService(name)
  }
}

Second thing that you need to do is create your custom inflator factory
class InflaterOnSteroids(appCompatActivity1: AppCompatActivity) : LayoutInflaterFactory {

    override fun onCreateView(parent: View?, name: String, context: Context, attrs: AttributeSet): View? {
      //Do stuff here and return a view
        return null
       }
 }

The problem with my code was that it was always crashing with a weird error that i couldn't troubleshoot until i realised that i need to add a ? after View since i'm using kotlin and parent view can be null :)
Happy programming
Good reference can be found here


text:
Q: How to change the style of an image inside an iframe I generate an iframe with Vaadin 7 and the result is:
<div class="zoom-to-fit" style="width: 1200px; height: 900px;">
    <iframe src="http://localhost:8090/image.png" frameborder="0" width="100%" height="100%">
    </iframe>
</div>

I can add a style class zoom-to-fit to the iframe, but the iframe is wrapped inside a div.
I am trying to stretch the image to the iframe, but it does not work.
I tried the following:
.zoom-to-fit {
    width: 100%;
    height: 100%;
}

.zoom-to-fit {
    background-size: 100% 100%;
}

.zoom-to-fit > html > body > img {
    width: 100%;
    height: 100%;
}

But they don't work.
I added the last one because the html code in the developer tools looks like:

I guess I cannot modify any styles inside the iframe... but how could I resize the image?
I know that if I go to the image and add the first style (width and height at 100% works) but I can only add or remove styles with the Vaadin framework I am using.

A: I saw this from a forum post that might help:
https://vaadin.com/forum/thread/393458/embedded-component-image-and-setwidth-resizing-both-component-and-image
also there's this from another SO question:
Resizing Vaadin Image

A: So, it is impossible to get to change the style with css, so the solution is a bit nasty (or not very nice).
CSS does not know the structure inside iframe, so that it is why it is not applied as I would have wanted. But since bot the site and the content of the iframe are from the same origin, javascript is safe to use (and the only way to make it work).
Luckily there is a tool in vaadin to execute javascript safely. So I can get the iframe tag and then the img tag.
import com.vaadin.ui.JavaScript;

JavaScript.getCurrent().execute(
    "document.getElementsByTagName('iframe')[1].contentDocument.body.children[0].style="
    + "'width: 100%; height: 100%;'");

This is vanilla javascript so it should work in most browsers.


text:
Q: Sort arrangement of Pandas column values? Assume, I have a Pandas DataFrame as following:
|    0 |   1 |   2 |   3 |
|-----:|----:|----:|----:|
| 1115 | nan | "YE"| nan |
| 1590 | nan | "He"| "NO"|

How can I rearrange such a DataFrame consisting of over 100 columns and rows, that the nan values are shifted to the right side and the real values to the left side:
Desired output:
|    0 |   1 |   2 |   3 |
|-----:|----:|----:|----:|
| 1115 | "YE"| nan | nan |
| 1590 | "HE"| "NO"| nan |

Note: this should also work for an arbitrary number of columns and rows.

A: IIUC
df=df.T.apply(lambda x : sorted(x,key=pd.isnull)).T
      0    0     1    2
0  1115  "YE"   NaN  NaN
1  1590  "He"  "NO"  NaN


text:
Q: The entity type Object is not part of the model for the current context I'm creating an object in this way:
var assembly = typeof (Cliente).Assembly;
var Tipo = assembly.GetType("Datos." + tipoItem);
var item = Activator.CreateInstance(Tipo);

where tipoItem is the name of a class and Datos is the respective namespace.
Cliente is a class in the same namespace.
To store the object in the database I have this generic method:
public void AddItem<TItem>(TItem item) where TItem : class
{
    db.Set<TItem>().Add(item);
    db.SaveChanges();
}

When debugging, the type of the item object is right. If tipoItem is "EmailCliente" then the type of item is Datos.EmailCliente.
The AddItem method receives item as a Datos.EmailCliente object but an exception is thrown:
"The entity type Object is not part of the model for the current context"
When debugging, TItem is of type object instead of Datos.EmailCliente and that's the problem.
I did try to cast item to Tipo using (Tipo), as Tipo, Convert.ChangeType(item, Tipo) but none of those work.
How can I cast item so the AddItem method accepts it.
TIA
EDIT:
Based on Andrei's answer this is the code that's working.
MethodInfo method = typeof(ControlDatos).GetMethod("AddItem");
MethodInfo generic = method.MakeGenericMethod(new[] { Tipo });
generic.Invoke(cd, new object[] { item });

where cd is an instance of the class ControlDatos where the AddItem method is defined.

A: When you are calling AddItem(item), compiler is deriving generic type from the argument and substituting it into method call. Since item is of type object (at compile time!) - this is what compiler is using. So really you are calling AddItem<object>(item), which gives you the error.
To resolve this you have to make a call of AddItem via reflection:
MethodInfo method = typeof(ItemRepository).GetMethod("AddItem", BindingFlags.Public | BindingFlags.Static);
MethodInfo generic = method.MakeGenericMethod("Datos." + tipoItem);
generic.Invoke(null, new object[]{item});

where ItemRepository is the class which defines AddItem method.


text:
Q: Iteratively generate restriction of multivariate function using Python I'm trying to write a function that generates the restrictions of a function g at a given point p.
For example, let's say g(x, y, z) = 2x + 3y + z and p = (5, 10, 15). I'm trying to create a function that would return [lambda x : g(x, 10, 15), lambda y: g(5, y, 15), lambda z: g(5, 10, z)]. In other words, I want to take my multivariate function and return a list of univariate functions.
I wrote some Python to describe what I want, but I'm having trouble figuring out how to pass the right inputs from p into the lambda properly.
def restriction_generator(g, p):
    restrictions = []
    for i in range(len(p)):
        restriction = lambda x : g(p[0], p[1], ..., p[i-1], p[x], p[i+1], .... p[-1])
        restrictions.append(restriction)
    return restrictions

Purpose: I wrote a short function to estimate the derivative of a univariate function, and I'm trying to extend it to compute the gradient of a multivariate function by computing the derivative of each restriction function in the list returned by restriction_generator.
Apologies if this question has been asked before. I couldn't find anything after some searching, but I'm having trouble articulating my problem without all of this extra context. Another title for this question would probably be more appropriate.

A: Since @bandicoot12 requested some more solutions, I will try to fix up your proposed code. I'm not familiar with the ... notation, but I think this slight change should work:
def restriction_generator(g, p):
    restrictions = []
    for i in range(len(p)):
        restriction = lambda x : g(*p[: i], x, *p[i+1:])
        restrictions.append(restriction)
    return restrictions

Although I am not familiar with the ... notation, if I had to guess, your original code doesn't work because it probably always inputs p[0]. Maybe it can be fixed by changing it from p[0], p[1], ..., p[i-1] to p[0], ..., p[i-1].

A: try something like this:
def foo(fun, p, i):
    def bar(x):
        p[i] = x
        return fun(*p)
    return bar

and
def restriction_generator(g, p):
    restrictions = []
    for i in range(len(p)):
        restrictions.append(foo(g, p, i))
    return restrictions


text:
Q: side bar with multiple collapsible sub menu in side bar wpf I have two toggle buttons which I am used to making to the collapsable sidebar sub-menu option. I want to display both collapsed initially. when of them is pressed it shout expand and when the other submenu is clicked the first one should collapse and the other one should get open.
                                <ToggleButton Grid.Column="0" Height="50" Style="{StaticResource CategoryButton}" FontSize="14" FontWeight="Regular" Foreground="{StaticResource SupremeFontColor}" Margin="6,2,6,0"
                                        FontFamily="{StaticResource FontFamily}" Content="Report Group" ToolTip="Report Group" x:Name="reportToggleButton"  BorderBrush="Transparent" Click="reportToggleButton_Click">
                                </ToggleButton>
                                <Grid  Height="60" Visibility="{Binding IsChecked, ElementName=reportToggleButton, Converter={StaticResource BoolToVisibilityConverter}}">
                                    <Grid.RowDefinitions>
                                        <RowDefinition/>
                                        <RowDefinition/>
                                    </Grid.RowDefinitions>
                                    <TextBlock Text="Fail Reports." Grid.Row="0" VerticalAlignment="Center" HorizontalAlignment="Center" Margin="0,0,0,0" Width="Auto" Height="30">
                                        <TextBlock.Style>
                                            <Style TargetType="TextBlock">
                                                <Setter Property="Background" Value="white" />
                                                <Style.Triggers>
                                                    <Trigger Property="IsMouseOver" Value="True">
                                                        <Setter Property="Background" Value="{StaticResource SupremeprimaryDarkBlue}" />
                                                    </Trigger>
                                                </Style.Triggers>
                                            </Style>
                                        </TextBlock.Style>
                                    </TextBlock>
                                    <TextBlock Text="Other Reports." Grid.Row="1" VerticalAlignment="Center" HorizontalAlignment="Center" Margin="0,0,0,0" Width="Auto" Height="30">
                                        <TextBlock.Style>
                                            <Style TargetType="TextBlock">
                                                <Setter Property="Background" Value="white" />
                                                <Style.Triggers>
                                                    <Trigger Property="IsMouseOver" Value="True">
                                                        <Setter Property="Background" Value="{StaticResource SupremeprimaryDarkBlue}" />
                                                    </Trigger>
                                                </Style.Triggers>
                                            </Style>
                                        </TextBlock.Style>
                                    </TextBlock>
                                </Grid>

                                <!--Sales Report-->
                                <ToggleButton Grid.Column="0" Height="50" Style="{StaticResource CategoryButton}" FontSize="14" FontWeight="Regular" Foreground="{StaticResource SupremeFontColor}"  Margin="6,2,6,0"
                                        FontFamily="{StaticResource FontFamily}" Content="Sales Report" ToolTip="Sales Report"  x:Name="salesToggleButton"  BorderBrush="Transparent" Click="salesToggleButton_Click">
                                </ToggleButton>
                                <Grid  Height="60" Visibility="{Binding IsChecked, ElementName=salesToggleButton, Converter={StaticResource BoolToVisibilityConverter}}">
                                    <Grid.RowDefinitions>
                                        <RowDefinition/>
                                        <RowDefinition/>
                                    </Grid.RowDefinitions>
                                    <TextBlock Text="Daily Course Summary" Grid.Row="0" VerticalAlignment="Center" HorizontalAlignment="Center" Width="Auto" Height="30">
                                        <TextBlock.Style>
                                            <Style TargetType="TextBlock">
                                                <Setter Property="Background" Value="white" />
                                                <Style.Triggers>
                                                    <Trigger Property="IsMouseOver" Value="True">
                                                        <Setter Property="Background" Value="{StaticResource SupremeprimaryDarkBlue}" />
                                                    </Trigger>
                                                </Style.Triggers>
                                            </Style>
                                        </TextBlock.Style>
                                    </TextBlock>
                                    <TextBlock Text="Finalize Event Payment Report" Grid.Row="1" VerticalAlignment="Center" HorizontalAlignment="Center" Width="Auto" Height="30">
                                        <TextBlock.Style>
                                            <Style TargetType="TextBlock">
                                                <Setter Property="Background" Value="white" />
                                                <Style.Triggers>
                                                    <Trigger Property="IsMouseOver" Value="True">
                                                        <Setter Property="Background" Value="{StaticResource SupremeprimaryDarkBlue}" />
                                                    </Trigger>
                                                </Style.Triggers>
                                            </Style>
                                        </TextBlock.Style>
                                    </TextBlock>
                                </Grid>

A: I would first clean-up your mess at least a little:
<!--I used StackPanel, but it can be any container you have-->
            <StackPanel>
                <StackPanel.Resources>
                    <Style TargetType="TextBlock" x:Key="myTextbox">
                        <Setter Property="Background" Value="White" />
                        <Setter Property="VerticalAlignment" Value="Center"/>
                        <Setter Property="HorizontalAlignment" Value="Center"/>
                        <Setter Property="Margin" Value="0"/>
                        <Setter Property="Width" Value="Auto"/>
                        <Setter Property="Height" Value="30"/>
                        <Style.Triggers>
                            <Trigger Property="IsMouseOver" Value="True">
                                <Setter Property="Background"  Value="White"/>
                            </Trigger>
                        </Style.Triggers>
                    </Style>

                    <Style TargetType="ToggleButton" x:Key="myToggleButton">
                        <Setter Property="Height" Value="50" />
                        <Setter Property="FontSize" Value="14"/>
                        <Setter Property="FontWeight" Value="Regular"/>
                        <Setter Property="Margin" Value="6,2,6,0"/>
                        <Setter Property="BorderBrush" Value="Transparent"/>
                    </Style>
                </StackPanel.Resources>

                <ToggleButton Content="Report Group" ToolTip="Report Group" x:Name="reportToggleButton" Click="reportToggleButton_Click" Style="{StaticResource myToggleButton}"/>

                <StackPanel Orientation="Horizontal" Height="60" Visibility="{Binding IsChecked, ElementName=reportToggleButton, Converter={StaticResource boolToVisibilityConverter}}">
                    <TextBlock Text="Fail Reports."   Style="{StaticResource myTextbox}"/>
                    <TextBlock Text="Other Reports." Style="{StaticResource myTextbox}"/>
                </StackPanel>

                <!--Sales Report-->
                <ToggleButton Content="Sales Report" ToolTip="Sales Report"  x:Name="salesToggleButton" Click="salesToggleButton_Click" Style="{StaticResource myToggleButton}"/>

                <StackPanel Orientation="Horizontal" Height="60" Visibility="{Binding IsChecked, ElementName=salesToggleButton, Converter={StaticResource boolToVisibilityConverter}}">
                    <TextBlock Text="Daily Course Summary" Style="{StaticResource myTextbox}"/>
                    <TextBlock Text="Finalize Event Payment Report" Style="{StaticResource myTextbox}"/>
                </StackPanel>

            </StackPanel>

And after would add something like this in your event handlers:
        private void reportToggleButton_Click(object sender, RoutedEventArgs e)
        {
            salesToggleButton.IsChecked = !(sender as ToggleButton).IsChecked;
        }

        private void salesToggleButton_Click(object sender, RoutedEventArgs e)
        {
            reportToggleButton.IsChecked = !(sender as ToggleButton).IsChecked;
        }

However I would recommend you to learn how to use standard components (maybe MenuItem or TreeItem would work for you) before considering creating something like that.


text:
Q: How to create a printable user form with a new USERID every time one downloads it in php How to create a printable user form with a new USERID every time one downloads it in php.
I have created a form in php. But I want it to be available in printable form as well. How to accomplish this, that whenever a user wants the printable form, a new form, with user id gets in the word document under applicant id field.


text:
Q: kernel panic error installing ubuntu 16.04 server in virtualbox 5.1.22 on windows 7 I am trying to install ubuntu server on my virtualbox vm but I get this error after I choose english as my language and then install ubuntu server. My logs do not seem to be giving me anything helpful. How can I get past this error so I can install ubuntu 16.04?

A: Is this the first time you've tried to run a VM on this machine?  My shot-in-the dark guess is that you haven't enabled the necessary BIOS settings on the host machine to allow VMs - or you have Hyper-V installed (which is sometimes installed along with other developer tools - like Docker or Visual Studio).  See this post: https://forums.virtualbox.org/viewtopic.php?f=6&t=57464

00:00:04.465388 HWACCM: No VT-x or AMD-V CPU extension found. Reason VERR_VMX_MSR_LOCKED_OR_DISABLED

You need to make sure that you have enabled hardware virtualization in you bios.
  Also make sure you do not have Hyper-V installed on the host. If yo do you need to disable it.

I believe they found the above error message by checking the VBox.log file.
 http://www.virtualbox.org/manual/ch12.html#collect-debug-info

Every time VirtualBox starts up a VM, a so-called "release log file" is created containing lots of information about the VM configuration and runtime events.
  The log file is called VBox.log and resides in the VM log file folder. Typically this will be a directory like this:
$HOME/VirtualBox VMs/{machinename}/Logs

Checking the contents of that file will hopefully provide more information to point you in the right direction.


text:
Q: encode a 0-1 matrix from an integer matrix numpy So I have an n*K integer matrix [Note: its a representation of the number of samples drawn from K-distributions (K-columns)]
a =[[0,1,0,0,2,0],
    [0,0,1,0,0,0],
    [3,0,0,0,0,0],
]

[Note: in the application context this matrix basically means that for the i row (sim instance) we drew 1 element from the "distribution 1" (1 \in [0,..K])  (a[0,1] = 1) and 2 from the distribution 4(a[0,4] = 2)].
What I need is to generate a 0-1 matrix that represents the same integer matrix but with ones(1). In this case, is a 3D matrix of n*a.max()*K that has a 1 for each sample that is drawn from the distributions. [Note: we need this matrix so we can multiply by our K-distribution sample matrix]
Output
b = [[[0,1,0,0,1,0], # we don't care if they samples are stack
      [0,0,0,0,1,0],
      [0,0,0,0,0,0]], # this is the first row representation
     [[0,0,1,0,0,0],
      [0,0,0,0,0,0],
      [0,0,0,0,0,0]], # this is the second row representation
     [[1,0,0,0,0,0],
      [1,0,0,0,0,0],
      [1,0,0,0,0,0]], # this is the third row representation

]

how to do that in NumPy ?
Thanks !

A: from @michael-szczesny comment
a = np.array([[0,1,0,0,2,0],
             [0,0,1,0,0,0],
             [3,0,0,0,0,0],
            ])
b = (np.arange(1, a.max()+1)[:,None] <= a[:,None]).astype('uint8')

print(b)
array([[[0, 1, 0, 0, 1, 0],
        [0, 0, 0, 0, 1, 0],
        [0, 0, 0, 0, 0, 0]],

       [[0, 0, 1, 0, 0, 0],
        [0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0]],

       [[1, 0, 0, 0, 0, 0],
        [1, 0, 0, 0, 0, 0],
        [1, 0, 0, 0, 0, 0]]], dtype=uint8)


text:
Q: Class group of $\mathbb Q(\sqrt{-55})$ and finding representatives for ideal classes My first step in computing the class group of $\mathbb Q(\sqrt{-55})$ was to compute the Minkowski bound. Initially, I said $\lambda(-55)=2\sqrt{-55}/\pi<2(8)/3<6$ and I went the normal way of finding an ideal of norm 5, $(5, \sqrt{-55})$ and this has a contribution to the class group since it is non-principal. But then I realised that I could get a better bound on $\lambda(-55)=2\sqrt{-55}/\pi<2(7.5)/3=5$. So in fact, I should have got no contribution from the ideal $(5, \sqrt{-55})$ and should have got that this ideal is in the same class as an ideal of norm $<5$.

I don't see how to get an ideal of norm $<5$ from $(5, \sqrt{-55})$ and I'm not sure why my argument above was wrong.

In more complicated situations, I'm worried that by making a mistake similar to the above, I would get much larger class groups than is correct. How do I avoid this mistake.

Is there a way of spotting if an ideal is in the same ideal class as an integral ideal of smaller norm, in general?

A: The first thing to note is that ideal classes are different from ideals, we say $I$ is in the class of  $J$ if $\exists (a),(b)$ with $(a)I=(b)J$. With this in mind, consider $(4\sqrt{-55})(5,\sqrt{-55})=(20\sqrt{-55},-220)=(\sqrt{-55})$. Now consider the ideal $(2,\frac{1+\sqrt{-55}}{2})$. I claim this is in the same class as $(5,\sqrt{-55})$.
Indeed, consider $$(10\sqrt{-55})(2,\frac{1+\sqrt{-55}}{2})=(20\sqrt{-55},5\sqrt{-55}+275)=(\sqrt{-55})$$
This answers your original question.
To get an ideal of norm $<5$, you want to consider ideals with norm $2$ or $3$. The way we do this is to determine whether $(2) , (3)$ are ramified in $K=\mathbb{Q}(\sqrt{-55})$.
Since $-55\equiv 1\pmod{4}$ we know that Disc($K)=-55$, and since neither $2$ nor $3$ divides 55, we see that neither prime is ramified. Thus, it remains to decide whether they are split completely or inert.
$(3)$ remains a prime in $K$, since $3$ is not a quadratic residue modulo $-55$, so we can discount ideals of norm $3$.
$(2)\equiv1\pmod{8}$, so we know $(2)$ splits completely in $K$. The ideal  I=$(2,\frac{1+\sqrt{-55}}{2})$ is a prime ideal of norm $2$, since $(2,\frac{1+\sqrt{-55}}{2})(2,\frac{1-\sqrt{-55}}{2})=(2)$. A computation shows that $I^2$ is not principal, and indeed, that $I^2\neq \bar I$. Hence, $I$ is not of order $3$. We compute either $I^3$, to give us $\bar I $, or $(I^2)^2$, to give us a principal ideal. Either way, we see that $I$ has order 4, and the class group is henceforth $\mathbb{Z}/4\mathbb{Z}$.


text:
Q: Editable only by logged in user I would like to be able to call an ajax php function to tell me if the user is permitted to edit the calendar.
I suspect that I need to call the ajax function and then set editable to true or false?
Does fullcalendar have some kind on initialisation method that is called before rendering?
Can anyone advise? Thanks.


text:
Q: Best Reference for creating web socket server in spring 4 I am trying to build a web socket server for chatting application. I made a sample java application for connecting server to client with web sockets. But i don't know how to do same in Spring framework.
Also, It would be a great help if you could also tell me how to manage multiple web-socket sessions on server end.
import java.io.IOException;
import java.util.Set;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint("/websocket")
public class WebSocketConnector {

    private static Set<Session> allSessions;

    @OnMessage
    public void onMessage(String message, Session session) throws IOException,     InterruptedException {

        // Print the client message for testing purposes
        System.out.println("Received: " + message);

    }

    @OnOpen
    public void onOpen(Session session) throws IOException {
        allSessions = session.getOpenSessions();
        session.getBasicRemote().sendText("Connection established");

    }

    @OnClose
    public void onClose() {
        System.out.println("Connection closed");
    }
}


text:
Q: Is it necessary to duplicate user credentials when using proxysql in front of a database cluster? I've set up a Percona Xtradb Cluster with 5 nodes on a network that also has a ProxySQL server. I have ProxySQL working, I can log in to the admin interface on port 6032 and administer it and I can also log in through port 6033, connecting to the cluster.
The problem (at least as I see it) is that I am only able to get through the proxy to the cluster (port 6033) by duplicating the user/pass for the cluster at the proxysql level.
I would have thought that there would be some way to have the credentials simply pass through the proxy to the cluster or at least some other way to not have to store the user/pass in two points for these connections.
Is this all exactly by design and I'm just hoping for something that doesn't exist because of good reasons like security/practices or is there some way to improve this setup to not have to tell ProxySQL about every database user I ever need to access the cluster databases?

A: in short - yes. it's simply the way ProxySQL handles queries.
Also,if security is one of your concerns you may think of password hashing on ProxySQL side.
Here's the official doc: Password management on how to configure.

A: From the Wiki:

Because ProxySQL performs routing based on traffic, when a client
  connects it cannot yet identify a destination HG, therefore ProxySQL
  needs to authenticate the client. For this reason, it needs to have
  some information related to the password of the user: enough
  information to allow the authentication.


text:
Q: ScrollView Objective C I am trying to add a scrollview on my view controller.
First I changed the Simulated size of View Controller to Freeform.
Add new scrollview and change the height to 1000
Added couple of tags.
select all these tags and embedded in a view.
I name this view as contentView.
then,
- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    [self.scrollView layoutIfNeeded];
    self.scrollView.contentSize = self.contentView.bounds.size;
}

didn't work, for sure i miss something.
Any advise?

A: you can check out my answer on this other post and get an idea how to use UIScrollView.


text:
Q: Why do I have backend in Google App Engine if I don't have backends.yaml at all When I open the admin panel of Google App Engine I see that I have running backend. I didn't intend to have one and I don't have backends.yaml file in my config.
I doubt it is because in the app.yaml I have this line manual_scaling in order to be able to make longer operatiotns:
manual_scaling:
  instances: 1
Probably I should consider using modules. But first I want to clear this issue.

A: Manual scaling only works with "B"-type instances, which used to be known as "backend instances":
https://developers.google.com/appengine/docs/python/modules/#Python_Instance_scaling_and_class


text:
Q: How to fetch data from API in Node.js to a view in React.js I tried to get data from my SQL Server Management Studio. I already made the the query inside API, so when I access those links using postman, it will retrieve data equals to the query inside those links. But when i want to show the data at page, it not comes out even though it already comes out at the console log. The error always changing, but never solved.
DbOperations Query
const config = require('./dbConfig');
const sql = require('mssql');

    async function getRoles() {
          try {
              let pool = await sql.connect(/My Configuration Database/);
              let products = await pool.request().query("SELECT [id],[division] FROM [FMLX_IME].[dbo].[ime.tbl_roles]");
              return products.recordsets;
              }
          catch(error) {
               console.log(error);
              }
          }

This is how I insert the function to API links
const express = require('express');
const cors = require('cors');
const app = express();
const bodyParser = require('bodyParser');
const Db = require('./dbOperations');
const router = express.Router();

const PORT = process.env.PORT || 3001;

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors());
app.use('/api', router);

router.use((request, response, next) => {
     console.log("============ MIDDLEWARE ============");
     next();
});

router.route('/get-roles').get((request, response) => {
    Db.getRoles().then(result => {
        response.json(result);
        console.log(result);
    });
});

This how I tried to fetch the data, already tried so many ways but nothing works. Only success to retrieved the data if using API that already online or running, not from my localhost. (Already tried using axios too)
Class ManualTest extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
           roles: [],
           isLoaded: false
        }
    }

    componentDidMount() {
        fetch('http://localhost:3001/api/get-roles')
           .then(result => console.log(result.json()))
           .then(res => res.json())
           .then(json => {
                this.setState({
                    roles: json,
                    isLoaded: true
                })
            }).catch((err) => {
                 console.log(err);
            });
    }

    render() {

      const { isLoaded, roles } = this.state;

      if(!isLoaded)
         return
Loading...

         return (

                     {roles.map(role => (

                            ID: {role.id} || ROLE: {role.role}

                      ))}

         );
    }
}

export default ManualTest


text:
Q: SQS can receive encrypted message from SNS with no specific KMS permission I am a new learner for AWS KMS (Key Management Service).
Currently I want to create an SNS that server-side encryption (SSE) is enabled and publishes message to subscribing Amazon SQS queue.
The Resource part of Cloudformation is like:
(The CMK key and SNS Arn are not shown)
Resources:
  MySNSTopic:
    Type: AWS::SNS::Topic
    Properties:
      TopicName: !Ref TopicName
      KmsMasterKeyId: (My_CMK_Key)

  MySQS:
    Type: AWS::SQS::Queue
    Properties:
      QueueName: "MySQS"

  MySQSPermissions:
    Type: AWS::SQS::QueuePolicy
    Properties:
      PolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Sid: MySQSPolicy
            Effect: Allow
            Principal: '*'
            Action:
              - sqs:SendMessage
            Resource: !GetAtt MySQS.Arn
            Condition:
              ArnEquals:
                aws:SourceArn: (My_SNS_ARN)
      Queues:
        - !Ref MySQS

  MySQSSubscription:
    Type: AWS::SNS::Subscription
    Properties:
      Protocol: sqs
      Endpoint: !GetAtt MySQS.Arn
      Region: !Ref AWS::Region
      TopicArn: (My_SNS_ARN)

As you can see only SNS topic is with SSE enabled, but SQS is just subscribing the SNS topic.
When I tried to publish message to the SNS topic. The SQS queue (MySQS) can receive message successfully but looks like its Body is not encrypted (still human-readable).
{
  "Type" : "Notification",
  "MessageId" : (id),
  "TopicArn" : (Arn),
  "Subject" : "The message from SNS topic",
  "Message" : "The message should be encrypted", // Looks like it is not encrypted?
  "Timestamp" : "....",
  "SignatureVersion" : "1",
  "Signature" : (Signature string),
  "SigningCertURL" : (Signing URL),
  "UnsubscribeURL" :  (Unscribed URL)
}

My questions are:

*

*How do I know the message from this SNS topic is encrypted?

*How the SQS queue receives the message (from SNS topic) that seems like not encrypted? The SQS queue in this case does not use the same CMK that used by the SNS topic, and also with no any KMS permission are specified.

*If I create a Lambda function to retrieve data from this SQS queue, does it require the CMK key? Or it can read the message successfully?

A: The Amazon SNS API is already served through Secure HTTP (HTTPS) and encrypts all messages in transit with Transport Layer Security (TLS).
And the KMS (SSE) used in this case is Message encryption at rest: "... The messages are stored in encrypted form across multiple Availability Zones (AZs) for durability and are decrypted just before being delivered to subscribed endpoints, such as Amazon Simple Queue Service (Amazon SQS) queues, AWS Lambda functions, and HTTP and HTTPS webhooks."
Long story short, the CMK we are using in this case is to "make all messaged are encrypted when they are in SNS", not "encrypt messages in transit".
Document: https://aws.amazon.com/blogs/compute/encrypting-messages-published-to-amazon-sns-with-aws-kms/


text:
Q: Java RMI: concurrency support I am developing a multiplayer card game with a P2P architecture, it isn't a my decision, the project has been commissioned by the professor of Distributed System course at my University.
Another constraint imposed by the professor is to use Java RMI technology to implement the communication layer between the players.
i would know if Java RMI manages concurrency "out of the box", in other words I would know if when I invoke a method on a remote object, the object is automatically "locked" and no objects can concurrently invoke the same method.
Could to declare methods as synchronized be a good solution?
Thanks

A: Calling a method on a remote object does not lock the object.
Declaring a method to be synchronized is one way to control access.  However simply declaring all of your methods on all of your remote-accessible objects to be synchronized is a bad idea.  Indeed, depending on the details of what you are doing it could create unnecessary concurrency bottlenecks and/or the risk of deadlocks.  You need to think more carefully about the behavior of the objects and the interactions.

A: Synchronizing your method is a good start. There is a performance penalty for doing this, but in your case this is perfectly fine.
Take a look at this Java RMI and synchronized methods


text:
Q: How to show that $(Re\lambda_1,\dotsb,Re\lambda_n)^T$ is majorized by $(\lambda_1(H),\dotsb,\lambda_n(H))^T$? Suppose $\lambda_1,\dotsb,\lambda_n$ are eigenvalues of $A$. And $H,K$ are hermitian such that $A=H+iK.$ Show that $(Re\lambda_1,\dotsb,Re\lambda_n)^T$ is majorized by $(\lambda_1(H),\dotsb,\lambda_n(H))^T,$ i.e. $$\max_{1\leq i_1<\dotsb <i_k\leq n }\sum_{j=1}^k \lambda_{i_j}(H)\geq \max_{1\leq i_1<\dotsb <i_k\leq n }\sum_{j=1}^k Re\lambda_{i_j}.$$ Any idea for applying Schur decomposition to prove it?

A: $A= H + iK = \frac{1}{2}\big(A+A^*\big)+\frac{1}{2}\big(A-A^*\big)$.
via congruence (i.e. using $Q^*AQ$ where $A=QRQ^*$ in Schur Triangularization) we can assume WLOG that $A$ is upper triangular.
Then
$\max_{1\leq i_1<\dotsb <i_k\leq n }\sum_{j=1}^k Re\lambda_{i_j}= \max_{1\leq i_1<\dotsb <i_k\leq n }\sum_{j=1}^k h_{i_j}$
i.e. maximal sum of k elements of the diagonal of $\frac{1}{2}\big(A+A^*\big)$
and this is well known to be majorized by the eigenvalues of $H$.  Reference e.g. one of the many proofs here:  Maximize $\mathrm{tr}(Q^TCQ)$ subject to $Q^TQ=I$


text:
Q: Arquilian fails to inject UserTransaction with multiple deployments I have this class:
@RunWith(Arquillian.class)
public class myIT {
    @Inject
    private UserTransaction utx;

    @Resource(mappedName="java:/jdbc/myDS")
    private DataSource dataSource;

    @Deployment(name="DeployOne", order = 1)
    public static Archive<?> deployOne() throws FileNotFoundException {
        //Build and return the file
    }

    // @Deployment(name="DeployTwo", order = 2)
    public static Archive<?> deployTwo() throws FileNotFoundException {
        //Build an empty file return the file
        return = ShrinkWrap.create(WebArchive.class, "deployTwo.war");
    }

    @Before
    public void setup() throws Exception {
        utx.begin();
        //Do things with utx
    }
}

As you can see, deployment 2 is commented, so my deployment works fine.
If I uncomment the @Deployment annotation, utx is not injected anymore and I get a null pointer exception.
Am I missing something? Why adding a new deployment causes my UserTransaction not to be injected anymore?

A: You have to inject the UserTransaction as a resource, since it's managed outside the CDI container.
private @Resource UserTransaction transaction;

See this Tutorial.


text:
Q: Handling infinite/large values in column for ML classification Computed a column using a formula (formula does't involve any log functions, just a group by with .sum()), but as expected this column would result in infinite/exponential values like below:
-inf
 nan
 inf
-3.000e+32
 7.3297+23 ...etc (similar data)

My doubt is how should I handle this column as I could also not avoid this column for prediction for a binary classification problem. What are the techniques to use before using this column in model classifier.
Thanks!

A: If your function computing a feature (the column) returns nan or inf I would be suspicious. Why is this the case?
In general if you have large values like yours, you can try to apply a log-transformation to scale down your values to more useful intervals.


text:
Q: Are There Any Server Options for ASP.NET Other Than IIS and Apache? Curious as to if ASP.NET is compatible with any other web servers out there (ie. node.js).

A: A quick search revealed there are a few other options:

*

*Aprelium

*Neokernal

*Casssini

*Cherokee
IIS is still probably the way to go though for asp.net. I'm not a Node expert but from my understanding Node.JS is not related to asp.net. Scott Hanselman wrote this blog post on how to get Node.JS running on Windows through IIS, I've just skimmed the article but you might find it interesting.