text:
Q: PYQT5 MDI subwindow the controls move upward than those in design window Why ? Any Solution? I have designed Main window & subwindow in PYQT5 designer
When I run the code the controls move upwards in the subwindow
But when the subwindow is maximized the controls look correctly spaced from top of window
Also when I resize the subwindow manually the window is not painted correctly but the same is ok when I use Maximize & restore buttons
I want to place objects in subwindow at absolute postion relative the top of sub window
Subwindow Class
# -*- coding: utf-8 -*-

# DataForm implementation generated from reading ui file 'subDataForm.ui'
#
# Created by: PyQt5 UI code generator 5.11.3
#
# WARNING! All changes made in this file will be lost!

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QGridLayout, QWidget, QDesktopWidget, QMdiArea, QMdiSubWindow

class Ui_DataForm(object):
    def setupUi(self, DataForm):
        DataForm.setObjectName("DataForm")
        DataForm.resize(577, 366)
        DataForm.setStyleSheet("")
        self.label_2 = QtWidgets.QLabel(DataForm)
        self.label_2.setGeometry(QtCore.QRect(10, 79, 56, 23))
        self.label_2.setObjectName("label_2")
        self.lcdNumber = QtWidgets.QLCDNumber(DataForm)
        self.lcdNumber.setGeometry(QtCore.QRect(10, 50, 64, 23))
        self.lcdNumber.setObjectName("lcdNumber")
        self.pushButton = QtWidgets.QPushButton(DataForm)
        self.pushButton.setGeometry(QtCore.QRect(10, 294, 75, 23))
        self.pushButton.setStyleSheet("")
        self.pushButton.setObjectName("pushButton")
        self.label = QtWidgets.QLabel(DataForm)
        self.label.setGeometry(QtCore.QRect(10, 187, 47, 16))
        self.label.setObjectName("label")
        self.lineEdit = QtWidgets.QLineEdit(DataForm)
        self.lineEdit.setGeometry(QtCore.QRect(10, 268, 133, 20))
        self.lineEdit.setObjectName("lineEdit")
        self.comboBox = QtWidgets.QComboBox(DataForm)
        self.comboBox.setGeometry(QtCore.QRect(10, 242, 69, 20))
        self.comboBox.setObjectName("comboBox")

        self.retranslateUi(DataForm)
        QtCore.QMetaObject.connectSlotsByName(DataForm)

    def retranslateUi(self, DataForm):
        _translate = QtCore.QCoreApplication.translate
        DataForm.setWindowTitle(_translate("DataForm", "DataForm"))
        self.label_2.setText(_translate("DataForm", "TextLabel"))
        self.pushButton.setText(_translate("DataForm", "PushButton"))
        self.label.setText(_translate("DataForm", "TextLabel"))

Mainwindow Class
# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'mainform.ui'
#
# Created by: PyQt5 UI code generator 5.11.3
#
# WARNING! All changes made in this file will be lost!

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QGridLayout, QWidget, QDesktopWidget, QMdiArea, QMdiSubWindow
class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(800, 600)
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap("E:/tools9/rajsoft.ico"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        MainWindow.setWindowIcon(icon)
        #self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.mdi = QMdiArea()
        self.centralwidget = QtWidgets.QWidget(self.mdi)
        self.centralwidget.setObjectName("centralwidget")
        self.gridLayout = QtWidgets.QGridLayout(self.centralwidget)
        self.gridLayout.setObjectName("gridLayout")
        self.verticalLayout = QtWidgets.QVBoxLayout()
        self.verticalLayout.setObjectName("verticalLayout")
        self.mdiArea = QtWidgets.QMdiArea(self.centralwidget)
        self.mdiArea.setObjectName("mdiArea")
        self.verticalLayout.addWidget(self.mdiArea)
        self.gridLayout.addLayout(self.verticalLayout, 0, 0, 1, 1)
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))
        self.menubar.setObjectName("menubar")
        self.menuMain_Menu = QtWidgets.QMenu(self.menubar)
        self.menuMain_Menu.setObjectName("menuMain_Menu")
        MainWindow.setMenuBar(self.menubar)

        self.toolBar = QtWidgets.QToolBar(MainWindow)
        self.toolBar.setObjectName("toolBar")
        MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.toolBar)

        self.actionNew_Window = QtWidgets.QAction(MainWindow)
        self.actionNew_Window.setObjectName("actionNew_Window")
        self.actionExit = QtWidgets.QAction(MainWindow)
        self.actionExit.setObjectName("actionExit")
        self.menuMain_Menu.addAction(self.actionNew_Window)
        self.menuMain_Menu.addAction(self.actionExit)
        self.menubar.addAction(self.menuMain_Menu.menuAction())

        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.menuMain_Menu.setTitle(_translate("MainWindow", "Main Menu"))
        self.toolBar.setWindowTitle(_translate("MainWindow", "toolBar"))
        self.actionNew_Window.setText(_translate("MainWindow", "New Window"))
        self.actionExit.setText(_translate("MainWindow", "Exit"))

Main Program
import sys
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from mainform  import Ui_MainWindow
from subform  import Ui_DataForm
from data_toolbar import Ui_FormToolBar

from PyQt5.QtWidgets import QGridLayout, QWidget, QDesktopWidget
from PyQt5.QtWidgets import QGridLayout, QWidget, QDesktopWidget, QMdiArea, QMdiSubWindow

class SubForm(QMdiSubWindow):
    def __init__(self):
        super().__init__()
        self.subform = Ui_DataForm()
        self.subform.setupUi(self)
        self.tb = Ui_FormToolBar("data_print","n")
        self.tb.setupUi(self)
        self.resizeEvent = self.resized
        self.resize(700, 600)

    def resized(self,event):
        self.tb.reconfig(self)

class AppWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        colors = QAction('Colors', self)
        exitAct = QAction('Exit', self)
        exitAct.triggered.connect(self.close_application)
        btnTB = QToolButton()
        btnTB.setText("TEST")
        self.ui.toolBar.addAction(colors)
        self.ui.toolBar.addAction(exitAct)
        self.ui.toolBar.addWidget(btnTB)
        self.ui.actionExit.triggered.connect(self.close_application)
        self.ui.actionNew_Window.triggered.connect(self.new_window)
        #center the window
        qtRectangle = self.frameGeometry()
        centerPoint = QDesktopWidget().availableGeometry().center()
        qtRectangle.moveCenter(centerPoint)

        sub = SubForm()
        self.ui.mdiArea.addSubWindow(sub)
        self.ui.statusbar.showMessage("HI THERE")
        #sub.move(qtRectangle.topLeft())

        #center the window
        sub.show()

    def close_application(self):
        print("whooaaaa so custom!!!")
        sys.exit()

    def new_window(self):
        sub = SubForm()
        self.ui.mdiArea.addSubWindow(sub)
        sub.show()

app = QApplication(sys.argv)
w = AppWindow()
w.setWindowState(Qt.WindowMaximized)
w.show()
sys.exit(app.exec_())

