text:
Q: Subfigures in Margin note My codes,
\documentclass[a4paper,twoside,openright,11pt]{scrbook}
\usepackage[left=1.5cm,right=1cm,top=3cm,bottom=1.5cm,marginparwidth=5.5cm,marginparsep=1cm,outer=8cm]{geometry}

\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{lmodern}
\usepackage[fulladjust]{marginnote}
\usepackage{sidenotes}
\usepackage[svgnames]{xcolor}
\usepackage{caption}
\usepackage{subcaption}
\usepackage{tikz}
\usetikzlibrary{positioning}
\usepackage{showframe}

\captionsetup{
justification=raggedright,
labelfont={color=Maroon,bf},
font=small}

\begin{document}

\begin{figure}
  \centering
  \begin{subfigure}[t]{0.45\textwidth}
    \centering
    \includegraphics[width=\textwidth]{IMAGE}
    \caption{One Circuit}\label{fig:1a}
  \end{subfigure}
  \quad
  \begin{subfigure}[t]{0.45\textwidth}
    \centering
    \includegraphics[width=\textwidth]{IMAGE}
    \caption{Two Circuit}\label{fig:1b}
  \end{subfigure}
  \caption{What a nice circuits.}\label{fig:1}
\end{figure}

\marginpar{
\begin{center}
\includegraphics[width=\marginparwidth]{IMAGE}
\captionof{figure}{Picture One in Margin}
\end{center}}

\marginpar{
\begin{center}
\includegraphics[width=\marginparwidth]{IMAGE}
\captionof{figure}{Picture Two in Margin}
\end{center}}
\end{document}

And output,

No problem but If possible, subfigures in body, same subfigures attached in margin note. Again If possible use to my preamble.
I didn't find duplicate another question. I found like its, don't working in full my code. Does anyone know how to fix it?

A: Borrowing from egreg's answer at Using the same figure twice with no new number, here is a solution.  EDITED to match format better.
I use \repeatcaption and \repeatsubcaption to regurgitate the label based on a prior reference.
\documentclass[a4paper,twoside,openright,11pt]{scrbook}
\usepackage[left=1.5cm,right=1cm,top=3cm,bottom=1.5cm,marginparwidth=5.5cm,
  marginparsep=1cm,outer=8cm]{geometry}

\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{lmodern}
\usepackage[fulladjust]{marginnote}
\usepackage{sidenotes}
\usepackage[svgnames]{xcolor}
\usepackage{caption}
\usepackage{subcaption}
\usepackage{tikz}
\usetikzlibrary{positioning}
\usepackage{showframe}

\captionsetup{
justification=raggedright,
labelfont={color=Maroon,bf},
font=small}