Data Toobar
import sys
from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_FormToolBar(object):

    def __init__(self,toolbar_type,button_type):
        super().__init__()
        self.toolbar_type = toolbar_type
        self.toolbar_type = self.toolbar_type.lower()
        self.button_type = button_type
        self.button_type = self.button_type.lower()
        self.next_left = 0
        if (self.button_type == "" or self.button_type == "n"):
            self.buttonheight = 41
            self.buttonwidht = 60

        if (self.button_type == "i"):
            self.buttonheight = 29
            self.buttonwidht = 30

    def setupUi(self, FormToolBar):
        _translate = QtCore.QCoreApplication.translate
        FormToolBar.setObjectName("FormToolBar")
        FormToolBar.resize(730, 55)
        self.frame = QtWidgets.QFrame(FormToolBar)
        self.frame.setGeometry(QtCore.QRect(0, 0, 721, 51))
        self.frame.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.frame.setFrameShadow(QtWidgets.QFrame.Raised)
        self.frame.setObjectName("frame")
        FormToolBar.setWindowTitle(_translate("FormToolBar", "Form"))

        self.nextleft = 0
        if (self.toolbar_type == 'data' or self.toolbar_type == 'data_print' or self.toolbar_type == 'data_nav' or self.toolbar_type == 'data_nav_print' ):
            self.btn_New = QtWidgets.QToolButton(self.frame)
            self.btn_New.setGeometry(QtCore.QRect(self.nextleft, 0, self.buttonwidht, self.buttonheight))
            icon3 = QtGui.QIcon()
            icon3.addPixmap(QtGui.QPixmap("D:/tools9/NEW.BMP"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
            self.btn_New.setIcon(icon3)
            if (self.button_type !="i"):
                self.btn_New.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon)
            self.btn_New.setObjectName("btn_New")
            self.btn_New.setText(_translate("FormToolBar", "New"))
            self.nextleft = self.nextleft  + self.buttonwidht

            self.btn_Find = QtWidgets.QToolButton(self.frame)
            self.btn_Find.setGeometry(QtCore.QRect(self.nextleft, 0, self.buttonwidht, self.buttonheight))
            icon = QtGui.QIcon()
            icon.addPixmap(QtGui.QPixmap("D:/tools9/find.bmp"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
            self.btn_Find.setIcon(icon)
            if (self.button_type !="i"):
                self.btn_Find.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon)
            self.btn_Find.setObjectName("btn_Find")
            self.btn_Find.setText(_translate("FormToolBar", "Find"))
            self.nextleft = self.nextleft  + self.buttonwidht + 2

        if (self.toolbar_type == 'data' or self.toolbar_type == 'data_print' )!= True:
            self.btn_First = QtWidgets.QToolButton(self.frame)
            self.btn_First.setGeometry(QtCore.QRect(self.nextleft, 0, self.buttonwidht, self.buttonheight))
            icon4 = QtGui.QIcon()
            icon4.addPixmap(QtGui.QPixmap("D:/tools9/Ffc/Graphics/TOP.BMP"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
            self.btn_First.setIcon(icon4)
            if (self.button_type !="i"):
                self.btn_First.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon)
            self.btn_First.setObjectName("btn_First")
            self.btn_First.setText(_translate("FormToolBar", "First"))
            self.nextleft = self.nextleft  + self.buttonwidht

            self.btn_Prev = QtWidgets.QToolButton(self.frame)
            self.btn_Prev.setGeometry(QtCore.QRect(self.nextleft, 0, self.buttonwidht, self.buttonheight))
            icon7 = QtGui.QIcon()
            icon7.addPixmap(QtGui.QPixmap("D:/tools9/Ffc/Graphics/PREVIOUS.BMP"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
            self.btn_Prev.setIcon(icon7)
            if (self.button_type !="i"):
                self.btn_Prev.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon)
            self.btn_Prev.setObjectName("btn_Prev")
            self.btn_Prev.setText(_translate("FormToolBar", "Previous"))
            self.nextleft = self.nextleft  + self.buttonwidht

            self.btn_Next = QtWidgets.QToolButton(self.frame)
            self.btn_Next.setGeometry(QtCore.QRect(self.nextleft, 0, self.buttonwidht, self.buttonheight))
            icon5 = QtGui.QIcon()
            icon5.addPixmap(QtGui.QPixmap("D:/tools9/Ffc/Graphics/next.bmp"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
            self.btn_Next.setIcon(icon5)
            if (self.button_type !="i"):
                self.btn_Next.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon)
            self.btn_Next.setObjectName("btn_Next")
            self.btn_Next.setText(_translate("FormToolBar", "Next"))
            self.nextleft = self.nextleft  + self.buttonwidht

            self.btn_Last = QtWidgets.QToolButton(self.frame)
            self.btn_Last.setGeometry(QtCore.QRect(self.nextleft, 0, self.buttonwidht, self.buttonheight))
            icon10 = QtGui.QIcon()
            icon10.addPixmap(QtGui.QPixmap("D:/tools9/Ffc/Graphics/BOTTOM.BMP"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
            self.btn_Last.setIcon(icon10)
            if (self.button_type !="i"):
                self.btn_Last.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon)
            self.btn_Last.setText(_translate("FormToolBar", "Last"))
            self.btn_Last.setObjectName("btn_Last")
            self.nextleft = self.nextleft  + self.buttonwidht + 2

        if (self.toolbar_type == 'data' or self.toolbar_type == 'data_print' or self.toolbar_type == 'data_nav' or self.toolbar_type == 'data_nav_print'):
            self.btn_Modify = QtWidgets.QToolButton(self.frame)
            self.btn_Modify.setGeometry(QtCore.QRect(self.nextleft, 0, self.buttonwidht, self.buttonheight))
            icon9 = QtGui.QIcon()
            icon9.addPixmap(QtGui.QPixmap("D:/tools9/OPEN.BMP"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
            self.btn_Modify.setIcon(icon9)
            if (self.button_type !="i"):
                self.btn_Modify.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon)
            self.btn_Modify.setObjectName("btn_Modify")
            self.btn_Modify.setText(_translate("FormToolBar", "Modify"))
            self.nextleft = self.nextleft  + self.buttonwidht

            self.btn_Delete = QtWidgets.QToolButton(self.frame)
            self.btn_Delete.setGeometry(QtCore.QRect(self.nextleft, 0, self.buttonwidht, self.buttonheight))
            icon1 = QtGui.QIcon()
            icon1.addPixmap(QtGui.QPixmap("D:/tools9/CUT.BMP"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
            self.btn_Delete.setIcon(icon1)
            if (self.button_type !="i"):
                self.btn_Delete.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon)
            self.btn_Delete.setObjectName("btn_Delete")
            self.btn_Delete.setText(_translate("FormToolBar", "Delete"))
            self.nextleft = self.nextleft  + self.buttonwidht

            self.btn_Save = QtWidgets.QToolButton(self.frame)
            self.btn_Save.setGeometry(QtCore.QRect(self.nextleft, 0, self.buttonwidht, self.buttonheight))
            icon11 = QtGui.QIcon()
            icon11.addPixmap(QtGui.QPixmap("D:/tools9/SAVE.BMP"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
            self.btn_Save.setIcon(icon11)
            if (self.button_type !="i"):
                self.btn_Save.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon)
            self.btn_Save.setObjectName("btn_Save")
            self.btn_Save.setText(_translate("FormToolBar", "Save"))
            self.nextleft = self.nextleft  + self.buttonwidht

            self.btn_Cancel = QtWidgets.QToolButton(self.frame)
            self.btn_Cancel.setGeometry(QtCore.QRect(self.nextleft, 0, self.buttonwidht, self.buttonheight))
            icon8 = QtGui.QIcon()
            icon8.addPixmap(QtGui.QPixmap("D:/tools9/UNDO.BMP"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
            self.btn_Cancel.setIcon(icon8)
            if (self.button_type !="i"):
                self.btn_Cancel.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon)
            self.btn_Cancel.setObjectName("btn_Cancel")
            self.btn_Cancel.setText(_translate("FormToolBar", "Cancel"))
            self.nextleft = self.nextleft  + self.buttonwidht

        if (self.toolbar_type == 'data_print' or self.toolbar_type == 'data_nav_print' or self.toolbar_type == 'nav_print'):
            self.btn_Print = QtWidgets.QToolButton(self.frame)
            self.btn_Print.setGeometry(QtCore.QRect(self.nextleft, 0, self.buttonwidht, self.buttonheight))
            icon6 = QtGui.QIcon()
            icon6.addPixmap(QtGui.QPixmap("D:/tools9/PRINT.BMP"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
            self.btn_Print.setIcon(icon6)
            if (self.button_type !="i"):
                self.btn_Print.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon)
            self.btn_Print.setObjectName("btn_Print")
            self.btn_Print.setText(_translate("FormToolBar", "Print"))
            self.nextleft = self.nextleft  + self.buttonwidht

        self.btn_Exit = QtWidgets.QToolButton(self.frame)
        self.btn_Exit.setGeometry(QtCore.QRect(self.nextleft, 0, self.buttonwidht, self.buttonheight))
        icon2 = QtGui.QIcon()
        icon2.addPixmap(QtGui.QPixmap("D:/tools9/CLOSE.BMP"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.btn_Exit.setIcon(icon2)
        if (self.button_type !="i"):
            self.btn_Exit.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon)
        self.btn_Exit.setObjectName("btn_Exit")
        self.btn_Exit.setText(_translate("FormToolBar", "Exit"))
        self.nextleft = self.nextleft  + self.buttonwidht

        QtCore.QMetaObject.connectSlotsByName(FormToolBar)
        FormToolBar.setTabOrder(self.btn_New, self.btn_Find)
        if (self.toolbar_type == 'data' or self.toolbar_type == 'data_print' )!= True:
            FormToolBar.setTabOrder(self.btn_Find, self.btn_First)
            FormToolBar.setTabOrder(self.btn_First, self.btn_Prev)
            FormToolBar.setTabOrder(self.btn_Prev, self.btn_Next)
            FormToolBar.setTabOrder(self.btn_Next, self.btn_Last)
            FormToolBar.setTabOrder(self.btn_Last, self.btn_Modify)

        if (self.toolbar_type == 'data' or self.toolbar_type == 'data_print' ):
            FormToolBar.setTabOrder(self.btn_Find, self.btn_Modify)
            FormToolBar.setTabOrder(self.btn_Modify, self.btn_Delete)
            FormToolBar.setTabOrder(self.btn_Delete, self.btn_Save)
            FormToolBar.setTabOrder(self.btn_Save, self.btn_Cancel)
        else:
            FormToolBar.setTabOrder(self.btn_Last, self.btn_Modify)
            FormToolBar.setTabOrder(self.btn_Modify, self.btn_Delete)
            FormToolBar.setTabOrder(self.btn_Delete, self.btn_Save)
            FormToolBar.setTabOrder(self.btn_Save, self.btn_Cancel)
        if (self.toolbar_type == 'data_print' or self.toolbar_type == 'data_nav_print' or self.toolbar_type == 'nav_print' ):
            FormToolBar.setTabOrder(self.btn_Cancel, self.btn_Print)
            FormToolBar.setTabOrder(self.btn_Print, self.btn_Exit)
        else:
            FormToolBar.setTabOrder(self.btn_Cancel, self.btn_Exit)
        FormToolBar.resize(self.nextleft + 10, 55)
        self.frame.setGeometry(QtCore.QRect(0, 0, self.nextleft + 8, 54))

    def reconfig(self,parent):
        self.po = parent
        parentwidth = parent.frameGeometry().width()
        parentheight = parent.frameGeometry().height()
        mywidth = self.frame.frameGeometry().width()
        myheight = self.frame.frameGeometry().height()
        width = ((parentwidth/2) - (mywidth/2))
        height = parentheight- (myheight + 30)
        self.frame.move(width,height)
        self.btn_Exit.clicked.connect(sys.exit)
        self.frame.update()

A: Your issue happens because you are setting an absolute position based on the window geometry, which can also include the title bar; in your case the vertical position will always be window.y() + titlebar.height() + y, so if the window is maximized the titlebar will have no height, thus showing the "correct" position you wanted.
The correct implementation of a QMdiSubWindow is to use setWidget() to add its contents. It's almost like using setCentralWidget() for a QMainWindow.
class SubForm(QMdiSubWindow):
    def __init__(self):
        super().__init__()

        # create the widget and set its ui
        self.subform = QWidget()
        subform_ui = Ui_DataForm()
        subform_ui.setupUi(self.subform)

        # set the widget for the window
        self.setWidget(self.subform)

        # you should *not* do this!!!
        self.tb = Ui_FormToolBar("data_print","n")
        self.tb.setupUi(self)

About the last lines, you should never call setupUi more than once on the same widget, and not even against an object that has a class different from what it expects: in your case, Ui_FormToolBar should be a QWidget, but you're using with a QMdiSubWindow instead; while it seems to work, you might face some serious problems in the future. What you should do is to create a separate QWidget and use the form setupUi with it.
Finally, I strongly suggest you to not edit the python files generated by pyuic to create your programs; read the official documentation on how to correctly use the files created with Designer instead.


text:
Q: OAS 3: How I can autopopulate the endpoint name into my responses? Using swagger made the following api:
openapi: 3.0.0
servers: []
info:
  description: This is a simple API
  version: "1.0.0"
  title: Simple API

paths:
  /inventory:
    get:
      summary: searches inventory
      description: |
        By passing in the appropriate options, you can search for
        available inventory in the system
      parameters:
        - in: query
          name: searchString
          description: pass an optional search string for looking up inventory
          required: false
          schema:
            type: string
      responses:
        '200':
          description: search results matching criteria
          content:
            application/json:
              schema:
                type: array
                items:
                  type: string
                  description: "Item names"
        '400':
          description: bad input parameter
          content:
            application/json:
              schema:
                type: object
                properties:
                  '/inventory':
                    type: boolean
                  message:
                    type: string
  /baka:
    get:
      responses:
        400:
          description: "ERROR"
          content:
            application/json:
              schema:
                type: object
                properties:
                  '/baka':
                    type: boolean
                  message:
                    type: string

As you can see I use the following pattern for my error responses:
endpoint_name: boolean
message: string

So how I can create a common response object that swagger will auto-populate with endpoint name?

redpajama_set_name: RedPajamaStackExchange


text:
Q: I do want to design something like shown below in image using css with that bevel effect I do want to apply the effects similar to shown in image below using css. I tried but unable to get the shinning or overlay arc thing?
So kindly help out with:

I do had tried this but unable to apply the solution provided below.
<!Doctype html>

    <title>JQ chart</title>
    <link rel="stylesheet" type="text/css" href="css/jquery.jqGauges.css">

A: You mean something like...

.shinyCircle{
  position:relative;
  overflow:hidden;
  background:#9F9F9F;
  width:200px;
  height:200px;
  border-radius:50%;
  border:5px solid #000;
}

.shinyCircle:after{
  position:absolute;
  content:"";
  background: -webkit-linear-gradient(top, #333, #ccc);
  background: -moz-linear-gradient(top, #333, #ccc);
  background: -ms-linear-gradient(top, #333, #ccc);
  background: linear-gradient(top, #333, #ccc);
  width:inherit;
  height:inherit;
  border-radius:inherit;
  top:30%;
}


text:
Q: how to Apply same autocomplete action to multiple form fields i am trying to add multiple product.For the name of each product i want to give user auto suggest,But i am able to give auto suggest for only first product.can any one tell me what i am doing wrong.
My html Code
Product Name 1.
<input style="border:2px solid #7f9db9" name="product1" id="in_pc_item_moq_unit_type" class="ui-autocomplete-input"  maxlength="100" placeholder="Enter your product name" type="text">

Product Name 2.

<input style="border:2px solid #7f9db9" name="product2" id="in_pc_item_moq_unit_type" class="ui-autocomplete-input"  maxlength="100" placeholder="Enter your product name" type="text">

Product Name 3.
<input style="border:2px solid #7f9db9" class="ui-autocomplete-input"id="in_pc_item_moq_unit_type" maxlength="100" name="product3" placeholder="Enter your product name" type="text">

Product Name 4.

   <input style="border:2px solid #7f9db9"  class="ui-autocomplete-input" id="in_pc_item_moq_unit_type" maxlength="100" name="product4" placeholder="Enter your product name" type="text">

 Product Name 5.

   <input style="border:2px solid #7f9db9"  class="ui-autocomplete-input" id="in_pc_item_moq_unit_type" maxlength="100" name="product5" placeholder="Enter your product name" type="text">

My Java script code
   < script language="javascript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>

A: You use a common function for this
Use below code and let me know
function auto_suggest(id)
{
    if(typeof(Suggester)!="undefined")
    {
        sugg=new Suggester({"element":id,"onSelect":selecttext,"type":"mcat","placeholder":"Enter your product name","classPlaceholder":"ui-placeholder-input",minStringLengthToFetchSuggestion:1});
    }else
    {
        setTimeout(function(){
            auto_suggest(id)},50);
    }
}
auto_suggest('text-box-id-1');
auto_suggest('text-box-id-2');
auto_suggest('text-box-id-3');

function selecttext(event, ui)
{
    this.value = ui.item.value;

}

Update :-
You are doing something wrong copy paste the below code.
HTML :-
You should not have same id in the html document.
Product Name 1.
<input style="border:2px solid #7f9db9" name="product1" id="in_pc_item_moq_unit_type1" class="ui-autocomplete-input"  maxlength="100" placeholder="Enter your product name" type="text">

Product Name 2.

<input style="border:2px solid #7f9db9" name="product2" id="in_pc_item_moq_unit_type2" class="ui-autocomplete-input"  maxlength="100" placeholder="Enter your product name" type="text">

Product Name 3.
<input style="border:2px solid #7f9db9" class="ui-autocomplete-input"id="in_pc_item_moq_unit_type3" maxlength="100" name="product3" placeholder="Enter your product name" type="text">

Product Name 4.

<input style="border:2px solid #7f9db9"  class="ui-autocomplete-input" id="in_pc_item_moq_unit_type4" maxlength="100" name="product4" placeholder="Enter your product name" type="text">

Product Name 5.

<input style="border:2px solid #7f9db9"  class="ui-autocomplete-input" id="in_pc_item_moq_unit_type5" maxlength="100" name="product5" placeholder="Enter your product name" type="text">

Javascript :-
  function auto_suggest(id)
    {
        if(typeof(Suggester)!="undefined")
        {
            sugg=new Suggester({"element":id,"onSelect":selecttext,"type":"mcat","placeholder":"Enter your product name 2","classPlaceholder":"ui-placeholder-input",minStringLengthToFetchSuggestion:1});
        }else
        {
            setTimeout(function(){
                auto_suggest(id)},50);
        }
    }
    auto_suggest('in_pc_item_moq_unit_type1');
    auto_suggest('in_pc_item_moq_unit_type2');
    auto_suggest('in_pc_item_moq_unit_type3');
    auto_suggest('in_pc_item_moq_unit_type4');
    auto_suggest('in_pc_item_moq_unit_type5');

    function selecttext(event, ui)
    {
        this.value = ui.item.value;

    }


text:
Q: Auto-reprojecting (st_transform) SRIDs in Postgis I have a postgis table that is edited from different sources.

*

*The points added from Source 1 are in SRID 23030.

*The points added from Soruce 2 are in SRID 4230.
I want all the points in the table to be stored in SRID 23030.
I can create a trigger and st_transform(the_geom,23030) all NEW.the_geom but i was wondering is this is the easiest way to achieve this.
Maybe i can create a CONSTRAINT or something that reprojects (st_transforms) every point if SRID it's not in 23030 or something like that?
Any suggestion?
Regards,

A: I think that if the transformation can not be handled on the client side, a trigger is the way to go. It's a simple approach and it will work for your case.
CREATE OR REPLACE FUNCTION myschema.transform () RETURNS trigger AS $$
BEGIN
    NEW.geom = ST_Transform(NEW.geom, 23030);
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER transform
       BEFORE INSERT OR UPDATE ON myschema.mytable
       FOR EACH ROW
       EXECUTE PROCEDURE myschema.transform();

Note, that check for the actual projections is no need, you can safely call ST_Transform on a geometry that is already in the target projection.
Maybe if you have a lot of inserts or updates, and few selects or depending on your exact user cases another approach will be useful. For example, allow having geometries with mixed srid in the table and having a SELECT RULE to make the transformation on the fly. But I don't like this as I think that usually is better have constraints a typemods to keep data integrity.


text:
Q: React Hook not notifying state change to components using the hook So I have a Hook
export default function useCustomHook() {
    const initFrom = localStorage.getItem("startDate") === null? moment().subtract(14, "d"): moment(localStorage.getItem("startDate"));
    const initTo = localStorage.getItem("endDate") === null? moment().subtract(1, "d"): moment(localStorage.getItem("endDate"));

    const [dates, updateDates] = React.useState({
        from: initFrom,
        to: initTo
    });

    const [sessionBreakdown, updateSessionBreakdown] = React.useState(null);

    React.useEffect(() => {
        api.GET(`/analytics/session-breakdown/${api.getWebsiteGUID()}/${dates.from.format("YYYY-MM-DD")}:${dates.to.format("YYYY-MM-DD")}/0/all/1`).then(res => {
            updateSessionBreakdown(res.item);
            console.log("Updated session breakdown", res);
        })
    },[dates])

    const setDateRange = React.useCallback((startDate, endDate) => {
        const e = moment(endDate);
        const s = moment(startDate);
        localStorage.setItem("endDate", e._d);
        localStorage.setItem("startDate", s._d);
        updateDates((prevState) => ({ ...prevState, to:e, from:s}));
    }, [])

    const getDateRange = () => {
        return [dates.from, dates.to];
    }

    return [sessionBreakdown, getDateRange, setDateRange]

}

Now, this hook appears to be working in the network inspector, if I call the setDateRanger function I can see it makes the call to our API Service, and get the results back.
However, we have several components that are using the sessionBreakdown return result and are not updating when the updateSessionBreakdown is being used.
i can also see the promise from the API call is being fired in the console.

I have created a small version that reproduces the issue I'm having with it at https://codesandbox.io/s/prod-microservice-kq9cck Please note i have changed the code in here so it's not reliant on my API Connector to show the problem,

A: To update object for useState, recommended way is to use callback and spread operator.
updateDates((prevState) => ({ ...prevState, to:e, from:s}));

Additionally, please use useCallback if you want to use setDateRange function in any other components.
const setDateRange = useCallback((startDate, endDate) => {
    const e = moment(endDate);
    const s = moment(startDate);
    localStorage.setItem("endDate", e._d);
    localStorage.setItem("startDate", s._d);
    updateDates((prevState) => ({ ...prevState, to:e, from:s}));
}, [])

Found the problem:
You are calling CustomHook in 2 components separately, it means your local state instance created separately for those components. So Even though you update state in one component, it does not effect to another component.
To solve problem, call your hook in parent component and pass the states to Display components as props.
Here is the codesandbox. You need to use this way to update in one child components and use in another one.
If wont's props drilling, use Global state solution.


text:
Q: Upgrade 2.2 to 2.3 - unique situation, PHP Stuck at 7.2 So, I'm on shared hosting, which works great for me, until now. My host updated PHP CLI to 7.2.15 My magento is on 2.2.6(doesn't support 7.2.15) so I need to upgrade to Magento 2.3.
My issue is I have no control over PHP CLI. How can I upgrade to 2.3 with PHP CLI at 7.2.15?


text:
Q: Errors in Java saving into a File Currently I am working on something but I don't know if its possible or not.
My problem is that can i save all errors that is displayed in the console and saving it into a text file.?
Also, is it also possible to save the warnings that will be shown.?
public static void main(String[] args) throws Exception {

    System.err.println("Successfully Printed!");
    PrintStream console = System.err;

    File file = new File("C:\\Users\\USer1\\Documents\\ERRORS\\errors.txt");
    FileOutputStream fos = new FileOutputStream(file);
    PrintStream ps = new PrintStream(fos);
    System.setErr(ps);

    System.err.println("ERRORS FOUND \n \n");

    try {
          int[] x = new int[1];
            x[2] = 5;
            x[1] = 10;
            x[2]=4;
    } catch (Exception e) {
        e.printStackTrace();
    }
    System.setErr(console);

I have tried this but only 1 error is saved on a text file. Is it possible to capture all errors and also the warning if there is any ( i.e unused variables)
Please keep in mind that I am using Java Language for this .
Thank you very much!!!

A: 1) Errors are generally recorded with a logging API instead of using the error output : System.err.
It is much simpler and cleaner.
Besides,  assigning a new value to  System.setErr in the frame of an application can be very error prone if at a time the statement that re-assigns the original value is not executed.
2) You have to enclose each statement that may throw an exception in a try/catch statement to capture all of them.
Extracting the execution of the statements in a method would avoid duplication.
In Java 8, you could write :
int[] x = new int[1];
execute(()->x[2] = 5, ()->x[1] = 10, ()->x[2] = 4);

public void execute(Runnable... calls) {
    for (Runnable call : calls) {
        try {
            call.run();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

Without Java 8 feature, you will probably use anonymous classes instead of lambdas:
int[] x = new int[1];
execute(new Runnable() {
            public void run() {
                x[2] = 5;
            }
        },

        new Runnable() {
            public void run() {
                x[1] = 10;
            }
        },

        new Runnable() {
            public void run() {
                x[2] = 4;
            }
        });


text:
Q: Does $a c>b^2$ if and only if $(1-a) (1-c)<(1-b)^2$, where $0Does $$a c>b^2$$  if and only if  $$(1-a) (1-c)<(1-b)^2,$$ where $0<a<1, 0<c<1$, and $0<b<1$ If it is correct, then how to prove it?

A: I finally find a easy way to prove it.
First, $ac>b^2$ implies $b^2<(\frac{a+c}{2})^2$. And note that $$(1-a)(1-c)-(1-b)^2 \leq (1-\frac{a+c}{2})^2-(1-b)^2=(2-\frac{a+c}{2}-b)(b-\frac{a+c}{2})<0$$
The last inequality is from $b^2\leq(\frac{a+c}{2})^2$ combined with $a,b,c,\in (0,1)$.


text:
Q: A bijection from $\{x: h(x)=\frac{1}{5}\}$ to $\mathbb N$ Question :
Assume that every rational number is written in the form $\frac{p}{q}$ such that $(p,q)=1$ and $q \gt 0$.
For every rational number, The function $h(x)$ is defined like this :
$x=\frac{p}{q} \implies h(x)=\frac{1}{q}$
Prove that $S_1:=\{x:h(x)=\frac{1}{5}\}$ is an infinite countable set.
My way :
I think that $S_1$ is equal to $\{\frac{p}{5}:(p,5)=1\}$. So,
I defined a function called $f$ which operates on each member of $S_1$ in this way :
$\forall \frac{p}{5} \in S_1 \space\space\space f(\frac{p}{5}) = p$
( First thing i'm stuck on, is to prove that $f(x)$ is surjective. )
Then i defined another function called $g$ from $\mathbb N$ to  $\mathbb Z-\{x: \exists k \in \mathbb Z \space \space \space x=5k\}$  which behaves this way :
Foreach $n \in \mathbb N$ If $\space\space\space \exists k \in \mathbb Z \space\space\space n=5k$ , $g(n)=$the first negative number in $\mathbb Z$
which is not in the form of $5k$ and is not taken by another number in $\mathbb N$.
If $n$ is not in the form of $5k$ , $g(n)=n$.
So, we have :
$g(1)=1 , g(2)=2 , g(3)=3 , g(4)=4$.
$5$ is in the form of $5k$, So we take the first available negative number in $\mathbb Z$, which is $-1$. $f(5)=-1$.
$g(6)=6, g(7)=7 , g(8)=8 , g(9)=9 $.
$10$ is in the form of $5k$, So $g(10)=-2$.
And so on ...
Then , If we show that $g$ is bijective, There will be a function like $g^{-1}$ from  $\mathbb Z-\{x: \exists k \in \mathbb Z \space \space \space x=5k\}$ to $\mathbb N$.
So, by putting these all together, we will conclude that $g^-1(f(x))$ is a bijective function from $S_1$ to $\mathbb N $.
My problem is that i don't know how to accurately define these functions $f , g$.

A: We already have a 1 to 1 mapping from the rationals to h by definition of h. we know the rationals are countable, therefore the set constructed by members of h are countable. to show that it is infinite it suffices to say that there are infinite primes p not equal to 5 and take 5/p through the definition to show we have all primes are in the set therefore it is countably infinite.

A: First of all, we have $$S_1:=\left\{x:h(x)=\frac{1}{5}\right\}=\left\{\dfrac{5}{p}:gcd(p,5)=1\right\}$$
Now define $$f:S_1\to \mathbb{N}, \dfrac{5}{p}\to p-\left[\frac{p}{5}\right].$$ Check that $f$ is a bijection.


text:
Q: Does $\int_{a}^{b}f(\phi(x))\phi'(x) \ dx=\int_{\phi(a)}^{\phi(b)}f(t) \ dt$ still hold if $f$ is continuous almost everywhere? Equip $[0,1]$ with the Borel sigma algebra and lebesgue measure. Suppose that $\phi\colon[0,1]\to[0,1]$ is continuously differentiable. Does the change of variables formula still hold when the integrand $f\colon[0,1]\to\mathbb{R}$ is merely continuous almost everywhere (instead of continuous)? In other words, for $0\leq a\leq b\leq1$, do we still have
$$\int_{a}^{b}f(\phi(x))\phi'(x) \ dx=\int_{\phi(a)}^{\phi(b)}f(t) \ dt?$$


text:
Q: SAPUI5 multiple sap.m.TileContainer in JS view I have a single page app written in SAPUI5 using JS views. I want to create a "Dashboard" page and put some tiles on it. Therefore I am creating a "sap.m.TileContainer" in the "createContent" function of my view.js-file.
What I need to implement is to have two separate TileConatiner because I have important tiles at the top and less important ones at the bottom. But no matter what I do e.g. putting the two TileContainers in a MatrixLayout, HorizontalLayout or as "content" into a sap.m.page it is no longer shown.
One TileContainer is shown when I just return this single instance directly without any componet surrounding it.
Can anyone help me out here please?
Following code works fine:
    createContent : function(oController) {

    var tileContainer = new sap.m.TileContainer({
        tiles : [
            new sap.m.StandardTile({
            icon : "sap-icon://play",
            title : "Important Tile",
            press : function() {
                oController.nav.to("AfoStart");
            }
        }), new sap.m.StandardTile({
            icon : "sap-icon://pause",
            title : "ANOTHER Important Tile",
            press : function() {
                oController.nav.to("AfoStart");
            }
        }), new sap.m.StandardTile({
            icon : "sap-icon://timesheet",
            title : "Third important tile",
            press : function() {
                oController.nav.to("AfoStart");
            }
        }), new sap.m.StandardTile({
            icon : "sap-icon://number-sign",
            title : "UNIMPORTANT ONE",
            press : function() {
                oController.nav.to("AfoStart");
            }
        }), new sap.m.StandardTile({
            icon : "sap-icon://locate-me",
            title : "UNIMPORTANT TWO",
            press : function() {
                oController.nav.to("AfoStart");
            }
        })

         ],

    });

    return tileContainer;
}

This code doesnt work:
    createContent : function(oController) {

    var tileContainerTop = new sap.m.TileContainer({
        tiles : [
            new sap.m.StandardTile({
            icon : "sap-icon://play",
            title : "Important Tile",
            press : function() {
                oController.nav.to("AfoStart");
            }
        }), new sap.m.StandardTile({
            icon : "sap-icon://pause",
            title : "Another important Tile",
            press : function() {
                oController.nav.to("AfoStart");
            }
        }), new sap.m.StandardTile({
            icon : "sap-icon://timesheet",
            title : "Third important tile",
            press : function() {
                oController.nav.to("AfoStart");
            }
        }),

         ],

    });

    var tileContainerBottom = new sap.m.TileContainer({
        tiles : [
            new sap.m.StandardTile({
            icon : "sap-icon://play",
            title : "UNIMPORTANT ONE",
            press : function() {
                oController.nav.to("AfoStart");
            }
        }), new sap.m.StandardTile({
            icon : "sap-icon://pause",
            title : "UNIMPORTANT TWO",
            press : function() {
                oController.nav.to("AfoStart");
            }
        })
         ],

    });

    var page = new sap.m.Page("myPage", {

        title: "Dashboard",
        content: [tileContainerTop, tileContainerBottom]

    });

    // OR create MatrixLayout here...doenst work
    // OR create HorizontalLayout here...doesnt work

    return page;
}

A: you need to set enableScrolling of your page to false.
Because then the page will take 100% of the place. If you do not do it the page will try to be as big as its content.
A tile container is by default as big as its parent so both the page and the containers will have a height of 0.
Here i placed 2 Tile containers below each other so they take half of the screen:
http://jsbin.com/disalulekezo/1/
Best regards

A: You have to set enableScrolling of your page to false and adjust the height of TileContainer both. Set the height of both container as 50-50% , both the tiles will be visible on your page. Only setting enableScrolling to false will not work.


text:
Q: Android AsyncTask with JSON Parsing and Basic Authentication I have a Rest web service, also service has a Basic Authentication. When I connect to the server, which asking me for a username and password. After that, I access a web service return a user about JsonArray. (username, birthday, age e.g.)
My purpose returning data parse at show the Textviews. I want to use AsyncTask Http request.
Can you give some examples of it? Thanks.

A: class RequestTask extends AsyncTask<String, String, String> {
    @Override
    protected String doInBackground(String... uri) {
        try {
                postData(uri[0]);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return null;
    }
    @Override
    protected void onCancelled() {
        myTask2.cancel(true);

    }
    @Override
    protected void onPostExecute(String url) {
        LinearLayouts();
    }
}

public static String postData(String url) throws UnsupportedEncodingException {
    HttpClient httpclient = new DefaultHttpClient();
    HttpGet httppost = new HttpGet(url);
    String responseString = "";

    try {
        HttpResponse response = httpclient.execute(httppost);
        StatusLine statusLine = response.getStatusLine();
        InputStream inputStream = null;
        if(statusLine.getStatusCode() == HttpStatus.SC_OK){
            inputStream = response.getEntity().getContent();
            if(inputStream != null)
                responseString = convertInputStreamToString(inputStream);
            else
                responseString = "Did not work!";
            JSONObject reader = null;
            JSONArray sys  = null;
            try {
                reader = new JSONObject(responseString);
                String res_metar = reader.getString("YOUR TAG");

            } catch (JSONException e) {
                e.printStackTrace();
            }
            //a = responseString;

        } else{
            response.getEntity().getContent().close();
            throw new IOException(statusLine.getReasonPhrase());
        }
    } catch (ClientProtocolException e) {

    } catch (IOException e) {

        // process execption
    }
    return responseString;
}

private static String convertInputStreamToString(InputStream inputStream) throws IOException{
    BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
    String line = "";
    String result = "";
    while((line = bufferedReader.readLine()) != null)
        result += line;

    inputStream.close();
    return result;

}

You should write it to top in your class.
private static RequestTask myTask2;

and add it to your mainactivity,
myTask2=(RequestTask)new RequestTask().execute(url);

A: alican has already mentioned about asynctask.
Have a look at Error "HTTP/1.1 401 Unauthorized" with basic authentication in android - EWS 2010 which contains information needed for basic authentication


text:
Q: Lowercase headers So I'm writing a book and I managed to put the chapter name on the even pages header and the section name on the odd pages header, and I also could make the chapter name lowercase and my problem now is with the section name, it is all upper case. As shown in the pictures. I want it also to be lowecase. Any solutions!!

Here's my preamble:
\documentclass[12pt, twoside]{book}

\usepackage[ paperwidth=15cm, paperheight=22cm]{geometry}

\usepackage{fancyhdr}
\pagestyle{fancy}
\fancyhf{}
\fancyhead[LE]{\leftmark}
\fancyhead[RO]{\rightmark}
\fancyhead[LO, RE]{\thepage}

\renewcommand{\chaptermark}[1]{%
\markboth{\chaptername
\ \thechapter.\ #1}{}}

A: Do as you did for chapters: add
\renewcommand{\sectionmark}[1]{\markright{\thesection\ #1}}

to your preamble.


text:
Q: AWT TextArea seems to count cr-lf sequence as one character I have this problem:
The text "ABCD\r\nEFGHJ" loaded from a file is matched with java regex "EFGH". Matcher object of course says start of the matched string is in position 6. The matcher counts \r \n as two positions.
I put the original text in a AWT TextArea Component and then call select(6,10) to highlight the area which was matched. Guess what... it starts highlighting from 'F' letter. One position forward than it should...
If more than 1 pair of crlf precedes matched area then highlighting moves even more forward than it should.
Anyone has any simple solution?

A: Simple solution: remove all \r from the text... :-P
Not as stupid as it sounds, unless you have inconsistent end of lines (it can happen) and want to keep them unchanged... And that's probably what the component does anyway.

A: I cant mess with the text because it is protocol data and \r and \n characters have semantics that dont have to do with display or line separation. I just want a component that will treat each one input character separately and treat it as one displayed and counted, no matter how it is displayed.

A: If the \r\n are consistent, you can remove the \r's before running the regex, then replace them before handing off to whatever is next.  Or change a copy, if that works better.  This way, your regex finds the position in a way consistent with what AWT is expecting.


text:
Q: Matching two arrays in Scala I have the following two arrays in Scala:
val array1 = Array("Football","Tennis","Tennis","Golf","Cricket","BasketBall","Golf")

val array2 = Array("Golf","Tennis","Formula1","Rugby")

I want to return the distinct words which match across both arrays. So as "Tennis" and "Golf" appear twice, we would count them as one. I believe you would just do array1.distinct to begin with. I was wondering however, how do I put this into a Scala function?

A: This is the obvious solution:
(array1.toSet intersect array2.toSet).toArray

However Array is not a full Scala type, so better to use Vector or List depending on how you intended to process the data. The Scala collections have a richer set of methods and inter-operate better.


text:
Q: Validation on radio button : javascript I have one registration form and want to add validation on gender section radio buttons.
My form is like
<form name="formreg" enctype="multipart/form-data" method="post">
     <input type="radio" value="male" name="gender" /> Male

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

      <input value="Submit" onclick="return inputval()" type="submit" />
    </form>

I use below script but not working properly ..

unable to find problem.

A: you re getting the element By Id, and 'gender' is your input's name, not the id.
instead of
<input type="radio" value="male" name="gender" /> Male

you should use
<input type="radio" value="male" id="gender" /> Male

A: Since you tagged this with jquery, use :checked pseudo class selector.

A: Try this with :checked:

A: You put jQuery down, so I'll use that.  document.getElementById('checked') does not exist.  Even if it did, it would only apply to one element.  You would have to iterate over each of the [name=gender] elements to see if any is checked.  jQuery makes this trivial:
$(".inputval").on('click', function (e) {
    if (!$("[name=gender]:checked").length) {
        alert('something something gender');
        e.preventDefault();
    }
});

http://jsfiddle.net/ExplosionPIlls/s2YfU/
EDIT: non-jQuery solution is also pretty trivial since querySelectorAll('[name=gender]:checked') works too.

A: There is no need of validation.By default check one radio button
<form name="formreg" enctype="multipart/form-data" method="post">
     <input type="radio" value="male" name="gender" checked="true" /> Male

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

      <input value="Submit" onclick="return inputval()" type="submit" />
    </form>

A: This fiddle could give you some ideas (without jquery). Note that I checked one of the buttons so I could show you that if one is checked, it will set anyChecked to true.
<form name="formreg" enctype="multipart/form-data" method="post">
    <input type="radio" value="male" name="gender" checked="checked"/>Male

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

    <input value="Submit" onclick="return inputval()" type="submit" />
</form>

var output = document.getElementById("output");
var genderInputs = document.getElementsByName("gender");
var anyChecked = false;

for (var j = 0; j < genderInputs.length; j++) {
    if (genderInputs[j].checked === true) {
        anyChecked = true;
        break;
    }
}

output.textContent = "any checked: " + anyChecked;

http://jsfiddle.net/F8XGU/1/


text:
Q: Android: whitelabel app with a debug directory per each flavor I am creating some app with multiple branding variations. One of the requirements is that we deliver 2 environments per client, so I need to have one release build per client for debug and release.
The code in build gradle file is
android {
...
 buildTypes {
    release {
        minifyEnabled false
    }
    debug {
        applicationIdSuffix ".debug"
    }
}
flavorDimensions "branding"
productFlavors {
    mainCompany {
        dimension "branding"
        applicationIdSuffix  ".mainCompany"
    }
    client1 {
        dimension "branding"
        applicationIdSuffix  ".client1"
    }
    client2 {
        dimension "branding"
        applicationIdSuffix  ".client2"
    }
    client3 {
        dimension "branding"
        applicationIdSuffix  ".client3"
    }
}

The directory structure tree is:
.
├── androidTest
│   └── java
├── client1
│   └── res
├── client2
│   └── res
├── client3
│   └── res
├── debug
│   └── res
├── main
│   ├── AndroidManifest.xml
│   ├── java
│   └── res
├── mainCompany
│   └── res
└── test
    └── java

And the question is, how do I create a debug folder per client? Such folder should have just the app icon and the strings with only the app title

A: It seems this was a stupid question. At the end, I found the solution in the android docs. Problem was I didn't know how to search this correctly :(
Here is the piece of doc that answers my question.
And the folders in my case should be called:
client1Debug
client2Debug
client3Debug
mainCompanyDebug
And this works exactly as I expected


text:
Q: AngularJS keeps sending Invalid Request when resource not available Say when I want to pull a collection of images via AJAX and display them in the page using ng-repeat.

The problem is with the above image source tags above. It keeps sending these below invalid requests to the server before the collection get pulled in and causing error messages in the logs file.
GET http://localhost:9000/campaign/%7B%7Bsubmission.profile_picture_url%7D%7D 404 (Not Found) test:138
GET http://localhost:9000/campaign/%7B%7Bsubmission.thumbnail_url%7D%7D 404 (Not Found)

Anyway to prevent this to happen? Thanks!

A: Using the ng values will keep this from happening:

Also, I wouldn't use width like that:

It's preferable to do with CSS (better through a class):

Source: AngularJS: ng


text:
Q: Typescript error after compile Cannot set property of undefined I'm trying to build an app using NodeJs. I'm familiar with raw Node.JS but Typescript is new.
What I'm trying to accomplish is, well, to get it running but I keep running into this error after it compiles into Javascript again. Cannot set property "title" of undefined
So I have two classes, a base class that looks like :
import { Request, Response, Router } from 'express';

export class BaseRoute {

    public basePath: string; // this gets set in child constructors
    public title: string;
    private scripts: string[];

    constructor() {
        this.title = "";
        this.scripts = [];
    }

}

And the one who inherits looks like this:
import { Request, Response, NextFunction, Router } from 'express';
import { BaseRoute } from './BaseRoute';

export class IndexRoute extends BaseRoute {

    constructor() {
        super();
        this.basePath = "/";
    }

    index(req: Request, res: Response, next: NextFunction) {
        this.title = "Home | Page";
        let options: Object = {
            "message": "This is a test message"
        };

        this.render(req, res, "index", options);
    }

}

It transpiles fine into Js but when I try to go to the route / I get the error. The stack tells me that it's being thrown in IndexRoute.index
The transpiled version looks something like:
BaseRoute:
"use strict";
var express_1 = require("express");
var BaseRoute = (function () {
    function BaseRoute() {
        this.title = "";
        this.scripts = [];
    }
    return BaseRoute;
}());
exports.BaseRoute = BaseRoute;

IndexRoute:
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var express_1 = require("express");
var BaseRoute_1 = require("./BaseRoute");
var IndexRoute = (function (_super) {
    __extends(IndexRoute, _super);
    function IndexRoute() {
        var _this = _super.call(this) || this;
        _this.basePath = "/";
        return _this;
    }
    IndexRoute.prototype.index = function (req, res, next) {
        this.title = "Home | Page";
        var options = {
            "message": "This is a test message"
        };
        this.render(req, res, "index", options);
    };
    return IndexRoute;
}(BaseRoute_1.BaseRoute));
exports.IndexRoute = IndexRoute;


text:
Q: Custom timer job email problem We have a daily custom timer job that emails a newsletter. Recently newsletters have not been sent and the timer job status has been stuck on "initialized 0%"
I have cleared the cache as described in this article - http://blogs.msdn.com/b/josrod/archive/2007/12/12/clear-the-sharepoint-configuration-cache-for-timer-job-and-psconfig-errors.aspx
However when the job next runs it goes back to "initialized 0%"
The logs are showing messages such as:

The operation has timed out.   at
  System.Net.Mail.SmtpClient.Send(MailMessage message)

I have confirmed that we are using the correct smtp settings for the outbound smtp server and that subscriber email addresses are being pulled through in the code correctly.
What is strange is that the newsletter is still being received by one recipient, who is using an email address with our company domain.
Is there anything else I can check in SharePoint (2007) or is this an exchange / SMTP issue?
Thanks very much

A:
"What is strange is that the newsletter is still being received by one
  recipient, who is using an email address with our company domain."

Are some of the email addresses outside your domain? SMTP Servers can have different rules for what they will do with internal and external addresses.
I would start by using an SMTP Test tool (you can also use telnet) to verify that you can send emails through your smtp server to internal and external addresses
http://www.simplecomtools.com/productcart/pc/viewPrd.asp?idproduct=5&idcategory=5
You may also want to consider installing a local SMTP server on your SharePoint server (such as IIS SMTP service), getting SharePoint to send to that and then relaying email from the local server to you main server.

A: Try this solution for Sending mail using SMTP.
  MailMessage mailMessage = new MailMessage(new MailAddress("From@gmail.com"), new MailAddress("TO@gmail.com"));
            mailMessage.Subject = "HI";
            mailMessage.IsBodyHtml = true;
            mailMessage.Body = "
Message
";
            System.Net.NetworkCredential networkCredentials = new System.Net.NetworkCredential("From@gmail.com", "PassWord");
            SmtpClient smtpClient = new SmtpClient();
            smtpClient.EnableSsl = true;
            smtpClient.UseDefaultCredentials = false;
            smtpClient.Credentials = networkCredentials;
            smtpClient.Host = "smtp.gmail.com";
            smtpClient.Port = 587;
            ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
            smtpClient.Send(mailMessage);

Main thing in this code is
            ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };


text:
Q: Is Kotlin Plugin required for the Flutter app? I am developing an app in Flutter which require plugins like
dependencies:
  flutter:
    sdk: flutter
  firebase_core: ^0.4.0+9
  firebase_auth: ^0.14.0+5
  cloud_firestore: ^0.12.9+5
  rflutter_alert: ^1.0.3
  modal_progress_hud: ^0.1.3
  gradient_app_bar: ^0.1.3
  firebase_storage_image: ^0.4.0
  shared_preferences: ^0.5.4+6
  firebase_storage: ^3.1.0
  image_picker: ^0.6.2+3
  cached_network_image: ^2.0.0-rc
  url_launcher: ^5.4.1
  fluttertoast: ^3.1.3
  google_map : any

Do I require Kotlin Support?
This is my build.gradle
buildscript {
    ext.kotlin_version = '1.2.71'
    repositories {
        google()
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.2.1'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath 'com.google.gms:google-services:4.2.0'
    }
}

As my app is gaining size It is now 50 MB, thought removing Kotlin Support may minimize the app size.


text:
Q: calling a stored procedure to a class in visual studio I wrote a simple stored procedure the sp_insert that would insert the data and sp_Update that would update the data then sp_delete that would delete data and sp_search that would search the data and last sp_view that would view the data into sql server its look like these
 . I tested the stored procedure and it  executed fine.Now I'm already connect to the database Icon to my Vs2015 until I click to the test connection it's success then click Uk now its connected. look like these..

Now we are on  a windows form UI in my VS2015 C#. I am created a class I name it repository in solution Explorer in my project.these class I have a code here
here it is..here is my  problem I can't call the four stored procedure which is the sp_insert,sp_Update,sp_delete,sp_search,sp_view in my class and its nothing to show.is there any problem regarding of my code.
public class repositories
    {
      //Initializes a new instance of the DataContext class by referencing     the connection name of database.
    public static DataClasses1DataContext db = null;

   //that registration is my table
    public static void add(registration)
    {
        db = new DataClasses1DataContext();
          //they are getting red cannot call sp_insert that i was created in sql server in my whole entire procedure.
        db.sp_insert(Username, password, securityQuestion, SecurityAnswer, LastName, firstName, MiddleInitial, address, gender, birthdate, age);
    }
    public static void Update (registration)
    {
        db = new DataClasses1DataContext();
        db.sp_Update(Username, password, securityQuestion, SecurityAnswer, LastName, firstName, MiddleInitial, address, gender, birthdate, age);
    }
    public static void delete (registration)
    {
        db = new DataClasses1DataContext();
        db.sp_Delete(UserId);
    }
    public static List<sp_ViewResult> View()
    {
        db = new DataClasses1DataContext();
        List<sp_ViewResult> View() = db.sp_view().Tolist<sp_viewResult>();
    }

}

}

I need some guidance in doing so. Can anyone just help me..
Your help is appreciated.

A: If you are using entity framework and registration is an object which was not clarified in you question then this code should work.
Also make sure you have added your stored procedures in you entity framework model. If they are added you could have the error because you are not adding any values but the entire class.

FYI. If you are running debug mode it should catch any error during
  the process if not in a try catch however if you run release it may
  not catch the error.

You may have to import using System; to use IDisposable
public class repositories: IDisposable
{
    private DataClasses1DataContext _db;
    public DataClasses1DataContext db
    {
        get
        {
            if (_db == null)
            {
                _db = new DataClasses1DataContext();
            }

            return _db;
        }
    }

    public static void add(registration reg)
    {
        db.sp_insert(reg.Username, reg.password, reg.securityQuestion, reg.SecurityAnswer, reg.LastName, reg.firstName, reg.MiddleInitial, reg.address, reg.gender, reg.birthdate, reg.age);
    }
    public static void Update(registration reg)
    {
        db.sp_Update(reg.Username, reg.password, reg.securityQuestion, reg.SecurityAnswer, reg.LastName, reg.firstName, reg.MiddleInitial, reg.address, reg.gender, reg.birthdate, reg.age);
    }
    public static void delete(registration reg)
    {
        db.sp_Delete(reg.UserId);
    }
    public static List<sp_ViewResult> View()
    {
        List<sp_ViewResult> View() = db.sp_view().Tolist<sp_viewResult>();
    }

    public void Dispose()
    {
        db.Dispose();
    }
}


text:
Q: Detect when user returns from using EmailComposeTask? I noticed the user is redirected back to our app after sending an email using the EmailComposeTask. Is there maybe a Completed event handler for this or someway to determine when the user returns back to our app?

A: The NavigatedTo event will be raised when the control comes back to your page.
Thanks,
Stefan Wick - Microsoft Silverlight

A: Yes there is a completed event handler.
Here is how to do it for CameraCaptureTask. EmailComposeTask should be the same.


text:
Q: Understanding the structure of $SO(3)$ as a manifold I know that $SO(3)$ is a matrix Lie group and therefore a smooth manifold. It has dimension three and I know that it can be, as a manifold constructed by identifying the antipodal points of $\mathbb S^3$.
I also know the "plate trick", that gives a hint that $SO(3)$ is not simply connected. In particular, we cannot take a closed path and shrink it down to a single point. But the plate trick shows us that we can shrink a closed path that goes around twice down to a single point.
I cannot wrap my head around how to imagine the structure of $SO(3)$ as a manifold. Is there maybe a nice projection into the $\mathbb R^4$ or even $\mathbb R^3$, where we can easily see that a closed path that goes around twice can be shrunken down to a single point?


text:
Q: Get Latest N numbers of records from table using where in condition Need to fetch the latest 3 records from tables of each orderid(s) related to storeid(s) using WHERE IN condition.
For Eg:
--------------------------
orderid      storeid
1               2
5               2
7               2
15              5
18              5
25              5
29              9
65              9
78              9
------------------------

Here my Query:
SELECT * FROM orders WHERE store_id IN('2', '5', '9') ORDER BY store_id

Thanks in advance.

A: using row_number() you can get the latest 3 orderids
select * from orders o
inner join (
   select row_number() over (partition by storeid order by orderid desc) rn, orderid
   from orders) t1 on t1.orderid = o.orderid
where t1.rn <= 3

A: Here is the mysql solution to get n number of rows for each store:
SELECT
*
FROM
(
SELECT
    store_id,
    order_id,
    @curRank := CASE WHEN @prevStore = store_id THEN @curRank + 1 ELSE 0 END AS rank,
    @prevStore:= store_id AS prevStore
FROM orders a, (SELECT @curRank := 0, @prevStore := NULL) r
WHERE store_id IN('2', '5', '9')
ORDER BY 1 desc,2
)a

WHERE a.rank<3;


text:
Q: How can I use the new Spotify API using PHP cURL? I'm trying to get some data from Spotify, since they recently changed their API I wrote a new function that follows new directives:
function get_Spotify() {
    $getTrackID = $this->db->query("SELECT `trackid` FROM `spotify` ORDER BY RAND() LIMIT 1");
    $TrackID = $getTrackID->fetch_assoc();
    $id=$TrackID['trackid'];

    $client_id = '********************';
    $client_secret = '**********************';

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,            'https://accounts.spotify.com/api/token' );
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
    curl_setopt($ch, CURLOPT_POST,           1 );
    curl_setopt($ch, CURLOPT_POSTFIELDS,     'grant_type=client_credentials' );
    curl_setopt($ch, CURLOPT_HTTPHEADER,     array('Authorization: Basic '.base64_encode($client_id.':'.$client_secret)));
    $result=curl_exec($ch);
    $result = json_decode($result, true);
    curl_close($ch);

    //find spotify data
    $spotifyURL = 'https://api.spotify.com/v1/tracks/'.$id;
    $authorization = 'Authorization: Bearer '.$result["access_token"];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json' , $authorization ));
    curl_setopt($ch, CURLOPT_URL, $spotifyURL);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:x.x.x) Gecko/20041107 Firefox/x.x");
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $json = curl_exec($ch);
    $json = json_decode($json, true);
    curl_close($ch);

    $spotifyURL_artist = $json['artists'][0]['href'];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json' , $authorization ));
    curl_setopt($ch, CURLOPT_URL, $spotifyURL_artist);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:x.x.x) Gecko/20041107 Firefox/x.x");
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $json_artist = curl_exec($ch);
    $data_artist = json_decode($json_artist, true);
    curl_close($ch);

    $Spotify_Player = '

'.$json['artists'][0]['name'].'

'.$json['name'].'

'.$json['artists'][0]['name'].'

'.$json['name'].'

 / 0.30

            <audio id="audio-player_spot" ontimeupdate="SeekBar()" ondurationchange="CreateSeekBar()" preload="none" loop>
            <source src="'.$json['preview_url'].'" type="audio/mpeg">Your browser does not support the audio element.
            </audio>

';

    return $Spotify_Player;

}

But my page load slow so after investigating using microtime() I found that this function (get_Spotify()) takes about 300 Milliseconds.
Is there anything wrong with my code that can lead to such a disastrous result?
P.S.
MySQL table actually has only 4 results, so I exclude my query from possible reason.


text:
Q: how to change the color of a row of a table on hover I am trying to change the color of a row of a table on hover.
by using row: hover, but by this way it is just hovering a perticular cell which is obvious.
but when I try using row cell: hover, then it is not having any effect. this is my html.
JSfiddle: https://jsfiddle.net/f4ojhxco/2/

SI. No.
    Application Date
    Customer Name
    Loan Amount
    Loan Status
    Action

    <input type="radio" name="expand">
{{i+1}}
{{item.date}}

  {{item.name}}
{{item.amount}}
{{item.status}}

  More Details

A: Give the style as follows by removing the space between the class .row and :hover.
.row:hover {
    background: green;
}

A: Just add the !important keyword.
  .row :hover {
    background: green !important;
  }

JSfiddle: https://jsfiddle.net/f4ojhxco/3/

A: Try this
#table .row:hover {
 /*add your css here*/
}

A: Try This:

 body {
   background: #cacaca;
   margin: 0;
   padding: 20px;
   font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;
   font-weight: 300;
 }

 #table {
   display: table;
    width: 100%;
   background: #fff;
   margin: 0;
   box-sizing: border-box;
 }

 .caption {
   display: block;
   width: 100%;
   background: #64e0ef;
   height: 55px;
   padding-left: 10px;
   color: #fff;
   font-size: 20px;
   line-height: 55px;
   text-shadow: 1px 1px 1px rgba(0, 0, 0, .3);
   box-sizing: border-box;
 }

 .header-row {
   background: #8b8b8b;
   color: #fff;
 }

 .row {
   display: table-row;
  }

  .row :hover {
    background: green;
  }

 .cell {
   display: table-cell;
   padding: 23px;
   border-bottom: 1px solid #e5e5e5;
   text-align: center;
 }

 .primary {
   text-align: left;
 }

 input[type="radio"],
 input[type="checkbox"] {
   display: none;
 }

 @media only screen and (max-width: 760px) {
   body {
     padding: 0;
   }
   #table {
     display: block;
     margin: 44px 0 0 0;
   }
   .caption {
     position: fixed;
     top: 0;
     text-align: center;
     height: 44px;
     line-height: 44px;
     z-index: 5;
     border-bottom: 2px solid #999;
   }
   .row {
     position: relative;
     display: block;
     border-bottom: 1px solid #ccc;
   }
   .header-row {
     display: none;
   }
   .cell {
     display: block;
     border: none;
     position: relative;
     height: 45px;
     line-height: 45px;
     text-align: left;
   }
   .primary:after {
     content: "";
     display: block;
     position: absolute;
     right: 20px;
     top: 18px;
     z-index: 2;
     width: 0;
     height: 0;
     border-top: 10px solid transparent;
     border-bottom: 10px solid transparent;
     border-right: 10px solid #ccc;
   }
   .cell:nth-of-type(n+2) {
     display: none;
   }
   input[type="radio"],
   input[type="checkbox"] {
     display: block;
     position: absolute;
     z-index: 1;
     width: 99%;
     height: 100%;
     opacity: 0;
   }
   input[type="radio"]:checked,
   input[type="checkbox"]:checked {
     z-index: -1;
   }
   input[type="radio"]:checked~.cell,
   input[type="checkbox"]:checked~.cell {
     display: block;
     border-bottom: 1px solid #eee;
   }
   input[type="radio"]:checked~.cell:nth-of-type(n+2),
   input[type="checkbox"]:checked~.cell:nth-of-type(n+2) {
     background: #e0e0e0;
   }
   input[type="radio"]:checked~.cell:nth-of-type(n+2):before,
   input[type="checkbox"]:checked~.cell:nth-of-type(n+2):before {
     content: attr(data-label);
     display: inline-block;
     width: 60px;
     background: #999;
     border-radius: 10px;
     height: 20px;
     margin-right: 10px;
     font-size: 12px;
     line-height: 20px;
     text-align: center;
     color: white;
   }
   input[type="radio"]:checked~.primary,
   input[type="checkbox"]:checked~.primary {
     border-bottom: 2px solid #999;
   }
   input[type="radio"]:checked~.primary:after,
   input[type="checkbox"]:checked~.primary:after {
     position: absolute;
     right: 18px;
     top: 22px;
     border-right: 10px solid transparent;
     border-left: 10px solid transparent;
     border-top: 10px solid #ccc;
     z-index: 2;
   }
 }
  .cell{
    height:10px;
    background:green;

  }
  .cell:hover{
    background:red;
  }

SI. No.
    Application Date
    Customer Name
    Loan Amount
    Loan Status
    Action

    <input type="radio" name="expand">
1
5-jan-2017

  mr xyz
60k
open

  More Details

A: Just remove space between .row and :hover
.row:hover{
    background: green;
}


text:
Q: Spring Hateoas: When consuming with RESTTemplate then content is always empty I have an endpoint which produces hateoas resources:
@GetMapping()
public ResponseEntity<PagedModel<EntityModel<Content>>> getContent(
    @RequestParam(defaultValue = "0") final Integer page,
    @RequestParam(defaultValue = "10") final Integer size) {
        return ResponsEntity
            .ok()
            .body(service.getContent(page, size));
}

When I call this endpoint using a browser I get the following result:
{
    "_embedded" : {
        "contents": [
            ...,
            ...
        ]
    },
    "_links": {
        "self": {
            "href": "http://localhost:8080/contents?page=0&size=10"
        }
    },
    "page": {
        "size": 10,
        "totalElements": 2,
        "totalPages": 1,
        "number": 0
    }
}

That is fine. But when I use another spring service to consume the endpoint using a rest template:
ResponseEntity response = restTemplate.exchange(
    url,
    GET,
    null,
    new ParameterizedTypeReference<PagedModel<EntityModel<Content>>>() {}));

LOG.info(response);

I get the following output:
<200, PagedResource { content: [], metadata: Metadata { number: 0, total pages: 1, total elements: 2, size: 10}, links: } ...

The content is always empty.
What do I need to do to be able to deserialize the PagedResource correctly?

A: Had to add the following configuration:
@Configuration
public class ServiceConfiguration {

  @Bean
  public ObjectMapper objectMapper() {
    final ObjectMapper objectMapper = new ObjectMapper();

    objectMapper.configure(FAIL_ON_UNKNOWN_PROPERTIES, false);
    objectMapper.registerModule(new Jackson2HalModule());

    return objectMapper;
  }

  @Bean
  public MappingJackson2HttpMessageConverter converter() {
    final MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();

    converter.setSupportedMediaTypes(singletonList(HAL_JSON));
    converter.setObjectMapper(objectMapper());

    return converter;
  }

  @Bean
  public RestTemplate restTemplate(final RestTemplateBuilder builder) {
    return builder.messageConverters(converter()).build();
  }
}


text:
Q: Windows not showing in grub menu in dual boot in separate drives I've dual booted Debian with windows 10 in two separate ssd
Now everytime I boot my grub menu doesn't show windows at all
But if I switch to windows boot manager manually from bios it boots up windows.
I tried
Sudo update-grub

But no result whatsoever
What should I try next?


text:
Q: regex performance java vs c++11 I am learning regex in c++ and java. So i did a performance test on c++11 regex and java regex with same expression and same no of inputs. Strangely java regex is faster than c++11 regex. Is there anything wrong in my code? Pls correct me
Java code:
import java.util.regex.*;

public class Main {
    private final static int MAX = 1_000_000;
    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        Pattern p = Pattern.compile("^[\\w._]+@\\w+\\.[a-zA-Z]+$");
        for (int i = 0; i < MAX; i++) {
            p.matcher("abcd_ed123.t12y@haha.com").matches();
        }
        long end = System.currentTimeMillis();
        System.out.print(end-start);
    }
}

C++ code:
#include <iostream>
#include <Windows.h>
#include <regex>

using namespace std;

int main()
{
    long long start = GetTickCount64();
    regex pat("^[\\w._]+@\\w+\\.[a-zA-Z]+$");
    for (long i = 0; i < 1000000; i++) {
        regex_match("abcd_ed123.t12y@haha.com", pat);
    }
    long long end = GetTickCount64();
    cout << end - start;
    return 0;
}

Performance:
Java -> 1003ms
C++  -> 124360ms

A: Just to add to the already provided answers...
Yes, the C++11 std::regex is slightly slower (even in Release mode) than the Java one.
But PCRE2 with JIT is 3 times faster:
#include <iostream>
#include <chrono>
#define PCRE2_STATIC
#define PCRE2_CODE_UNIT_WIDTH 8
#include "pcre2.h"

using namespace std;
using namespace std::chrono;
using namespace std::chrono_literals;

int main()
{
    auto start = high_resolution_clock::now();
    int errn;
    PCRE2_SIZE erroffset;
    auto pattern = (PCRE2_SPTR8)"^[\\w._]+@\\w+\\.[a-zA-Z]+$";
    pcre2_code* re = pcre2_compile(pattern, PCRE2_ZERO_TERMINATED, 0, &errn, &erroffset, nullptr);
    if (!re)
        cerr << "pcre2_compile failed\n";
    pcre2_match_data* match_data = pcre2_match_data_create_from_pattern(re, nullptr);
    for (long i = 0; i < 1000000; i++) {
        auto text = (PCRE2_SPTR8)"abcd_ed123.t12y@haha.com";
        int rc = pcre2_match(re, text, PCRE2_ZERO_TERMINATED, 0, 0, match_data, nullptr);
        if (rc <= 0)
            cerr << "pcre2_match failed\n";
    }
    auto end = high_resolution_clock::now();
    cout << (end - start) / 1ms << "\n";
    return 0;
}

Results:

*

*PCRE2 v10.21: 139ms

*Java: 440ms

A: As various commenters have pointed out it sounds like you are compiling your C++ code in debug mode which turns off many compiler optimizations and adds some extra diagnostic code to your program.
Since you are using Visual Studio 2017 look for the Solution Configuration drop-down and change it from Debug to Release.

A: Made the C++ sample portable:
#include <iostream>
#include <chrono>
#include <regex>

using C = std::chrono::high_resolution_clock;
using namespace std::chrono_literals;

int main()
{
    auto start = C::now();
    std::regex pat("^[\\w._]+@\\w+\\.[a-zA-Z]+$");
    for (long i = 0; i < 1000000; i++) {
        regex_match("abcd_ed123.t12y@haha.com", pat);
    }
    std::cout << (C::now() - start)/1.0ms;
}

On linux, and with clang++ -std=c++14 -march=native -O3 -o clang ./test.cpp I get 595.970 ms. See also Live On Wandbox
The java runs in 561 ms, on the same machine.

Update: Boost Regex runs much faster, see below comparative benchmark

Caveat: synthetic benchmarks like these are very prone to error: the compiler might sense that no observable side effects are done, and optimize the whole loop out, just to give an example.

More Fun: Adding Boost To The Mix
Using Boost 1.67 and Nonius Micro-Benchmarking Framework

We can see that Boost's Regex implementations are considerably faster.
See the detailed sample data interactive online: https://plot.ly/~sehe/25/
Code Used
#include <iostream>
#include <regex>
#include <boost/regex.hpp>
#include <boost/xpressive/xpressive_static.hpp>
#define NONIUS_RUNNER
#include <nonius/benchmark.h++>
#include <nonius/main.h++>

template <typename Re>
void test(Re const& re) {
    regex_match("abcd_ed123.t12y@haha.com", re);
}

static const std::regex std_normal("^[\\w._]+@\\w+\\.[a-zA-Z]+$");
static const std::regex std_optimized("^[\\w._]+@\\w+\\.[a-zA-Z]+$", std::regex::ECMAScript | std::regex::optimize);
static const boost::regex boost_normal("^[\\w._]+@\\w+\\.[a-zA-Z]+$");
static const boost::regex boost_optimized("^[\\w._]+@\\w+\\.[a-zA-Z]+$", static_cast<boost::regex::flag_type>(boost::regex::ECMAScript | boost::regex::optimize));

static const auto boost_xpressive = []{
    using namespace boost::xpressive;
    return cregex { bos >> +(_w | '.' | '_') >> '@' >> +_w >> '.' >> +alpha >> eos };
}();

NONIUS_BENCHMARK("std_normal",      [] { test(std_normal);      })
NONIUS_BENCHMARK("std_optimized",   [] { test(std_optimized);   })
NONIUS_BENCHMARK("boost_normal",    [] { test(boost_normal);    })
NONIUS_BENCHMARK("boost_optimized", [] { test(boost_optimized); })
NONIUS_BENCHMARK("boost_xpressive", [] { test(boost_xpressive); })

Note Here's the output of the Hotspot JVM JIT compiler:

*

*http://stackoverflow-sehe.s3.amazonaws.com/fea76143-b712-4df9-97c3-4725b2f9e695/disasm.a.xz
This was generated using
LD_PRELOAD=/home/sehe/Projects/stackoverflow/fcml-1.1.3/example/hsdis/.libs/libhsdis-amd64.so ./jre1.8.0_171/bin/java -XX:+UnlockDiagnosticVMOptions -XX:+PrintAssembly Main  2>&1 > disasm.a


text:
Q: How to compress an image up to 5kb? How to write a Base64-encoded image to file?
I encoded an image to a string using Base64.
First, I read the file, then convert it to a byte array and then apply Base64 encoding to convert the image to a string.
Now my problem is how to compress image to 5kb.
Like Whatsapp Image Compression in Android.

A: If what you need is to store the image as "text" you can compress the Base64 string SO answer.
On the other hand you can reduce resolution of the image by lowering its size.
Not all the images can be compressed to 5kb without losing quality, but making proper resolution changes and compresing the image it can be achieved Another SO answer.


text:
Q: preg_replace for closing tags only works for one instance I have the following stored in a database table...

Introduction

    (Some text)

History

    (Some text)

I'd like to insert an element ('XXX') before each div's closing tag...

Introduction

    (Some text)
    XXX

Of course, I have to make sure my script ignores nested div's. The following script almost works:
 $Content = preg_replace('/
([^`]*?)<\/div>/', '
$2XXX
', $Content);

In fact, it does work - but just once; it inserts XXX at the end of the first section only. Also, I discovered that it doesn't ignore nested div's.
Does anyone know how I can fix those problems?

A: Try simplehtmldom. It will make these things a lot easier for you.


text:
Q: Getting unexpected results when using synonyms I am using the following synonym definition:
"medals, medal => metals,medals,medal count, most medals"
When I search "Medals" in the title field, documents like "Armenia Medals, Diving Medals, etc" score higher than a document with a title of "Medals". Since Medals is an exact match I would expect it to be ranked the highest but it isn't. Does anyone have any explanation for this?
I'm using a edge ngram (1 to 50) when indexing documents and the standard analyzer when searching.
Mapping:
"title":{
      "type": "text",
      "analyzer": "full_search_analyzer",
      "search_analyzer": "standard",
      "fields": {
        "keyword":{
          "type": "keyword"
        }
      }
    }
"sport_name":{
      "type": "text",
      "analyzer": "full_search_analyzer",
      "search_analyzer": "standard",
      "fields": {
        "keyword":{
          "type": "keyword"
        }
      }
    },
    "country_name":{
      "type": "text",
      "analyzer": "full_search_analyzer",
      "search_analyzer": "standard",
      "fields": {
        "keyword":{
          "type": "keyword"
        }
      }
    },

Query:
query: {
         bool: {
           must:[{
             "multi_match": {
                 "query": "medals",
                      "fields": "title^2", "sport_name", "country_name",
                                    "minimum_should_match": "100%"
                                }
                            }],
                            should: {
                                term: {
                                    title: "Medals"
                                }
                            },
                            filter: {
                                term: {
                                    hideFullResults : false
                                }
                            }
                        }
                    },

The query is in a node app.
Thanks in advance.


text:
Q: bulk insert blocks nolock query I have a SSIS package that is truncating and then inserting a whole table from serverA to serverB, however I am trying to view the progress of the job by performing a select with a NOLOCK hint on serverB but it gets lock by the "BULK INSERT" performed by the SSIS package.
I have review the "sys.dm_tran_locks" and found that the "BULK INSERT" is holding a "Sch-M" lock on the table, and I don't understand why.
Please can you help me with this?
Thanks.

A: The Sch-M lock indicates that you have at least one index on the destination table.
See "Table Locking and Logging During Bulk Import":
http://msdn.microsoft.com/en-us/library/ms177445%28v=sql.105%29.aspx
Based on the table in the reference, Sch-M will be used when you are bulk inserting into:

*

*A Heap with one non-clustered index and tablock is used

*An empty B-Tree (clustered index) and tablock is used

Also, if the load is done correctly, the truncate will be completed (and it's Sch-M lock gone) before the bulk insert begins.
The bulk update (BU) lock is the most optimal lock, but don't expect to be reading the table during the bulk insert:
Bulk update (BU) locks allow processes to bulk copy data concurrently into the same table while preventing other processes that are not bulk copying data from accessing the table. http://msdn.microsoft.com/en-us/library/aa213039%28v=sql.80%29.aspx
Use Remus suggestion (sys.allocation_units) for checking progress.

A: Truncate requires SCH-M for deallocating the table allocation units. Among other, this lock serves the very purpose of protecting against concurrent dirty reads. Had the truncate succeed in deallocating the table while dirty reads scanner are in it those scanner would all of a sudden find themselves reading pages that belong to no one (or worse, were reallocated to some other AU). As with any write lock, the 2PL protocol requires to be held until end of transaction. Subsequent dirty scanners will block behind it, as they should.
If you do not have the TRUNCATE/BULK INSERT wrapped in a transaction then there are other scenarios that could cause BULK INSERT itself to go SCH-M instead of X (I think table lock hint on bulk insert on an empty table (no AU root page) will cause this).
Too peek at the progress of the BULK INSERT check how many pages are allocated to your target in sys.allocation_units. This will give you a rough estimate of percent complete.


text:
Q: Geometric interpretation of complex eigenvectors I'm having trouble getting the geometric interpretation of complex eigenvectors and eigenvalues of a rotation matrix. I am given A=
\begin{bmatrix}
0 & -2 \\
2 & 0
\end{bmatrix}
The given eigenvalues are:
D=\begin{bmatrix}
2i & 0 \\
0 & -2i
\end{bmatrix}
and the eigenvectors are:\begin{bmatrix}
i & -i \\
1 & 1
\end{bmatrix}
I need to know the geometric interpretation of these complex eigenvectors and values and also those of $A^{\frac{1}{N}}$.
I know that A= $2\cdot\begin{bmatrix} 0 & -1 \\ 1 & 0 \end{bmatrix} = 2\cdot\begin{bmatrix}\cos{\pi /2} & -\sin{\pi /2} \\ \sin{\pi /2} & \cos{\pi /2}\end{bmatrix}$, so $A^{\frac{1}{N}}=2^{\frac{1}{N}}\cdot\begin{bmatrix}\cos{\pi /2N} & -\sin{\pi /2N} \\ \sin{\pi /2N} & \cos{\pi /2N}\end{bmatrix}$, which is a rotation of $\frac{\pi}{2N}$ counterclockwise and scaling by $2^{\frac{1}{N}}$.
I did read the earlier post about geometric interpretation, and the fantastic animated explanation, but I still don't get it. I apologise, it sounds like I'm asking for answers (I kind of am yeah), but I need a worked example to get anything done at all, and David C. Lay's textbook was incomprehensible to me.
Thank you very much for your help.
I'd be very grateful if someone could draw out the basis vectors, show me how I tell how much they rotate, and in which direction, and then how much it scales.