\newcommand{\repeatcaption}[2]{%
  \addtocounter{figure}{-1}%
  \renewcommand{\thefigure}{\ref{#1}}%
  \captionsetup{list=no, labelformat=simple, labelsep=colon}%
  \captionof{figure}{#2}%
}

\newcommand{\repeatsubcaption}[2]{%
  \renewcommand{\thesubfigure}{\subref{#1}}%
  \captionsetup{list=no, labelformat=parens, labelsep=space}%
  \captionof{subfigure}{#2}%
}
\begin{document}
\begin{figure}
  \centering
  \begin{subfigure}[t]{0.45\textwidth}
    \centering
    \includegraphics[width=\textwidth]{example-image-A}
    \caption{One Circuit}\label{fig:1a}
  \end{subfigure}
  \quad
  \begin{subfigure}[t]{0.45\textwidth}
    \centering
    \includegraphics[width=\textwidth]{example-image-B}
    \caption{Two Circuit}\label{fig:1b}
  \end{subfigure}
  \caption{What a nice circuits.}\label{fig:1}
\end{figure}

\marginpar{
\begin{center}
\includegraphics[width=\marginparwidth]{example-image-A}
\repeatsubcaption{fig:1a}{One Circuit}
\medskip
\includegraphics[width=\marginparwidth]{example-image-B}
\repeatsubcaption{fig:1b}{Two Circuit}
\repeatcaption{fig:1}{What a nice circuits.}
\end{center}}

\end{document}

A: I had such a solution. Do you want evaluate? How is it?  Or is there a simple way?
\documentclass[a4paper,twoside,openright,11pt]{scrbook}
\usepackage[left=1.5cm,right=1cm,top=3cm,bottom=1.5cm,marginparwidth=5.5cm,marginparsep=1cm,outer=8cm]{geometry}

\usepackage[utf8]{inputenc}
\usepackage[svgnames]{xcolor}

\usepackage{caption}
\usepackage{tikz}
\usetikzlibrary{positioning}
\usepackage{calc}
\usepackage{showframe}

\captionsetup{
justification=raggedright,
labelfont={color=Maroon,bf},
font=small,textfont=it,
indention=0pt,format=plain}

\newcommand{\margintwosubfigures}[5]{
\marginpar{
\includegraphics[width=\marginparwidth]{#1}
\begin{center}\raggedright\small\bfseries\textcolor{Maroon}{(a)} \normalfont\small\itshape {#2}\end{center}
    \includegraphics[width=\marginparwidth]{#3}
    \begin{center}\raggedright\small\bfseries\textcolor{Maroon}{(b)} \normalfont\small\itshape {#4}\end{center}
\captionof{figure}{#5}
}}

\begin{document}

\begin{figure}[h]
\centering
\includegraphics[keepaspectratio=false,width=6cm]{example-image-a}
\caption{I am a figure}
\end{figure}

\margintwosubfigures{example-image-a}{First Subfigure}{example-image-a}{Second Subfigure}{Two Subfigures}

\end{document}


text:
Q: Calling a function in an imported package - what am I doing wrong? I have this project structure
Bot/
-- bot.py
FlapPyBird/
-- flappy.py
run.py

bot.py:
import pygame
from pygame.locals import *

def run(upperPipes, lowerPipes, playerInfo):
    pass

flappy.py:
from itertools import cycle
import random
import sys

import pygame
from pygame.locals import *

def doStuff(bot)
    some stuff

and run.py:
import FlapPyBird as game
import Bot as bot

def main():
    game.doStuff(bot)

if __name__ == '__main__':
    main()

And I'm getting this error running 'python run.py'
Traceback (most recent call last):
File "C:/Users/Kyle/IdeaProjects/flappy_bird_bot/run.py", line 8, in <module>
main()
File "C:/Users/Kyle/IdeaProjects/flappy_bird_bot/run.py", line 5, in main
game.doStuff(Bot)

AttributeError: module 'FlapPyBird' has no attribute 'doStuff'

What am I not understanding? How can I abstract away my two packages so I can call them from my root directory?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Iterating over an array within another array in Javascript and showing items in UL I'm in the process of creating a quiz app using Javascript and can't work out how to get the multiple choice answers to show in the ul. They're all currently appearing in one li and I need them split across each one. I'll also be including an image with each li so have set up the HTML and CSS to ensure these are displayed correctly.
The HTML contains the text mainly as a placeholder, and I've only copied in one of the questions in the allQuestions array in the JS code.

var i = 0;
var j =0;
var allQuestions = [ {
    questionNumber: 1,
    question: 'Who is the most successful manager of Manchester United?',
    options: ['Sir Matt Busby', 'Louis Van Gaal', 'Ryan Giggs', 'Sir Alex Ferguson'],
    answer: 3,
    info: 'Sir Alex Ferguson was the manager of Manchester United for 26 years between 1986 and 2013. During that time he amassed 38 trophies including 13 Premier League titles, five FA Cups and two UEFA Champions League titles. His win rate was nearly 60 per cent, the highest of any manager in the history of the club.'
}];

//start quiz and generate first question//
$('#go').on('click', function() {
    $('.start').hide();
    generateQuestions();

});

function generateQuestions() {
    $('.question-container').fadeIn(1000);
    $('.submit').fadeIn(1000);
    var firstQuestion = allQuestions[i].question;
    $('.question').html(firstQuestion);
    console.log(firstQuestion);
    var firstNumber = allQuestions[i].questionNumber;
    $('.question-number').html("Question" + " " + firstNumber);
    console.log(firstNumber);
    /*var firstOptions = allQuestions[i].options;
      $('li').html(firstOptions);
      console.log(firstOptions);*/
};

//submit answer and show answer modal//
$('.submit').on('click', function() {
    $('.answer-overlay').show();
    submitAnswer();
});

function submitAnswer() {
    $('.answer-overlay').show();
    var currentAnswer = allQuestions[i].answer;
    $('.answer').html(currentAnswer);
    console.log(currentAnswer);
    var currentInfo = allQuestions[i].info;
    $('.answer-info').html(currentInfo);
    console.log(currentInfo);
};

//hide answer modal and show next question//
$('.next-question').on('click', function() {
    nextQuestion();
});

function nextQuestion() {
    $('.answer-overlay').fadeOut(1000);
    if(i>allQuestions.length -1) {
        i=0
    }
    generateQuestions(i);
    i++

    var nextQuestion = allQuestions[i].question;
    $('.question').html(nextQuestion);
    console.log(nextQuestion);
    var nextNumber = allQuestions[i].questionNumber;
    $('.question-number').html("Question" + " " + nextNumber);
    console.log(nextNumber);
    /*var nextOptions = allQuestions[i].options;
      $('li').html(nextOptions);
      console.log(nextOptions);*/
};

Question 1

Who is the most successful manager of Manchester United?

Sir Matt Busby

Louis Van Gaal

Ryan Giggs

Sir Alex Ferguson

A: allQuestions[i].options.forEach(function(answer,index){
        $("#pic"+(index +1)).html(answer);
    console.log(answer);
});

Just .forEach through each of the answers individually.
Here's a JSFiddle

A: Your code seems to work for me. (I added a runnable snippet into OP for you to check)

Edit: Ok, I see that was the placeholder text being shown.
$('li').html(firstOptions); is your problem. You should instead be looping through firstOptions (as it is an array) and setting each li's content individually. The same applies for nextOptions.
Something like below will work.

var i = 0;
var j =0;
var allQuestions = [ {
    questionNumber: 1,
    question: 'Who is the most successful manager of Manchester United?',
    options: ['Sir Matt Busby', 'Louis Van Gaal', 'Ryan Giggs', 'Sir Alex Ferguson'],
    answer: 3,
    info: 'Sir Alex Ferguson was the manager of Manchester United for 26 years between 1986 and 2013. During that time he amassed 38 trophies including 13 Premier League titles, five FA Cups and two UEFA Champions League titles. His win rate was nearly 60 per cent, the highest of any manager in the history of the club.'
}];

//start quiz and generate first question//
$('#go').on('click', function() {
    $('.start').hide();
    generateQuestions();

});

function generateQuestions() {
    $('.question-container').fadeIn(1000);
    $('.submit').fadeIn(1000);
    var firstQuestion = allQuestions[i].question;
    $('.question').html(firstQuestion);
    console.log(firstQuestion);
    var firstNumber = allQuestions[i].questionNumber;
    $('.question-number').html("Question" + " " + firstNumber);
    console.log(firstNumber);
    var firstOptions = allQuestions[i].options;
    var k;
    for (k = 0; k < 4; k++)
      $('#pic'+(k+1)).html(firstOptions[k]);
    console.log(firstOptions);
};

//submit answer and show answer modal//
$('.submit').on('click', function() {
    $('.answer-overlay').show();
    submitAnswer();
});

function submitAnswer() {
    $('.answer-overlay').show();
    var currentAnswer = allQuestions[i].answer;
    $('.answer').html(currentAnswer);
    console.log(currentAnswer);
    var currentInfo = allQuestions[i].info;
    $('.answer-info').html(currentInfo);
    console.log(currentInfo);
};

//hide answer modal and show next question//
$('.next-question').on('click', function() {
    nextQuestion();
});

function nextQuestion() {
    $('.answer-overlay').fadeOut(1000);
    if(i>allQuestions.length -1) {
        i=0
    }
    generateQuestions(i);
    i++

    var nextQuestion = allQuestions[i].question;
    $('.question').html(nextQuestion);
    console.log(nextQuestion);
    var nextNumber = allQuestions[i].questionNumber;
    $('.question-number').html("Question" + " " + nextNumber);
    console.log(nextNumber);
    var nextOptions = allQuestions[i].options;
    var k;
    for (k = 0; k < 4; k++)
      $('#pic'+(k+1)).html(nextOptions[k]);
};

generateQuestions(); // added for snippet


text:
Q: After cloning a repository using ssh keys, What is the meaning of Permanently added 'gitlab.com' (ED25519) to the list of known hosts After I have cloned an empty repository to my local system, I just want to clarify each of these 3 lines what is their meaning.
Warning: Permanently added 'gitlab.com' (ED25519) to the list of known hosts.
client_global_hostkeys_private_confirm: server gave bad signature for RSA key 0
warning: You appear to have cloned an empty repository.

I am just a curious person

A: That is an SSH thing.  It asked you if the remote's key is OK the first time it saw it, and then remembers that.


text:
Q: Need to paas JSON array with POST body using collection runner as array has 5000 + indexes I have a POST API and need to pass the request body as variable as the request body JSON array has 5000 + indexes.
Sample Request Body
[
   {
      "code":"1",
      "Center":"1",
      "name":"CC_name_00111",
      "description":"",
      "erpId":"",

   },
   {
      "code":"2",
      "Center":"2",
      "name":"CC_name_0011",
      "description":"",
      "erpId":"",

   }
]

The API should run only once with all the complete request body. Need help on how to achieve this.


text:
Q: Set Similarity measure with known item similarities and abundances I'm looking for a similarity measure (like the Jaccard Index) but I want to use known similarities between objects within the set, and weigh the connections by the item abundances. These known similarities are scores between 0 and 1, 1 indicating an exact match.
For example, consider two sets:
SET1 {A,B,C} and SET2 {A',B',C'}
I know that
{A,A'}, {B,B'}, {C,C'} each have an item similarity of 0.9. Hence, I would expect the similarity of SET1 and SET2 to be relatively high.
Another example would be: consider two sets SET1 {A,B,C} and SET2 {A,B',C',D,E,F,.....,Z}. Although the matches between the first three items are higher than in the first example, this score should likely be lower because of the size difference (as in Jaccard).
One more issue here is how to use abundances as weights, but I've got no idea as how to solve this.
In general, I need a normalized set similarity measure that takes into account this item similarity and abundancy.

A: Correct me if I'm wrong but I guess you need clustering error as similarity measure. It is the proportion of points which are clustered differently in A' and A after an optimal matching of clusters.  In other words, it is the
scaled sum of the non-diagonal elements of the confusion matrix, minimized
over all possible permutations of rows and columns. It uses the Hungarian algorithm to avoid high computational cost and it penalizes different number of elements in sets.


text:
Q: Cannot use SQLite WAL mode I'm using c# with NHibernate on SQLite.
System.Data.SQLite version 1.0.88
SQLite version 3.7.17
I've recently found out about SQLite WAL mode and it looks like just what I need.
The problem is that I can't seem to get it to work.
The documentation simply states:

To convert to WAL mode, use the following pragma:
PRAGMA journal_mode=WAL;
The journal_mode pragma returns a string which is
the new journal mode. On success, the pragma will return the string
"wal". If the conversion to WAL could not be completed (for example,
if the VFS does not support the necessary shared-memory primitives)
then the journaling mode will be unchanged and the string returned
from the primitive will be the prior journaling mode (for example
"delete").

I've tried this both within code:
ISQLQuery query = session.CreateSQLQuery("PRAGMA journal_mode=WAL;");
object result = query.UniqueResult();

and within the SQLiteman management application.
In each case, I get a return value of 'delete'. i.e. The database has failed to enter WAL mode.
Trouble is, I have no idea why.. The only possibility I can see in the documentation is your file system not supporting shared-memory primatives, but I'm on Win 7 so that's not an issue.
Any ideas how I can enable WAL mode or figure out why it's not working?

A: Try set the pragma on your connection builder.
SQLiteConnectionStringBuilder connBuilder = new SQLiteConnectionStringBuilder();
connBuilder.JournalMode = SQLiteJournalModeEnum.Wal;

Check out this:
System.data.sqlite - Activating WAL Journal Mode

A: Found the answer.
It seems that the journal mode needs to be set when the connection is first created. (I haven't found any documentation stating that for definite but it's the only way I can get it to work)
I now specify the journal mode when creating the connection string:
SQLiteConnectionStringBuilder connectionStringBuilder = new SQLiteConnectionStringBuilder();
connectionStringBuilder.DataSource = dbFile;
connectionStringBuilder.JournalMode = SQLiteJournalModeEnum.Wal;

My Fluent NHbiernate config then uses this:
SQLiteConfiguration.Standard.ConnectionString(connectionStringBuilder.ToString())

A: SQLite doesnt actually change the journaling mode until a write (or read?) has been issued to the database. Im not familiar with the C# interface, but I've seen it with the Objective C interface.


text:
Q: What python packages are installed by default on Ubuntu Imagine having to write python code to be submitted to a remote Ubuntu box to be run there (you do not get to touch the terminal, you do not get to install anything or run apt to query what's installed). How would you go about figuring out what python packages are likely available on that machine by default (i.e. what does a complete Ubuntu install include, not what can I download and install later). I'm having the hardest time finding something like a "list of all packages installed by default" or some such thing. Is there such a thing? Or do I have to download an image and actually install it just to find out what's in the box?

A: Go to http://releases.ubuntu.com/ and select the specific version of Ubuntu. Then download the ".manifest" file (there can be more than one, e.g. desktop and server).  For example here is one recent file:
http://releases.ubuntu.com/20.04.1/ubuntu-20.04.1-live-server-amd64.manifest
Grep that for "python" and you'll see most of the relevant parts.  Some selected highlights from the above link:
python3 3.8.2-0ubuntu2
python3-automat 0.8.0-1ubuntu1
python3-blinker 1.4+dfsg1-0.3ubuntu1
python3-colorama    0.4.3-1build1
python3-configobj   5.0.6-4
python3-dbus    1.2.16-1build1
python3-idna    2.8-1
python3-jinja2  2.10.1-2
python3-jsonschema  3.2.0-0ubuntu2
python3-more-itertools  4.2.0-1build1
python3-oauthlib    3.1.0-1ubuntu2
python3-requests    2.22.0-2ubuntu1
python3-simplejson  3.16.0-2ubuntu2
python3-six 1.14.0-2
python3-twisted 18.9.0-11
python3-urllib3 1.25.8-2
python3-yaml    5.3.1-1
python3-zope.interface  4.7.1-1


text:
Q: Typedefs and casting typedef seems to be C++ specific (perhaps in some other languages). I find it hides the real data type of the value, thus is confusing someone new to the project. Perhaps it is useful to shorten the typing sometimes. When do you recommend the use of typedef?
I also notice I can't pass a typedef-ed value to a function that accepts the underlying type?
something like:
typedef string VAL;
VAL s = "x";
func(string x); // if I try to pass `s`, I get something like no instance of function template match argument list

A: typedef is a C and C++ language label used to create a new type from an existing type.  The best place is to use it with the C programming language with structs such as the following example or to use it to create a new, more abstract type from an existing primitive type (short, long, etc.).
typedef struct {
    int iValue;
    int jValue;
} MyValues;
// declare a variable with this struct
MyValues aMyValuesStruct;

Before typedef was introduced into C, in order to use the above struct as a type you would have had to do something like the following:
struct _MyValuesStruct {
    int iValue;
    int jValue;
};
// declare a variable with this struct
struct _MyValuesStruct aMyValuesStruct;

In C++ structs and classes are similar constructs which create new types so the typedef is not as useful for those types of variables.  However if you are using a built in primitive type to represent some other, more abstract type then the typedef statement helps you to specify the type in a more abstract way.
This use of typedef makes it a lot easier to specify a label for a type so that when a programmer is reading the source code they can understand what a particular variable represents.  For instance if you have a color value variable that fits in an unsigned short if you use a typedef to create a new type for color value and use it consistently then it is much easier to recognize that a variable contains a color value and not some other kind of an unsigned short.
What typedef also allows is that it makes it much easier to find all of the places in the source where a particular abstract type is being used and it makes it easier to change the underlying type.  For instance if your color value type starts off as a byte so you use typedef to create an abstract type like typedef unsigned char ColorValue; and then later you find that you need to change it from an unsigned char to an unsigned short, there would be a single place to make the change and if your use of the type was reasonably strict, that would be the only place you need to make a change.

A:
Perhaps it is useful to shorten the typing sometimes. When do you recommend the use of typedef?

One good usecase is when you want to be able to remap a type without editing your codebase:
typedef int32_t pixel_t;

Another one is where you want the type to be more explicit so that the usage of the code becomes clearer:
typedef int distance_t;

typedef int angular_momentum_t;

A: Your question is answered in that other question.
typedefs are useful (in C as well as C++, and perhaps Objective-C too?) to abstract implementation details. It is good practice to hide the type to parts of a program which don't need to know how the type is implemented, so as to avoid polluting that code with problems unrelated to its function, and make it easier to change the type implementation without having to change that code.
Someone new to the project might find it actually easier to cope with the code if unnecessary details are hidden where possible.
As for your problem, func(string x); is a function prototype declaration, not a function call.

A: typedef is used to hide the underlying type representing the data, in some circumstances.
For example, the Standard leaves it unspecified what the typical size of a short int, int or long int are, which might be an issue. On the other hand, the implementation should (now) provide int8_t, int16_t, int32_t and int64_t (and possibly int128_t depending on the platform) so you can have integers with a known range of values at your disposition.
But what is int32_t ? Well, it's a signed integer, with a width of 32 bits. It could be any of char, short int, int, long int or long long int in theory... and which it is should not matter: it is an implementation detail.
Therefore, at some point in your standard library headers you'll see:
typedef int int32_t; // most likely representation

and this definition is conditioned on the platform.
In your code, using int32_t let you leave behind those dreadful platform peculiarities and concentrate on the business at hand: your business.


text:
Q: Arduino to PC secure bluetooth connection(cryptography) I'm using an Arduino Uno to build a smoke detection system, which works. Since I have to do an IoT project, I have to establish a secure connection with a device (I thought with my smartphone, or my PC), and I'm using a Bluetooth module HC-05 to do it. The idea is:

*

*Send the smoke sensor data to Arduino IDE, encrypt them and display the encrypted data to the serial (and it works)

*Connect Arduino to my smartphone using HC-05 and the app "Makerslab BT Demo" (already done)

*Decrypt the value of the sensor when I press "1" on the app and display it;
Decrypt the value of the sensor when there's danger and display a "danger message".
(that's what I have to do now).
That's my code on Arduino IDE:
    #include <AES.h>
    #include <AESLib.h>
    #include <AES_config.h>
    #include <xbase64.h>
    #include <SoftwareSerial.h>
    SoftwareSerial BT(1,0);

    #define VCC2 5
    int smokeA0 = A0;
    int buzzer = 11;
    AES aes;
    byte cipher[400];
    char b64[400];
    float sensorValue;
    //char a;

    void do_encrypt(String msg, String key_str, String iv_str){

    byte iv[16];
    memcpy(iv,(byte*)iv_str.c_str(),16);
    int blen=base64_encode(b64,(char*)msg.c_str(),msg.length());
    aes.calc_size_n_pad(blen);
    int len=aes.get_size(); //zero padding
    byte plain_p[len];
    for(int i=0;i<blen;++i) plain_p[i]=b64[i];
    for(int i=blen;i<len;++i) plain_p[i]='\0';

    // l'AES-128-CBC encryption
    int blocks = len/16;
    aes.set_key((byte *)key_str.c_str(), 16);
    aes.cbc_encrypt(plain_p, cipher, blocks, iv);

    // use base64 encoder to encode the encrypted data:
    base64_encode(b64,(char *)cipher,len);
    Serial.println(String((char *)b64));
    }

    void setup() {

    pinMode(buzzer, OUTPUT);
    pinMode(smokeA0, INPUT);
    pinMode(VCC2, OUTPUT);
    digitalWrite(VCC2, HIGH);

    BT.begin(9600);
    BT.println(F("Hi! Press "1" to know the sensor value."));
    Serial.begin(115200);

    Serial.println(F("gas sensor is warming up!"));
    delay(2000); //allow the sensor to warm up
    noTone(buzzer);
    }

    void loop() {

    String key_str="aaaaaaaaaaaaaaaa"; //16 bytes
    String iv_str="aaaaaaaaaaaaaaaa"; //16 bytes
    sensorValue = analogRead(smokeA0);
    String msg = String(sensorValue, 3);
    do_encrypt(msg,key_str,iv_str);

    /* if(BT.available()){
     a=(BT.read());
     if(a=='1'){
       Serial.print(F("Air quality: "));
     }
    }*/
    if(sensorValue > 300){

    Serial.print(F(" | Danger!"));
    BT.print(F(" | Danger!"));
    tone(buzzer,1000,2000);
    }
    else {
    noTone(buzzer);
    }
    Serial.println(F(""));
    delay(2000);
    }

I'm not sure to use the right security protocol (AES), but encryption works. How I can decrypt data?


text:
Q: Подскажите пожалуйста, exe`шник после сборки через Сmake и mingw32-make не запускается У меня установлен Cmake и MinGW. Оба находятся в переменных средах. Хочу собрать проект. Использую команду cmake .. -G "MinGW Makefiles", после этого запускаю команду mingw32-make. Все собирается, экзешник появляется, но не запускается. Ошибка: Точка входа в процедуру _ZdlPvj не найдена в библиотеке DLL.

CMakeLists.txt:
cmake_minimum_required(VERSION 3.0)

set(CMAKE_BUILD_TYPE Release)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++14 -Wall")

project(Packman)

add_executable(main main.cpp Constants.h Game.h Ghost.h ICharacter.h Packman.h
Pellet.h setConsoleAtributes.h Game.cpp Ghost.cpp Pellet.cpp Packman.cpp
SetConsoleAtributes.cpp)

Запускаю через g++ командой: g++ -o name.exe -std=c++14 -static-libgcc -static-libstdc++ main.cpp Constants.h Game.h Ghost.h ICharacter.h Packman.h Pellet.h setConsoleAtributes.h Game.cpp Ghost.cpp Pellet.cpp Packman.cpp SetConsoleAtributes.cpp и все собирается. Но через Cmake не получается. Подскажите, в чем может быть проблема? Думаю, что в статической линковке, но я не уверен. Если да, то как правильно ее настроить через Cmake? Спасибо, буду рад любой помощи.

A: Ошибка состоит в том, что программа линковалась динамически и искала необходимые ей dll-ки, которые она не смогла найти. Для того, чтобы слинковать статически, нужно в CMakeLists.txt добавить set(CMAKE_EXE_LINKER_FLAGS "-static-libgcc -static-libstdc++). После этого будет запускаться.


text:
Q: How to integrate JSP with SOLR? I have created a simple JSP page that consist of textbox and search button. So when user types in something, it should call SOLR to query the data and return results back to the JSP page.
I had searched through the net for days.
Looked through the SolrJava guide, but I don't understand what it means by handler and the SolrJ code, my solr root folder does not have any "org" folder (I download solr-4.7.0 that starts off with "contrib", "dist", "docs", "example", "licenses" and some text files).
Could anyone enlighten me, how do you use JSP to call SOLR? Any step by step explanation or link will be grateful.

A: solr can be called via a simple HTTP-GET Request. You can use that from the shell via curl or use a similiar object in java. If you go to the solr-console, that can be found here:
YOUR-URL:8983/solr/ you can query the machine. The URL, that you need to call from your JSP is shown
above the field, where the answers are shown.


text:
Q: JPA Unit testing - Query returning more entities than were ever persisted I have written a bunch of entities. I am trying to test them now. I was having problems with an entity very similar to this, but all of a sudden the problem went away when I cleaned the build. Then I started writing a similar test for SetMap, and then..... same problem. I am 99.9999% sure I am only perisisting 100 SetMaps. however, my test says there are 101 with the query in the code below.

*

*I feel like these tests suck. Can someone give me some pointers on unit testing Entity classes? what exactly should I be testing for? merely existing after I persist them?

*why, why, why are there 101 SetMaps returned in my test method below. How... why... =-[

*I get this error everytime I compile:
89  persistence-test  WARN   [main] openjpa.Runtime - The persistence unit "persistence-test" was found multiple times in the following resources "[file:/home/matt/Code/vox/vox-lib/vox-lib-common/vox-entity/target/classes/META-INF/persistence.xml, file:/home/matt/Code/vox/vox-lib/vox-lib-common/vox-entity/src/main/resources/META-INF/persistence.xml]", but persistence unit names should be unique. The first persistence unit matching the provided name in "file:/home/matt/Code/vox/vox-lib/vox-lib-common/vox-entity/target/classes/META-INF/persistence.xml" is being used.
202  persistence-test  INFO   [main] openjpa.Runtime - Starting OpenJPA 2.1.1
448  persistence-test  INFO   [main] openjpa.jdbc.JDBC - Using dictionary class "org.apache.openjpa.jdbc.sql.DerbyDictionary".
there is definitely only one persistence.xml in my src/main/resources/META-INF folder.
I am using maven. Is it possible maven is copying something somewhere?
public class SetMapTest {

    private static EntityManagerFactory emf;
    private static EntityManager em;
    private static EntityTransaction tx;

    @BeforeClass
    public static void initEntityManager() throws Exception {
        emf = Persistence.createEntityManagerFactory("persistence-test");
        em = emf.createEntityManager();
    }

    @AfterClass
    public static void closeEntityManager() throws SQLException {
        em.close();
        emf.close();
    }

    @Before
    public void initTransaction() {
        tx = em.getTransaction();
    }

    @Test
    public void testSomeMethod() {

        // check that nothing is there
        String s = "SELECT x FROM SetMap x";
        Query q = em.createQuery(s);
        List<SetMap> qr = q.getResultList();
        assertEquals(0, qr.size());

        int count = 100;
        // util method that returns setMaps where setMap.title = 'title:i'
        // where 0 <= i < count
        ArrayList<SetMap> setMaps = TestUtil.getNumberedSetMapList(count);
        assertEquals(setMaps.size(), count);

        VoxUser author = TestUtil.getNumberedVoxUser(0);
        SetPatternMap setPatternMap = TestUtil.getNumberedSetPatternMap(0);
        setPatternMap.setAuthor(author);
        author.addSetPatternMap(setPatternMap);

        tx.begin();
        em.persist(author);
        em.persist(setPatternMap);

        Iterator<SetMap> iter = setMaps.iterator();
        while(iter.hasNext()){

            SetMap setMap = iter.next();
            em.persist(setMap);
            setMap.setAuthor(author);
            author.addSetMap(setMap);
            setMap.setSetPatternMap(setPatternMap);
            setPatternMap.addSetMap(setMap);

        }
        tx.commit();

        String qString = "SELECT x FROM SetMap x";
        q = em.createQuery(qString);
        qr = q.getResultList();
        assertEquals(count, qr.size());  // this is the method that fails
        // it claims there are 101 SetMaps in the P.C.

        for (int i = 0; i < 1; i++) {
            String qt = "SELECT x FROM SetMap x WHERE x.title = 'title:" + i + "'";
            q = em.createQuery(qt);
            qr = q.getResultList();
            assertEquals(1, qr.size());
            // i played around with this a little bit. It seems there are two SetMaps
            // whose titles are "title:0" I can't figure out how that is....
        }
    }
}

some of my util methods:
public static PhraseMap getNumberedPhraseMap(int pos){
        PhraseMap phraseMap = new PhraseMap();
        phraseMap.setTitle("title:" + pos);
        return phraseMap;
 }

public static ArrayList<PhraseMap> getNumberedPhraseMapList(int count){
        ArrayList<PhraseMap> phraseMaps = new ArrayList<PhraseMap>();
        for(int i = 0; i < count; i++){
            PhraseMap phraseMap = getNumberedPhraseMap(i);
            phraseMaps.add(phraseMap);
        }
        return phraseMaps;
}

help please!

A:
there is definitely only one persistence.xml in my
  src/main/resources/META-INF folder

Who said there wasn't ? Maven says there is one in
/home/matt/Code/vox/vox-lib/vox-lib-common/vox-entity/target/classes/META-INF/persistence.xml
and one in
/home/matt/Code/vox/vox-lib/vox-lib-common/vox-entity/src/main/resources/META-INF/persistence.xml
and both of these are in the CLASSPATH at runtime (you are not compiling at that point, maybe "compile" was one of the goals invoked but this is not in that step).
So fix your pom.xml to not copy things around when Maven is doing some things for you. That would (should) then remove the error message


text:
Q: Not allowed to navigate top frame to data URL: data:image/png;base64, error in google charts I want to create google chart into png but it is not working in chrome. Please provide me solution for this. I don't understand what is wrong with this code because this code is working properly in Firefox. Here is my code-
google.charts.load("current", {packages:['corechart']});
    google.charts.setOnLoadCallback(drawChart);
    arrayData = [
        ["Element", "Percent", { role: "style" } ],
        /*["Gross Margin", 5.94, "#00aeef"],
        ["Operating Margin", 10.49, "#00aeef"],
        ["Net Profit", 19.30, "#00aeef"],
        ["Before Interest and Tax Margin (EBIT)", 21.45, "color: #00aeef"]*/
      ]
    function drawChart() {
    //console.log(arrayData);

      var data = google.visualization.arrayToDataTable(arrayData);
      var view = new google.visualization.DataView(data);
      view.setColumns([0, 1,
                       {
                        calc: "stringify",
                         sourceColumn: 1,
                         type: "string",
                         role: "annotation"
                       },
                       2]);
      var options = {
        title: "Profitability Indicators(%)",
        width: 555,
        height: 400,
        bar: {groupWidth: "95%"},
        legend: { position: "none" },
         vAxis: {
            baselineColor:'Black',
            textPosition: 'none',
            gridlines: {
                color: 'transparent'
            }
        }
      };
      var chart = new google.visualization.ColumnChart(document.getElementById("columnchart_values"));
      chart.draw(view, options);

      document.getElementById('columnchart_values').outerHTML = 'Printable version';
  }


text:
Q: Capturing Crash logs I am writing a custom UncaughtExceptionHandler to end the app gracefully. For collecting crash logs, I am using Crashlytics. The objective is to

*

*gather the crash logs in the custom Uncaughtexception handler.

*Send the crash logs to Crashlytics server.

*Restart the app without showing "Force Close" dialog.
To achieve that I have written the following code which seems to catch the UncaughtExceptions but it's not sending the off to the Crashlytics server.
public class MyApplication extends Application{
Thread.UncaughtExceptionHandler mUEHandler;
Thread.UncaughtExceptionHandler mDefaultUEHandler;

@Override
public void onCreate() {
    super.onCreate();

    Fabric.with(this, new Crashlytics());

    mDefaultUEHandler = Thread.getDefaultUncaughtExceptionHandler();
    mUEHandler = new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread t, Throwable e) {
            reEmergeFromCrash();
            Crashlytics.logException(e);
        }
    };

    Thread.setDefaultUncaughtExceptionHandler(mUEHandler);

    throw new RuntimeException("hello");
}
}

What am doing wrong? How can I send the caught crash logs to Crashlytics.

A: Figured it out. Crashlytics.logException() does record your exceptions that you have caught, however to put less strain on the app's resources, Fabric has designed Crashlytics to send the recorded exceptions off to the server the next time you open the app.


text:
Q: SwiftUI TextField cannot be cleaned in onCommit functions I am new to SwiftUI from UIKit and I have a question regarding the behavior of the TextField.
struct ContentView: View {
    @State private var text = ""
    @State private var words: [String] = []

    var body: some View {
        Form {
            Section {
                TextField("Input", text: $text) {
                    words.insert(text, at: 0)
                    text = ""
                }
            }

            Section {
                Button("Clear") {
                    text = ""
                }
            }

            Section {
                ForEach(words, id: \.self) { word in
                    Text(word)
                }
            }
        }
    }
}

The behavior I would like to do is to clear the text and add it to a list. After the input the text field will be cleared. The problem now is that text = "" is called but it didn't clean up the field. However, by having a separate button below it works correctly.
For the context, I need to set the minimum deployment version to iOS14 and I am using Xcode 14.0.1.

I have tried to move it to a function but didn't help either.

A: in Clear Button before text = "" just append in the array
struct ContentView: View {
    @State private var text = ""
    @State private var words: [String] = []

    var body: some View {
        Form {
            Section {
                TextField("Input", text: $text) {
                    words.insert(text, at: 0)
                    text = ""
                }
            }

            Section {
                Button("Clear") {
                    words.append(text) // <-- here append first and then clear.
                    text = ""
                }
            }

            Section {
                ForEach(words, id: \.self) { word in
                    Text(word)
                }
            }
        }
    }
}

A: For iOS 14, you can achieve it by using UIViewRepresentable of UITextField and Coordinator class to manage textfield delegate.
Here is the working code for the same.
struct TextFieldView: View {

   @State private var text = ""
   @State private var words: [String] = []

   var body: some View {
        Form {
            Section {
                //Use here UIViewRepresentable class of TextField
                CustomTextFieldView(inputText: $text, arrWords: $words, placeHolderText: "Input Text")
            }

            Section {
                ForEach(words, id: \.self) { word in
                    Text(word)
                }
            }
        }
    }
}

struct CustomTextFieldView: UIViewRepresentable {

   @Binding var inputText: String
   @Binding var arrWords: [String]

   var placeHolderText: String

   func makeUIView(context: Context) -> UITextField {
       let textView = UITextField()
       textView.placeholder = placeHolderText
       textView.delegate = context.coordinator
       textView.autocapitalizationType = .sentences

       return textView
   }

   func updateUIView(_ uiView: UITextField, context: Context) {
       uiView.text = inputText
   }

   func makeCoordinator() -> Coordinator {
       Coordinator($inputText, textArr: $arrWords)
   }

   class Coordinator: NSObject, UITextFieldDelegate {
      var text: Binding<String>
      var arrText: Binding<[String]>

      init(_ text: Binding<String>, textArr : Binding<[String]>) {
         self.text = text
         self.arrText = textArr
      }

      func textFieldShouldReturn(_ textField: UITextField) -> Bool {
         arrText.wrappedValue.append(textField.text!)
         textField.text = ""
         return true
      }
   }
}

In iOS 15 and above versions, you can manage it by using the onCommit method of TextField
TextField("Input", text: $text).onSubmit {
    words.insert(text, at: 0)
    text = ""
}


text:
Q: AngularJS data displayed only after reload My data comes from a JSON (link to be seen)
I can see in my logs that data are loaded
I can't display value in my template (need to reload browser to be displayed)
As can be seen bottom my template is very simple selectedCategories.name in the title and events values
First is displayed after reloaded page, second never.
Thanks for your help
Factory :
.factory('selectedCategoriesService', function($http, $stateParams) {
        var selectedCategories = [];

        return {
        getselectedCategories: function(){
            return $http.get('http://www.myapi.com&data=categorie', { params: { cat: $stateParams.id } }).then(function(response){
                selectedCategories = response.data;
                delete selectedCategories.api;
                return response.data;
            });
        },
        getselectedCategorie: function(selectedCategorieId){
            for(i=0;i<selectedCategories.length;i++){
                if(selectedCategories[i].id == selectedCategorieId){
                    return selectedCategories[i];
                }
            }
        }
    }
})

Controller :
.controller('CategoriesListDetailCtrl',function($scope, $stateParams, selectedCategoriesService, $ionicModal){
  selectedCategoriesService.getselectedCategories().then(function(selectedCategories){
    $scope.selectedCategories = selectedCategories[0];
    console.log("Categorie = " + JSON.stringify(selectedCategories[0]));
    })
})

Template :
<ion-pane>

  <ion-view view-title="{{selectedCategories.name}}">

    <ion-content class="has-header">

        <ion-item class="item-thumbnail-left" collection-repeat="event in events | DateDivider" divider-collection-repeat>

           <h2>{{event.title}}</h2>

        </ion-item>

    </ion-content>

  </ion-view>

</ion-pane>

A: This could be a digest cycle issue, You may need to use $scope.$apply()
.controller('CategoriesListDetailCtrl',function($scope, $stateParams, selectedCategoriesService, $ionicModal){
  selectedCategoriesService.getselectedCategories().then(function(selectedCategories){
    $scope.selectedCategories = selectedCategories[0];
    $scope.$apply()
    console.log("Categorie = " + JSON.stringify(selectedCategories[0]));
    })
})

A: If the title doesn't display it's because in my template i use :
<ion-view title="{{content.title}}">
    ....

in spite of :
<ion-view>
    <ion-nav-title>{{content.title}}</ion-nav-title>
    ...

Thanks to @Dunc


text:
Q: Media buttons on keyboard with spotify I've added spotify preview as my defualt music program, by doing this.

As doug suggested, simply add this line to your >~/.local/share/applications/mimeapps.list file in two places, like so:
[Default Applications]
  ...
  audio/x-vorbis+ogg=spotify.desktop
[Added Associations]
  ...
  audio/x-vorbis+ogg=spotify.desktop;

But the media buttons doesnt seem to wanna work. Is there any easy known way to fix this without binding special keys etc perhaps?

A: This is a known issue with the Spotify Linux client. It's something that the company is aware of, but in the meantime you can use the Spotify Gnome Integration software to get the media keys working.
Edit: Hooray, we added this feature in client version 0.9.4! It should now work, if it doesn't then please post a message on the community forums.

A: The keyboard's media keys (means the "XF86Audio*" keys, usually Fn + Arrows) work in Spotify out of the box now – but depending on your desktop environment and configuration, maybe only if Spotify has the keyboard focus. Sometimes, a solution is to make Spotify the default music application, but there are alternatives:
Solution for Lubuntu / LXDE / OpenBox
The following configures the media keys as global keyboard shortcuts that always control Spotify:

*

*Install the Spotify command line client sp, a small bash script controlling Spotify via DBUS: just save the sp file as /usr/local/bin/sp and make it executable.

*Open ~/.config/opebox/lubuntu-rc.xml and somewhere between <keyboard>…</keyboard>, add:
<keybind key="XF86AudioPlay">
  <action name="Execute">
    <command>sp play</command>
  </action>
</keybind>
<keybind key="XF86AudioStop">
  <action name="Execute">
    <command>sp pause</command>
  </action>
</keybind>
<keybind key="XF86AudioNext">
  <action name="Execute">
    <command>sp next</command>
  </action>
</keybind>
<keybind key="XF86AudioPrev">
  <action name="Execute">
    <command>sp prev</command>
  </action>
</keybind>

*Save the file and make your changes effective by executing:
openbox --reconfigure

Sources:

*

*sp Spotify command line client, in the improved version by duncan-bayne

*LXDE wiki on changing keyboard shortcuts

*Config snippet from the LXDE wiki for global media key shortcuts


text:
Q: polyglossia & fontspec's script feature in 'setotherlanguage' My fonts are able to give the wanted output.
My fonts have both the Latin and Hebrew characteres, and even Greek needed.
Is there any other way in which I can have the result wanted?
Do I need the line:
\newfontfamily\hebrew[Script=Hebrew]{Cardo}
...and accordingly the:  \hebrew{....} in the body-text?
Example:
\documentclass{article}
\usepackage{fontspec}
\setmainfont{Cardo} %SBL BibLit; Linux Libertine O; Cardo
\usepackage{polyglossia}
\setdefaultlanguage{english}
\setotherlanguage{hebrew}
\newfontfamily\hebrew[Script=Hebrew]{Cardo}

\begin{document}
This hebrew text is Gen.1:1 from BHS\\
\RL{בְּרֵאשִׁ֖ית בָּרָ֣א אֱלֹהִ֑ים}\\   % result: misplaced vowels & diacritics
\hebrew{\RL{בְּרֵאשִׁ֖ית בָּרָ֣א אֱלֹהִ֑ים}}\\  % result: right placed vowels & diacritics
\end{document}

A: Yes, it's necessary to activate Script=Hebrew because Cardo defines Hebrew mark (that's everything that behaves like a diacritic) positioning only for Hebrew script.


text:
Q: How to count which bracket is unbalance? In a program to check whether the brackets are balanced or not? My program runs correctly it does its work.Only problem that i am facing right now is that i cant count which bracket is mismatch. For example in given below input
[ ] ( ( )

output must be
3

because the 3rd bracket is unmatched.But acc to my code its
5

because the 4th bracket closing is missing which should be at place 5
So anyone please help me to understand how can I do it
Here is a part of my code that does the work
for i in n:
    if i in "{([":
        arr.append(i)
        count += 1
    elif i in "})]":
        if len(arr) == 0:
            flag = 0
            break
        temp = arr.pop()
        if i == "}" and temp == "{" :
            count += 1
            continue
        elif i == ")" and temp == "(":
            count += 1
            continue
        elif i == "]" and temp == "[":
            count += 1
            continue
        else:
            flag = 0
            break

And at last print count

A: You should use a stack to track which braces you have seen. You should push to the stack on an opening brace, and pop from it on a closing brace. As you parse each brace, make a note of its index in the string (e.g. by pushing not just the brace type onto the stack, but maybe a tuple of the character and its index, something like ('[', 1) or ('(', 3). Once you have finished parsing, the only things left on the stack will be the unmatched braces along with their indices.


text:
Q: How to clear the contents of FileReader() buffer? I have a an HTML file uploader with an onChange function that finds the SHA256 hash of the file I have uploaded. My problem is that if I select a new file, it seems to be "building up" the contents of the buffer (thus returning the wrong hash of every file uploaded except the first one). Here is an example of what is happening. Each file is selected in order:
one.txt returns 6b86b273ff34fce19d6b804eff5a3f5747ada4eaa22f1d49c01e52ddb7875b4b (correct)
two.txt returns 1e5e6cdb24208b723fa1631b107613cb1084c202a3b48fc6e3ddf9d458adf5ea
one.txt returns 2ebc9be2494f13b2ec93f578bea1002be847c7fad8a5bf27ddd674547121a284

I have tried to put the buffer into a state, and use the state to find the hash. The hope is that each time the DOM is reloaded (by calling the onChange() function), I would get a fresh buffer. Either I am doing it wrong, or it isn't working. Here is the full code, any thoughts?
import React, { Component } from "react";

const crypto = require("crypto");
const hash = crypto.createHash("sha256");

class SearchPage extends Component {
  constructor(props) {
    super(props);
    this.state = {
      hashOutput: "",
      files: null,
    };
  }

  onChange(e) {
    let files = e.target.files;
    let reader = new FileReader();
    this.setState({ fileName: files[0].name });
    this.setState({ files: files[0] }, () => {
      reader.readAsArrayBuffer(this.state.files);
    });
    console.log(this.state.files);

    reader.onload = e => {
      hash.update(Buffer.from(e.target.result));
      const hashOutput = hash.digest("hex");
      this.setState({ hashOutput });
      console.log(hashOutput);
    };
  }

  render() {
    return (

          <input type="file" name="file" onChange={e => this.onChange(e)} />

    );
  }
}

A: Remove the const hash from the top and try something like this:
onChange(e, hash) {
let files = e.target.files;
let reader = new FileReader();
this.setState({ fileName: files[0].name });
this.setState({ files: files[0] }, () => {
  reader.readAsArrayBuffer(this.state.files);
});
console.log(this.state.files);

reader.onload = e => {
  hash.update(Buffer.from(e.target.result));
  const hashOutput = hash.digest("hex");
  this.setState({ hashOutput });
  console.log(hashOutput);
  };
}

render() {
return (

      <input type="file" name="file" onChange={e =>
      this.onChange(e,
      crypto.createHash("sha256"))} />

    );
   }
  }


text:
Q: Spring Boot Devtools how to reload Maven multiple dependent modules in the independent module? I have a multiple modules Maven with this structure:
app-parent
  -------app-library (Hibernate data entities layer)
  -------app-main (contains app-library as dependency), Spring Boot web application.

The simple pom.xml files for these folders:

*

*app-parent/pom.xml

<modules>
   <module>app-library</module>
   <module>app-main</module>
</modules>
<packaging>pom</packaging>
<name>app-parent</name>

*

*app-library/pom.xml

<parent>
    <groupId>test</groupId>
    <artifactId>app-parent</artifactId>
    <version>1.0.0</version>
</parent>
<dependencies>
   .... Some libraries here ....
</dependencies>

*

*app-main/pom.xml

<parent>
    <groupId>test</groupId>
    <artifactId>app-parent</artifactId>
    <version>1.0.0</version>
</parent>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
    </dependency>
    <dependency>
        <groupId>${project.groupId}</groupId>
        <artifactId>petascope-core</artifactId>
        <version>${project.version}</version>
    </dependency>
</dependencies>

With NetBeans 8.2 and Spring Boot version 1.5.2, I used Spring Devtools to auto reload changed Java classes file (~few seconds) instead of cold restart (> 10 seconds).
On app-main folder, I run this command to set up the WebApplication which allows NetBeans to attach a debugger to port 5005:
mvn spring-boot:run -Drun.jvmArguments="-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005"

Also, in application.properties of app-main/src/main/resources, I added this watch to allow Spring Devtools detect the change from app-library
spring.devtools.restart.additional-paths=../app-library

So, whenever I change one java file in app-main or app-library, I can see from the terminal that Spring DevTool does the reload in few seconds.
     .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.5.2.RELEASE)

  INFO [08:57:20] ApplicationMain@48: Starting ApplicationMain on localhost.localdomain with PID 19645 (/home/rasdaman/rasdaman_community/build/applications/petascope/target/petascope_main/classes started by rasdaman in /home/rasdaman/rasdaman_community/rasdaman/applications/petascope/petascope_main)
 DEBUG [08:57:20] ApplicationMain@51: Running with Spring Boot v1.5.2.RELEASE, Spring v4.3.7.RELEASE
  INFO [08:57:20] ApplicationMain@637: No active profile set, falling back to default profiles: default
[2018-05-01 08:57:22.341] - 19645 INFO [restartedMain] --- org.apache.catalina.core.StandardService: Starting service Tomcat
[2018-05-01 08:57:22.341] - 19645 INFO [restartedMain] --- org.apache.catalina.core.StandardEngine: Starting Servlet Engine: Apache Tomcat/8.5.11
[2018-05-01 08:57:22.361] - 19645 INFO [localhost-startStop-1] --- org.apache.catalina.core.ContainerBase.[Tomcat].[localhost].[/rasdaman]: Initializing Spring embedded WebApplicationContext
  INFO [08:57:24] ApplicationMain@57: Started ApplicationMain in 3.612 seconds (JVM running for 84.418)

The problem is with some basic change in a method of app-library, Spring DevTools can detect the file has been saved and reload, but from the app-main where called this method, the output is still the same, e.g:
app-library
public class Service {
     public String returnValue() {
          // return "Value before Spring DevTools reload.";

          // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
          // After app-main was set up from Maven command lines, I changed this line here and saved it to notice Spring DevTool to reload in the console.
          return "Value after Spring DevTools reload."
     }
}

app-main
public class TestService {

    public TestService() {
         Service service = new Service();
         // !!!!!!!!!!!!!!!!!!!
         // It can only print "Value before Spring DevTools reload."
         // even though the Service file has been changed to return different value and Spring DevTools reloaded.
         System.out.println(service.returnValue());
    }
}

With this problem, I cannot just change in app-library and expect the changes will be applied in app-main. Instead, I have to stop the Maven command line, then in NetBeans click on app-main and select Build with dependencies, then runs Maven command line again to set up this Web Application with cold start (total: ~1 minute).
What can I do to make Spring DevTools can apply the changes from app-library to app-main instantly after I saved files in app-library? That would help to reduce the waiting time from NetBeans "Build with Dependencies".

A: So, in app-main it needs app-library built in local repository (~/.m2/...) and the only way to update this repository is going to app-library folder and run:
mvn install

After that, stop the running Web application from command line (ctrl + c) and restart it with same maven command on app-main folder:
mvn spring-boot:run -Drun.jvmArguments="-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005"

It still takes time to cold restart app-main, but it is acceptable.


text:
Q: Are there only finitely many near-perfect numbers with more than 4 distinct prime divisors? Given a positive integer $n$, let $\sigma(n)$ denote the sum of divisors
of $n$. We say that a positive integer $n$ is a near-perfect number
if $\sigma(n) - 2n$ is greater than $0$ and a proper divisor of $n$.
Question: Is it true that there are only finitely many near-perfect
numbers with more than $4$ distinct prime divisors?


text:
Q: Working with jYearChooser and jMonthChooser i'm working in java swing and i need to get year a jYearChooser and month from a jMonthChooser and then format it to this format "yyyy-MM-dd 00:00:00"
Here is my code , but it doesn't give the expected output
int year = jYearChooser1.getYear();
int month = jMonthChooser1.getMonth();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
Date dt = new Date(year, month,00);
Date todate = dateFormat.format(dt);

please help me

A: That's because year parameter is specific in Date class constructor:
**
 * Allocates a Date object and initializes it so that
 * it represents midnight, local time, at the beginning of the day
 * specified by the year, month, and
 * date arguments.
 *
 * @param   year    the year minus 1900.
 * @param   month   the month between 0-11.
 * @param   date    the day of the month between 1-31.
 * @see     java.util.Calendar
 * @deprecated As of JDK version 1.1,
 * replaced by Calendar.set(year + 1900, month, date)
 * or GregorianCalendar(year + 1900, month, date).
 */
@Deprecated
public Date(int year, int month, int date) {
    this(year, month, date, 0, 0, 0);
}

Also you can notice that this constructor is @Deprecated. So better idea is to use Calendar:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd 00:00:00");

Calendar c = Calendar.getInstance();
c.set(year, month, 1); // Specify day of month

String formattedDate = dateFormat.format(c.getTime());


text:
Q: How would I show an HTML page in Eclipse at Design Time? When I'm writing crappy code in eclipse and I'm looking at a website for help I am constantly flipping back and forth between the browser and eclipse. To help me write crappy code faster is there a way to have a View that has a web page in it? I need to be able to set the URL and if I'm navigating around the site have a button to have it return to the original URL. So a URL Address box and 1 favorite link.
BTW I'm not a Eclipse plugin developer.

A: *

*menu: window / show view / other ...

*enter browser in the search box on top

*select internal web browser

i would recommend you to install the web development tools

*

*menu: help / install new software

*select the software site for your eclipse installation (in my case it's "Helios - http://download.eclipse.org/releases/helios")

*enter "web" in the search bar (and wait a little bit) and select "Eclipse Web Developer Toos" and "Web Page Edtior (Optional)"

A: Just open your HTML file with web page editor. This will open in view where you can view the html code as well as the design it is going to create at run time.

A: The ticked answer did not work for me.
However, removing the line:
-javaagent:C:\Users\EdHeal\eclipse\java-2022-12\eclipse\lombok.jar

From eclipse.ini worked


text:
Q: JavaVisitor vs. JavaIsoVisitor: When to use what? I wonder, what the difference between JavaVistitor and JavaIsoVisittor is. When shall I use what. This is not clear to me from the documentatio https://docs.openrewrite.org/.

A: Did you see the JavaDoc at the top of the JavaIsoVisitor?
/**
 * This iso(morphic) refactoring visitor is the appropriate base class for most Java refactoring visitors.
 * It comes with an additional constraint compared to the non-isomorphic JavaRefactorVisitor:
 * Each visit method must return an AST element of the same type as the one being visited.
 *
 * For visitors that do not need the extra flexibility of JavaRefactorVisitor, this constraint
 * makes for a more pleasant visitor authoring experience as less casting will be required.
 */
public class JavaIsoVisitor<P> extends JavaVisitor<P> {

So whenever you're only replacing elements with elements of the same type, you're able to use the JavaIsoVisitor.
When you're replacing elements with one or more element of a different type, you will have to use JavaVisitor.


text:
Q: Changing the position of AIR-window (in AS3)? I created a simple transparent app for Adobe AIR in Flash. It has not chrome, so now I need to make it draggable. How could this be done? Thanks!

A: This code is for the whole window draggable:
stage.addEventListener( MouseEvent.MOUSE_DOWN, startMove );

private function startMove( event : MouseEvent ) : void {
    stage.nativeWindow.startMove();
}

Other case, if you need just one little part of a window to accept MOUSE_DOWN event to start dragging, replace stage.addEventListener with movieClip.addEventListener and you are done.


text:
Q: Aggregate Function/Group-By Query Performance This query works (thanks to those that helped) to generate a 30-day moving average of volume.
SELECT x.symbol, x.dseqkey, AVG(y.VOLUME) moving_average
FROM STOCK_HIST x, STOCK_HIST y
WHERE x.dseqkey>=29 AND x.dseqkey BETWEEN y.dseqkey AND y.dseqkey+29
AND Y.Symbol=X.Symbol
GROUP BY x.symbol, x.dseqkey
ORDER BY x.dseqkey DESC

However the performance is very bad. I am running the above against a view (STOCK_HIST) that brings two tables (A and B) together. Table A contains daily stock volume and the daily date for over 9,000 stocks dating back as far as 40 years (300+ rows, per year, per each of the 9,000 stocks). Table B is a "Date Key" table that links the date in table A to the DSEQKEY (int).
What are my options for performance improvement? I have heard that views are convenient but not performant. Should I just copy the columns needed from table A and B to a single table and then run the above query? I have indexes on the tables A and B on the stock symbol + date (A) and DSEQKEY (B).
Is it the view that's killing my performance? How can I improve this?
EDIT
By request, I have posted the 2 tables and the view below. Also, now there is one clustered index on the view and each table. I am open to any recommendations as this query that produces the deisred result, is still slow:
SELECT
      x.symbol
    , x.dseqkey
    , AVG(y.VOLUME) moving_average
FROM STOCK_HIST x
JOIN STOCK_HIST y ON x.dseqkey BETWEEN y.dseqkey AND y.dseqkey+29 AND Y.Symbol=X.Symbol
WHERE    x.dseqkey >= 15000
GROUP BY x.symbol, x.dseqkey
ORDER BY x.dseqkey DESC ;

HERE IS THE VIEW:
CREATE VIEW [dbo].[STOCK_HIST]
WITH SCHEMABINDING
AS
SELECT
      dbo.DATE_MASTER.date
    , dbo.DATE_MASTER.year
    , dbo.DATE_MASTER.quarter
    , dbo.DATE_MASTER.month
    , dbo.DATE_MASTER.week
    , dbo.DATE_MASTER.wday
    , dbo.DATE_MASTER.day
    , dbo.DATE_MASTER.nday
    , dbo.DATE_MASTER.wkmax
    , dbo.DATE_MASTER.momax
    , dbo.DATE_MASTER.qtrmax
    , dbo.DATE_MASTER.yrmax
    , dbo.DATE_MASTER.dseqkey
    , dbo.DATE_MASTER.wseqkey
    , dbo.DATE_MASTER.mseqkey
    , dbo.DATE_MASTER.qseqkey
    , dbo.DATE_MASTER.yseqkey
    , dbo.DATE_MASTER.tom
    , dbo.QP_HISTORY.Symbol
    , dbo.QP_HISTORY.[Open]  as propen
    , dbo.QP_HISTORY.High    as prhigh
    , dbo.QP_HISTORY.Low     as prlow
    , dbo.QP_HISTORY.[Close] as prclose
    , dbo.QP_HISTORY.Volume
    , dbo.QP_HISTORY.QRS
FROM dbo.DATE_MASTER
INNER JOIN dbo.QP_HISTORY ON dbo.DATE_MASTER.date = dbo.QP_HISTORY.QPDate ;

HERE IS DATE_MASTER TABLE:
CREATE TABLE [dbo].[DATE_MASTER] (
      [date]    [datetime] NULL
    , [year]    [int] NULL
    , [quarter] [int] NULL
    , [month]   [int] NULL
    , [week]    [int] NULL
    , [wday]    [int] NULL
    , [day]     [int] NULL
    , [nday]    nvarchar NULL
    , [wkmax]   [bit] NOT NULL
    , [momax]   [bit] NOT NULL
    , [qtrmax]  [bit] NOT NULL
    , [yrmax]   [bit] NOT NULL
    , [dseqkey] [int] IDENTITY(1,1) NOT NULL
    , [wseqkey] [int] NULL
    , [mseqkey] [int] NULL
    , [qseqkey] [int] NULL
    , [yseqkey] [int] NULL
    , [tom]     [bit] NOT NULL
) ON [PRIMARY] ;

HERE IS THE QP_HISTORY TABLE:
CREATE TABLE [dbo].[QP_HISTORY] (
      [Symbol] varchar    NULL
    , [QPDate] [date]     NULL
    , [Open]   [real]     NULL
    , [High]   [real]     NULL
    , [Low]    [real]     NULL
    , [Close]  [real]     NULL
    , [Volume] [bigint]   NULL
    , [QRS]    [smallint] NULL
) ON [PRIMARY] ;

HERE IS THE VIEW (STOCK_HIST) INDEX
CREATE UNIQUE CLUSTERED INDEX [ix_STOCK_HIST] ON [dbo].[STOCK_HIST]
(
    [Symbol] ASC,
    [dseqkey] ASC,
    [Volume] ASC
)

HERE IS THE QP_HIST INDEX
CREATE UNIQUE CLUSTERED INDEX [IX_QP_HISTORY] ON [dbo].[QP_HISTORY]
(
    [Symbol] ASC,
    [QPDate] ASC,
    [Close] ASC,
    [Volume] ASC
)

HERE IS THE INDEX ON DATE_MASTER
CREATE UNIQUE CLUSTERED INDEX [IX_DATE_MASTER] ON [dbo].[DATE_MASTER]
(
    [date] ASC,
    [dseqkey] ASC,
    [wseqkey] ASC,
    [mseqkey] ASC
)

I do not have any primary keys setup. Would this help performance?
EDIT - After making suggested changes the query is slower than before. What ran in 10m 44s is currently at 30m and still running.
I made all of the requested changes except I did not change name of date in Date_Master and I did not drop the QPDate column from QP_Hist. (I have reasons for this and do not see it impacting the performance since I'm not referring to it in the query.)
REVISED QUERY
select x.symbol, x.dmdseqkey, avg(y.volume) as moving_average
from dbo.QP_HISTORY as x
join dbo.QP_HISTORY as y on (x.dmdseqkey between y.dmdseqkey and (y.dmdseqkey + 29))
                         and (y.symbol = x.symbol)
where x.dmdseqkey >= 20000
group by x.symbol, x.dmdseqkey
order by x.dmdseqkey desc ;

PK on QP_History
ALTER TABLE [dbo].[QP_HISTORY]
   ADD CONSTRAINT [PK_QP_HISTORY] PRIMARY KEY CLUSTERED ([Symbol] ASC, DMDSeqKey] ASC)

FK on QP_History
ALTER TABLE [dbo].[QP_HISTORY] ADD  CONSTRAINT [FK_QP_HISTORY_DATE_MASTER] FOREIGN KEY([DMDSeqKey]) REFERENCES [dbo].[DATE_MASTER] ([dseqkey])

PK on Date_Master
ALTER TABLE [dbo].[DATE_MASTER]
 ADD  CONSTRAINT [PK_DATE_MASTER] PRIMARY KEY CLUSTERED ([dseqkey] ASC)

EDIT
HERE IS THE EXECUTION PLAN

A: First, separate join an filter.
(edit: fixed ON clause)
SELECT x.symbol, x.dseqkey, AVG(y.VOLUME) moving_average
FROM
    STOCK_HIST x
    JOIN
    STOCK_HIST y ON x.dseqkey BETWEEN y.dseqkey AND y.dseqkey+29
                                AND Y.Symbol=X.Symbol
WHERE x.dseqkey>=29
GROUP BY x.symbol, x.dseqkey
ORDER BY x.dseqkey DESC

Also, what indexes do you have - I'd suggest an index on (dseqkey, symbol) INCLUDE (VOLUME)
Edit 3: you can't have an INCLUDE in a clustered index, my bad. Your syntax is OK.
Please try these permutations... the aim is find the best index for the JOIN and WHERE, followed with the ORDER BY.
CREATE UNIQUE CLUSTERED INDEX [ix_STOCK_HIST] ON [dbo].[STOCK_HIST] (...

    ...[Symbol] ASC, [dseqkey] ASC, [Volume] ASC )

    ...[dseqkey] ASC, [Symbol] ASC, [Volume] ASC )

    ...[Symbol] ASC, [dseqkey] DESC, [Volume] ASC )

    ...[dseqkey] DESC, [Symbol] ASC, [Volume] ASC )

A: SQL Server does not support LAG or LEAD clauses available in Oracle and PostgreSQL, neither does it support session variables like MySQL.
Calculating aggregates against moving windows is a pain in SQL Server.
So God knows I hate to say this, however, in this case a CURSOR based solution may be more efficient.

A: try putting a clustered index on the view. that will make the view persisted to disk like a normal table and your tables won't have to be accessed every time.
that should speed things up a bit.
for better answer please post the link to your original question to see if a better solution can be found.

A: OK, so I'll start from the end. I would like to achieve this model.

With this in place, you can run the query on the history table directly, no need for the view and join to the dbo.DATE_MASTER.
select
      x.symbol
    , x.dseqkey
    , avg(y.volume) as moving_average
from dbo.QP_HISTORY as x
join dbo.QP_HISTORY as y on  (x.dSeqKey between y.dSeqKey and (y.dSeqKey + 29))
                         and (y.symbol = x.symbol)
where x.dseqkey >= 15000
group by x.symbol, x.dseqkey
order by x.dseqkey desc
OPTION (ORDER GROUP) ;

The QP_HISTORY is narrower than the STOCK_HISTORY view, so the query should be faster. The "redundant column removal" from joins is scheduled for the next generation of SQL Server (Denali), so for the time being narrower usually means faster -- at least for large tables. Also, the join on .. and the where clause nicely match the the PK(Symbol, dSeqKey).
Now, how to achieve this:
a) Modify the [date] column in dbo.DATE_MASTER to be if the type date instead of datetime. Rename it FullDate to avoid confusion. Not absolutely necessary, but to preserve my sanity.
b) Add PK to the dbo.DATE_MASTER
alter table dbo.DATE_MASTER add constraint primary key pk_datemstr (dSeqKey);

c) In the table QP_HISTORY add column dSeqKey and populate it for matching QPDate dates.
d) Drop the QPDate column from the  table.
e) Add PK and FK to the QP_HISTORY
alter table dbo.QP_HISTORY
   add constraint pk_qphist  primary key (Symbol, dSeqKey)
 , add constraint fk1_qphist foreign key (dSeqKey)
                             references dbo.DATE_MASTER(dSeqKey) ;

f) Drop all those indexes mentioned at the end ouf your question, at least for the time being.
g) I do not see the size of the Symbol field. Define it as narrow as possible.
h) Needles to say, implement and test this on a development system first.


text:
Q: atmospheric correction in ENVI 5.1 I want to perform atmospheric correction on Landsat 8 images in ENVI 5.1. In order to create radiance image, I selected basic tools> preprocessing> calibration utilities> Landsat calibration. However, OLI sensor does not exist in sensor type. Would you please help me how I can perform this analysis in ENVI 5?

A: Have a look at this Exelis video on Youtube. Use the new interface - not the classic view.


text:
Q: How to download On demand Confluence page content image to local machine? I am new user for on demand confluence, i am able to read the page content using REST API

*

*https://{companyName}.atlassian.net/wiki/rest/prototype/1/content/524312?expand=attachments

I am find the image source link in this content like below

*

*https://{companyName}.atlassian.net/wiki/download/attachments/524312/worddave1f7873c424d7824e580764369e7ee68.png

I am trying to download the images in the page content to local directory using the below c# coding
image=https://{companyName}.atlassian.net/wiki/download/attachments/524312/worddave1f7873c424d7824e580764369e7ee68.png;
imageLocation =@"C:\Images";
string[] FileName = image.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
WebClient client = new WebClient();
client.Credentials = new NetworkCredential("xxx", "yyy");
client.DownloadFile(new Uri(image), imageLocation + "\\" + FileName[FileName.Count() - 1]);

I am not able to download the any images from on demand confluence page.
I also tried the below things
  1. I have manually export the particular page by "Export to HTML" from page operations in on demand confluence
  2. I have checked that export HTML zip file,  an attachment directory have the images in the particular page
I need to achieve my goal like above, please share your knowledge

A: I have changed my code like below, than i have downloaded the on demand confluence page content images to my local machine
image=https://{companyName}.atlassian.net/wiki/download/attachments/524312/worddave1f7873c424d7824e580764369e7ee68.png;
imageLocation =@"C:\Images";
string[] FileName = image.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
WebClient client = new WebClient();
client.DownloadFile(new Uri(image+"?&os_username=xxx&os_password=yyy"), imageLocation + "\\" + FileName[FileName.Count() - 1]);


text:
Q: MVC controller encoding JSON with Json(object) vs JavaScriptSerializer().Serialize(object) In my current MVC application I perform an AJAX call to the controller. The controller gets an object from the database and returns it in the form of a JSON response. My confusion is between using the Controller.Json method vs JavaScriptSerializer.Serialize(object). My object I am converting is a simple class called PhoneSerializable with a few public properties of type string and int.
I have the following:
var serializedPhone = jsSerializer.Serialize(new PhoneSerializable(phone));
return new ContentResult {Content = serializedPhone, ContentType = "application/json"};

This works correctly and I get a JSON response that my AJAX caller can parse.
Yet some online examples I have seen use this instead:
return Json(new PhoneSerializable(phone));

The response of this has mostly null properties and a DenyGet header which means it failed parsing or something. The documentation for the Json(object) method states that it uses the same javascript serializer for the object yet it fails to convert my simple object to JSON.
What am I missing? I would like to use Json(object) since it is much cleaner but I cannot seem to get it to work.
EDIT WITH ANSWER:
The Json() method was defaulting to "DenyGet" adding more parameters fixed the issue and it now works:
return Json(new PhoneSerializable(phone),
            "application/json",
            JsonRequestBehavior.AllowGet);

A: Using the Json method from the Controller base class simply returns a new object of type JsonResult, using the following overload:
protected internal JsonResult Json(object data)
{
    return this.Json(data, null, null, JsonRequestBehavior.DenyGet);
}

protected internal virtual JsonResult Json(
                       object data,
                       string contentType,
                       Encoding contentEncoding,
                       JsonRequestBehavior behavior)
{
    return new JsonResult
    {
        Data = data,
        ContentType = contentType,
        ContentEncoding = contentEncoding,
        JsonRequestBehavior = behavior
    };
}

After you return Json(new PhoneSerialize(phone));, the controller eventually invokes a method called ExecuteResult(ControllerContext context), which internally does the same serialization with JsonSerializer:
public override void ExecuteResult(ControllerContext context)
{
    if (context == null)
    {
        throw new ArgumentNullException("context");
    }
    if (this.JsonRequestBehavior == JsonRequestBehavior.DenyGet &&
                            string.Equals(context.HttpContext.Request.HttpMethod,
                                          "GET",
                                          StringComparison.OrdinalIgnoreCase))
    {
        throw new InvalidOperationException(MvcResources.JsonRequest_GetNotAllowed);
    }
    HttpResponseBase response = context.HttpContext.Response;
    if (!string.IsNullOrEmpty(this.ContentType))
    {
        response.ContentType = this.ContentType;
    }
    else
    {
        response.ContentType = "application/json";
    }
    if (this.ContentEncoding != null)
    {
        response.ContentEncoding = this.ContentEncoding;
    }
    if (this.Data != null)
    {
        JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
        if (this.MaxJsonLength.HasValue)
        {
            javaScriptSerializer.MaxJsonLength = this.MaxJsonLength.Value;
        }
        if (this.RecursionLimit.HasValue)
        {
            javaScriptSerializer.RecursionLimit = this.RecursionLimit.Value;
        }
        response.Write(javaScriptSerializer.Serialize(this.Data));
    }
}

This basically means you're passing both DenyGet as a default parameter, yet your method is a "GET", which ends up throwing an InvalidOperationException. You should specify the "AllowGet" explicitly to avoid this:
return Json(new PhoneSerializable(phone),
            "application/json",
            JsonRequestBehavior.AllowGet);


text:
Q: SSL proxy error with tfsonline and TeamCity When I set up my project in TeamCity to connect to a version control system root on tfsonline. However, I keep getting a problem related to ServicePointManager claiming some proxy doesn't support HTTPS.
How can I fix this problem? Is there's some additional configuration needed to get it to work?
The error I get:
Server='https://XXXX.visualstudio.com/DefaultCollection/XXXX'
Username='fredrik@XXXXX'
ERROR - The ServicePointManager does not support proxies with the https scheme.
System.Exception: The ServicePointManager does not support proxies with the https scheme.

A: It was solved by installing Visual Studio 2012, updates on the server, and all available updates in Windows Update.


text:
Q: Polymer hello-world component not rendering I'm following the Polymer tutorial at https://www.youtube.com/watch?v=wId1gMzriRE
I'm using Polymer 1.0 (the tutorial is an older version). I had changed the platform.js to webcomponents.js.
Now my index.html is as
<!doctype html>

    <title>Polymer Trial</title>

    <link rel="import" href="elements/hello-world.html">

Test

        <hello-world></hello-world>

And I've my element file hello-world.html as
<link rel="import" href="../bower_components/polymer/polymer.html">
<polymer-element name="hello-world" noscript>
    <template>

Hello World!

    </template>
</polymer-element>

But all I get in the browser is as below; no "Hello World!" is rendered.

Am I missing something? How can I figure out where is the issue?
Attached below is my directory structure.

A: The older tutorial will not work for Polymer 1.0, as there are many drastic changes.  In the new version, a Hello World would look like:
<dom-module id="hello-world">
  <template>

Hello world!

  </template>
</dom-module>

More information can be found in the Polymer documentation at https://www.polymer-project.org/1.0/docs/devguide/feature-overview.html


text:
Q: Select for JSON with LEFT JOIN returns single element array when no data in the right table I'm exporting some data from an MS SQL server database as JSON.
There are two tables with a foreign key from table A to table B. It is a 0-many relationship, ie. a record in table A may have some data in table B, but it doesn't have to. Table A contains people records, and table B is a list of their current and previous addresses.
I'm using this statement to get the JSON data:
SELECT
    A.Firstname,
    A.LastName,
    HistoricAddresses.AddressLine1
    HistoricAddresses.AddressLine2
FROM
    People A
LEFT JOIN
    HistoricAddresses ON HistoricAddresses.PeopleId = A.Id
FOR JSON AUTO

This results in a JSON structure that looks like this:
[
    {
        "Firstname": "xyz",
        "Lastname": "xyz",
        "HistoricAddresses": [
            {
                "AddressLine1": "abc",
                "AddressLine2": "abc"
            },
            // more historic address records follow
        ]
    },
    // more records follow
]

This is all good until one record in the A table does not have any records in the B table. In that case, the JSON looks like this:
[
    {
        "Firstname": "xyz",
        "Lastname": "xyz",
        "HistoricAddresses": [
            {}
        ]
    },
    // more records follow
]

The contents of HistoricAddresses property is an array with a single empty element. It should be just an empty array.
Is there a way to accomplish that?

A: I solved this by not using a LEFT JOIN, but a subselect.
Instead of
SELECT
    A.Firstname,
    A.LastName,
    HistoricAddresses.AddressLine1
    HistoricAddresses.AddressLine2
FROM
    People A
LEFT JOIN
    HistoricAddresses ON HistoricAddresses.PeopleId = A.Id
FOR JSON AUTO

I'm now using
SELECT
    A.Firstname,
    A.LastName,
    (SELECT
        HistoricAddress.AddressLine1,
        HistoricAddress.AddressLine2
     FROM
        HistoricAddress
     WHERE
        HistoricAddress.PeopleId = A.Id
     FOR JSON AUTO) AS HistoricAddresses
FROM
    People A
FOR JSON AUTO

This completely leaves out the HistoricAddresses JSON property if there aren't any. My parser can work with that.
I haven't benchmarked it yet, though, so other solutions are definitely welcome.

A: I think you can use replace method for that;
SELECT REPLACE((
SELECT
    A.Firstname,
    A.LastName,
    HistoricAddresses.AddressLine1
    HistoricAddresses.AddressLine2
FROM
    People A
LEFT JOIN
    HistoricAddresses ON HistoricAddresses.PeopleId = A.Id
FOR JSON AUTO),'{}','')

This should do the trick.


text:
Q: How to make the text of selected radio button label bold using jQuery or javascript? I want to  make the text of selected radio button label bold using jQuery or javascript. I don't know how to triggerthe function I wrote.

    <input type="radio" name="gender" value="Male" id="male" checked>Male

    <input type="radio" name="gender" value="Female" id="female">Female

$("input[name=gender]:radio").change(function () {
 var gender = $('input[name="gender"]:checked').val();

 switch(gender){
  case "Male":
  $(":radio[value=Male]").css("font-weight", "bold");
  break;

  case "Female":
  $(":radio[value=Female]").css("font-weight", "bold");
  break;
 }
});

A: You can use pure css for that, no need for javascript:

input:checked ~ span {
  font-weight: bold;
}

    <input type="radio" name="gender" value="Male" id="male" checked>Male
    <input type="radio" name="gender" value="Female" id="female">Female

Node that I added a span element to wrap the text (which should be bold).


text:
Q: mysql join query not using index im stuck with a query which take more than 13 secs to return output
i did create the indexes but the execution plan doesnt seem to use them. Below are some information regarding
Query
SELECT  userinfo.username,userinfo.firstname,userinfo.lastname,userinfo.email,
radcheck.attribute,radcheck.value,radusergroup.groupname, userinfo.id,
userinfo.workphone,userinfo.homephone,
userinfo.mobilephone,userinfo.address, userinfo.zone,
userinfo.account_state,userinfo.device_owner,userinfo.link_type,userinfo.account_type
FROM userinfo
INNER JOIN radcheck ON userinfo.username = radcheck.username
INNER JOIN radusergroup ON userinfo.username = radusergroup.username
WHERE  radcheck.attribute='Expiration'  and
STR_TO_DATE(radcheck.value, '%d %M %Y') < CURDATE()
and radusergroup.groupname='Customer30M';

Explain output
+----+-------------+--------------+------+--------------------+-----------+---------+--------------------------------+------+-----------------------------------+
| id | select_type | table        | type | possible_keys      | key       | key_len | ref                            | rows | Extra                             |
+----+-------------+--------------+------+--------------------+-----------+---------+--------------------------------+------+-----------------------------------+
|  1 | SIMPLE      | radusergroup | ref  | username,groupname | groupname | 66      | const                          |    5 | Using where with pushed condition |
|  1 | SIMPLE      | radcheck     | ref  | username,attribute | attribute | 34      | const                          |    9 | Using where                       |
|  1 | SIMPLE      | userinfo     | ref  | username           | username  | 131     | ctradius.radusergroup.username |   10 | Using where                       |
+----+-------------+--------------+------+--------------------+-----------+---------+--------------------------------+------+-----------------------------------+
3 rows in set (0.00 sec)

Table Info
Table: radusergroup
+-----------+-------------+------+-----+---------+----------------+
| Field     | Type        | Null | Key | Default | Extra          |
+-----------+-------------+------+-----+---------+----------------+
| id        | int(11)     | NO   | PRI | NULL    | auto_increment |
| username  | varchar(64) | NO   | MUL |         |                |
| groupname | varchar(64) | NO   | MUL |         |                |
| priority  | int(11)     | NO   |     | 1       |                |
+-----------+-------------+------+-----+---------+----------------+

radusergroup table Index
+--------------+------------+-------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table        | Non_unique | Key_name          | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+--------------+------------+-------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| radusergroup |          0 | PRIMARY           |            1 | id          | A         |       11292 |     NULL | NULL   |      | BTREE      |         |               |
| radusergroup |          1 | username          |            1 | username    | A         |        NULL |     NULL | NULL   |      | BTREE      |         |               |
| radusergroup |          1 | groupname         |            1 | groupname   | A         |        NULL |     NULL | NULL   |      | BTREE      |         |               |
| radusergroup |          1 | indexradusergroup |            1 | username    | A         |        NULL |     NULL | NULL   |      | BTREE      |         |               |
| radusergroup |          1 | indexradusergroup |            2 | groupname   | A         |        NULL |     NULL | NULL   |      | BTREE      |         |               |

Table : userinfo
---------------------+------------------+------+-----+---------------------+----------------+
| Field               | Type             | Null | Key | Default             | Extra          |
+---------------------+------------------+------+-----+---------------------+----------------+
| id                  | int(11) unsigned | NO   | PRI | NULL                | auto_increment |
| username            | varchar(128)     | YES  | MUL | NULL                |                |
| firstname           | varchar(200)     | YES  |     | NULL                |                |
| lastname            | varchar(200)     | YES  |     | NULL                |                |
| email               | varchar(200)     | YES  |     | NULL                |                |
| workphone           | varchar(200)     | YES  |     | NULL                |                |
| homephone           | varchar(200)     | YES  |     | NULL                |                |
| mobilephone         | varchar(200)     | YES  |     | NULL                |                |
| address             | varchar(200)     | YES  |     | NULL                |                |
| zone                | varchar(20)      | YES  |     | NULL                |                |
| account_state       | varchar(10)      | YES  |     | active              |                |
| change_commit       | tinyint(1)       | YES  |     | NULL                |                |
| link_type           | varchar(8)       | YES  |     | NULL                |                |
| account_type        | varchar(255)     | YES  |     | NULL                |                |
| device_owner        | varchar(255)     | YES  |     | NULL                |                |
| account_name        | varchar(255)     | YES  |     | NULL                |                |
| account_email       | varchar(255)     | YES  |     | NULL                |                |
| account_mobile      | varchar(255)     | YES  |     | NULL                |                |
| groupname           | varchar(255)     | YES  |     | NULL                |                |
+---------------------+------------------+------+-----+---------------------+----------------+

Indexes on userinfo
----------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table    | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+----------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| userinfo |          0 | PRIMARY  |            1 | id          | A         |       11282 |     NULL | NULL   |      | BTREE      |         |               |
| userinfo |          1 | username |            1 | username    | A         |        NULL |     NULL | NULL   | YES  | BTREE      |         |               |
+----------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+

Table: Radcheck
+-----------+------------------+------+-----+---------+----------------+
| Field     | Type             | Null | Key | Default | Extra          |
+-----------+------------------+------+-----+---------+----------------+
| id        | int(11) unsigned | NO   | PRI | NULL    | auto_increment |
| username  | varchar(64)      | NO   | MUL |         |                |
| attribute | varchar(32)      | NO   | MUL |         |                |
| op        | char(2)          | NO   |     | ==      |                |
| value     | varchar(253)     | NO   | MUL |         |                |
+-----------+------------------+------+-----+---------+----------------+

indexes on radcheck
+----------+------------+---------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table    | Non_unique | Key_name      | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+----------+------------+---------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| radcheck |          0 | PRIMARY       |            1 | id          | A         |       33425 |     NULL | NULL   |      | BTREE      |         |               |
| radcheck |          1 | username      |            1 | username    | A         |        NULL |     NULL | NULL   |      | BTREE      |         |               |
| radcheck |          1 | value         |            1 | value       | A         |        NULL |     NULL | NULL   |      | BTREE      |         |               |
| radcheck |          1 | attribute     |            1 | attribute   | A         |        NULL |     NULL | NULL   |      | BTREE      |         |               |

A: The function invalidates the use of the index. Despite your cardinality showing 11k rows, the table scan ensues and it takes 13 seconds.
Though you have a join between Radcheck and userinfo, it is the STR_TO_DATE function in the where clause that kills the index use.


text:
Q: Finding the "GAP" in node values ? or next? Let say I have a nodes with values a multiples of 10. I want to find the first GAP in the values.
Here is how I would do it in numpy :
 > np.where(np.diff([11,21,31,51,61,71,91]) > 10)[0][0] + 2
 > 4  i.e. 41

How would I do this in Cypher... ?
 match (n) where n.val % 10 = 1
 with n.val
 order by val ....???

I'm using RedisGraph.
PS>
if no GAP it should return the next value i.e. biggest + 10, if possible !

A: I'm not sure if this is the most performant solution, but you can accomplish this using a combination of collect() and list comprehensions:
MATCH (n) WHERE n.val % 10 = 1 WITH n.val AS val ORDER BY n.val // collect ordered vals
WITH collect(val) AS vals // combine vals into array
WITH vals, [idx IN range(0, size(vals) + 1) WHERE vals[idx + 1] - vals[idx] > 10] AS gaps // find first index with diff > 10
RETURN vals[gaps[0]] + 10 // return missing value

To additionally return the next-biggest value if no gaps are found, change the RETURN clause to use a CASE statement:
RETURN CASE size(gaps) WHEN 0 THEN vals[-1] + 10 ELSE vals[gaps[0]] + 10 END


text:
Q: Finding subset of dataframe rows that maximize one column sum while limiting sum of another A beginner to pandas and python, I'm trying to find select the 10 rows in a dataframe such that the following requirements are fulfilled:

*

*Only 1 of each category in a categorical column

*Maximize sum of a column

*While keeping sum of another column below a specified threshold

The concept I struggle with is how to do all of this at the same time. In this case, the goal is to select 10 rows resulting in a subset where sum of OPW is maximized, while the sum of salary remains below an integer threshold, and all strings in POS are unique. If it helps understanding the problem, I'm basically trying to come up with the baseball dream team on a budget, with OPW being the metric for how well the player performs and POS being the position I would assign them to. The current dataframe looks like this:
    playerID    OPW        POS  salary
87  bondsba01   62.061290   OF  8541667
439 heltoto01   41.002660   1B  10600000
918 thomafr04   38.107000   1B  7000000
920 thomeji01   37.385272   1B  6337500
68  berkmla01   36.210367   1B  10250000
785 ramirma02   35.785630   OF  13050000
616 martied01   32.906884   3B  3500000
775 pujolal01   32.727629   1B  13870949
966 walkela01   30.644305   OF  6050000
354 giambja01   30.440007   1B  3103333
859 sheffga01   29.090699   OF  9916667
511 jonesch06   28.383418   3B  10833333
357 gilesbr02   28.160054   OF  7666666
31  bagweje01   27.133545   1B  6875000
282 edmonji01   23.486406   CF  4500000
0   abreubo01   23.056375   RF  9000000
392 griffke02   22.965706   OF  8019599
       ...    ...        ...     ...

If my team was only 3 people, with a OF,1B, and 3B, and I had a sumsalary threshold of $19,100,000, I would get the following team:
    playerID    OPW        POS  salary
 87 bondsba01   62.061290   OF  8541667
918 thomafr04   38.107000   1B  7000000
616 martied01   32.906884   3B  3500000

The output would ideally be another dataframe with just the 10 rows that fulfill the requirements. The only solution I can think of is to bootstrap a bunch of teams (10 rows) with each row having a unique POS, remove teams above the 'salary' sum threshold, and then sort_value() the teams by df.OPW.sum(). Not sure how to implement that though. Perhaps there is a more elegant way to do this?
Edit: Changed dataframe to provide more information, added more context.

A: IIUC you can use groupby with aggregating sum:
df1 = df.groupby('category', as_index=False).sum()
print (df1)
  category  value  cost
0        A     70  2450
1        B     67  1200
2        C     82  1300
3        D     37  4500

Then filter by boolean indexing with treshold:
tresh = 3000
df1 = df1[df1.cost < tresh]

And last get top 10 values by nlargest:
#in sample used top 3, in real data is necessary set to 10
print (df1.nlargest(3,columns=['value']))
  category  value  cost
2        C     82  1300
0        A     70  2450
1        B     67  1200

A: This is a linear programming problem. For each POS, you're trying to maximize individual OPW while total salary across the entire team is subject to a constraint. You can't solve this with simple pandas operations, but PuLP could be used to formulate and solve it (see the Case Studies there for some examples).
However, you could get closer to a manual solution by using pandas to group by (or sort by) POS and then either (1) sort by OPW descending and salary ascending, or (2) add some kind of "return on investment" column (OPW divided by salary, perhaps) and sort on that descending to find the players that give you the biggest bang for the buck in each position.


text:
Q: Draw line to connect centroids I have an image
.
After I process to find centroid, it has four centroids.
My goal is I want to connect them using line and measure the angle between this area. To be clear about the centroid and my goal, you can open .
Here it is my code to achieve the centroid
I = imread('22c.jpg');
Ibw = im2bw(I);
Ibw = imfill(Ibw,'holes');

Ilabel = bwlabel(Ibw);
stat = regionprops(Ilabel,'centroid');
imshow(I); hold on;
for x = 1: numel(stat)
    plot(stat(x).Centroid(1),stat(x).Centroid(2),'ro');
end

The problem is I am still confused to do the next (to connect each centroids and measure the angle). I need your help, thanks

A: Here is a file exchange link to bresenham.m
Changed your code to get all the 4 centroids
%// read your input image
im = imread('http://i.stack.imgur.com/xeqe8.jpg');

BW = im>220;

CC = bwconncomp(BW);
stat = regionprops(CC,'Centroid');

figure; imshow(BW); hold on
for x = 1: numel(stat)
    plot(stat(x).Centroid(1),stat(x).Centroid(2),'ro');
end

Here is the output:

Further implementation:
%// putting all the Centroid coordinates into corresponding x,y variable
x = [stat(1).Centroid(1),stat(2).Centroid(1),stat(3).Centroid(1),stat(4).Centroid(1)];
y = [stat(1).Centroid(2),stat(2).Centroid(2),stat(3).Centroid(2),stat(4).Centroid(2)];

%// obtain row and col dim
[r,c] = size(BW);

%// get all x,y values connecting the centroid points
[xAll{1},yAll{1}] = bresenham(x(1),y(1),x(4),y(4));
[xAll{2},yAll{2}] = bresenham(x(2),y(2),x(3),y(3));
[xAll{3},yAll{3}] = bresenham(x(3),y(3),x(4),y(4));

%// change row and col subs to linear index
for ii = 1:3
    idx{ii} = sub2ind(size(BW),yAll{ii},xAll{ii});
end

%// change grayscale image to 3D (as you want red line)
out = repmat(im,[1,1,3]);

%// obtaining corresponding index of all 3 slices
for ii = 1:3
    idxall{ii} = bsxfun(@plus, idx{ii},[0:2].*(r*c));
end

%// keep only the index of 1st slice to 255 and changing rest to 0 to obtain a red line.
%// Similar process for blue line except keep the index in the 3rd slice to 255
out(cat(1,idxall{:})) = 0;
out(idx{1}) = 255;
out(idx{2}) = 255;
out(idx{3}+2*(r*c)) = 255;

%// see what you have obtained
figure; imshow(out);hold on
for x = 1: numel(stat)
    plot(stat(x).Centroid(1),stat(x).Centroid(2),'bo');
end

Result:
Note: The line may look dotted due to the picture's large size, but its continuous

Last figure zoomed to see continuous line:

Going further:
You may have to take the advice of @Spektre to find the angle of inclination using atan2. Also refer his answer for more explanation.


text:
Q: The name of the VLAN is abnormal when added to the eth1 When the VLAN is added to the Linux, the VLAN Dev name of VLAN ends normally with the network card. As a result, the abnormal VLAN ends up with the rename word.
normal:

abnormal:

commands:
ifconfig:

sudo vim /etc/sysconfig/network-scripts/ifcfg-eth1:

add vlan:
sudo vconfig add eth1 70:

What happened?

A: before using
vconfig add eth1 70

you might whish to use
vconfig set_name_type VLAN_PLUS_VID_NO_PAD

see man vconfig for details.


text:
Q: Merge Excel sheets with different structure with Talend I have one excel file with this structure:
sheet1 - column1 column2 column3 column4
sheet2 - column1 column3 column4
what i want is to merge both sheets into one, by column name (i.e sheet2 will have null values on column2 but column1 and column3 should merge)
so I should have one sheet with column1 column2 column3 Only
what talend does is that he takes first 3 columns from both sheets and merge them
i.e col1 with col1, col2 with col3 and col3 with col4.
i wanna do this dynamically, i dont really have only 2 sheets, i have a lot, and a lot of excel files, example is just for explaning
Data looks like this

All sheets have commun columns, but some sheets have more columns some less