text:
Q: How to add postgresql Driver in liferay? I am trying to save the data in my db (already saving it in lportal). For that i created a connection file and wrote all the required code. Like we do in JDBC. I am able to store the data in lportal(default one) but when I tried to save it in my db.
I am getting below exception.
java.lang.ClassNotFoundException: org.postgresql.Driver cannot be found by ""

I tried adding the JAR to the folder but still the same thing. In JDBC we can add the JAR in lib folder but it doesn't seem to work here.
I also tried adding the jar to the tomcat bundle in lib and lib/ext folder but nothing seems to happen.
I also added the following line in my build.gradle file but no results.
compile group: 'org.postgresql', name: 'postgresql', version: '42.2.25'

Can someone help regarding this as where and how to add JAR or any other file so that I can save the data in db at the same time as lportal.
EDIT 1:
Stacktrace
java.lang.ClassNotFoundException: org.postgresql.Driver cannot be found by my.registration.form_1.0.0
    at org.eclipse.osgi.internal.loader.BundleLoader.findClassInternal(BundleLoader.java:508)
    at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:419)
    at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:411)
    at org.eclipse.osgi.internal.loader.ModuleClassLoader.loadClass(ModuleClassLoader.java:150)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:264)
    at my.registration.form.portlet.DatabaseConnection.initializeDatabase(DatabaseConnection.java:16)
    at my.registration.form.portlet.RegistrationDAO.addOrganization(RegistrationDAO.java:14)
    at my.registration.form.portlet.MyRegistrationFormPortlet.addOrganization(MyRegistrationFormPortlet.java:242)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.liferay.portal.kernel.portlet.LiferayPortlet.callActionMethod(LiferayPortlet.java:189)
    at com.liferay.portal.kernel.portlet.bridges.mvc.MVCPortlet.callActionMethod(MVCPortlet.java:415)
    at com.liferay.portal.kernel.portlet.LiferayPortlet.processAction(LiferayPortlet.java:97)
    at com.liferay.portal.kernel.portlet.bridges.mvc.MVCPortlet.processAction(MVCPortlet.java:260)
    at com.liferay.portlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:77)
    at com.liferay.portal.kernel.portlet.PortletFilterUtil.doFilter(PortletFilterUtil.java:50)
    at com.liferay.portal.kernel.servlet.PortletServlet.service(PortletServlet.java:108)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    at org.eclipse.equinox.http.servlet.internal.registration.EndpointRegistration.service(EndpointRegistration.java:153)
    at org.eclipse.equinox.http.servlet.internal.servlet.ResponseStateHandler.processRequest(ResponseStateHandler.java:62)
    at org.eclipse.equinox.http.servlet.internal.context.DispatchTargets.doDispatch(DispatchTargets.java:120)
    at org.eclipse.equinox.http.servlet.internal.servlet.RequestDispatcherAdaptor.include(RequestDispatcherAdaptor.java:48)
    at com.liferay.portlet.internal.InvokerPortletImpl.invoke(InvokerPortletImpl.java:564)
    at com.liferay.portlet.internal.InvokerPortletImpl.invokeAction(InvokerPortletImpl.java:610)
    at com.liferay.portlet.internal.InvokerPortletImpl.processAction(InvokerPortletImpl.java:299)
    at com.liferay.portal.monitoring.internal.portlet.MonitoringInvokerPortlet.processAction(MonitoringInvokerPortlet.java:216)
    at com.liferay.portlet.internal.PortletContainerImpl._processAction(PortletContainerImpl.java:490)
    at com.liferay.portlet.internal.PortletContainerImpl.lambda$processAction$0(PortletContainerImpl.java:148)
    at com.liferay.portlet.internal.PortletContainerImpl._preserveGroupIds(PortletContainerImpl.java:395)
    at com.liferay.portlet.internal.PortletContainerImpl.processAction(PortletContainerImpl.java:141)
    at com.liferay.portlet.SecurityPortletContainerWrapper.processAction(SecurityPortletContainerWrapper.java:95)
    at com.liferay.portlet.RestrictPortletContainerWrapper.processAction(RestrictPortletContainerWrapper.java:78)
    at com.liferay.portal.kernel.portlet.PortletContainerUtil.processAction(PortletContainerUtil.java:118)
    at com.liferay.portal.action.LayoutAction.processLayout(LayoutAction.java:346)
    at com.liferay.portal.action.LayoutAction.execute(LayoutAction.java:174)
    at com.liferay.portal.struts.PortalRequestProcessor._processActionPerform(PortalRequestProcessor.java:706)
    at com.liferay.portal.struts.PortalRequestProcessor._process(PortalRequestProcessor.java:646)
    at com.liferay.portal.struts.PortalRequestProcessor.process(PortalRequestProcessor.java:194)
    at com.liferay.portal.servlet.MainServlet.process(MainServlet.java:1067)
    at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:462)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
    at com.liferay.portal.servlet.MainServlet.callParentService(MainServlet.java:598)
    at com.liferay.portal.servlet.MainServlet.service(MainServlet.java:575)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:119)
    at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:144)
    at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:103)
    at com.liferay.portal.apio.internal.architect.servlet.filter.APIDocumentationFilter.processFilter(APIDocumentationFilter.java:74)
    at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:49)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDoFilter(InvokerFilterChain.java:207)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:112)
    at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:144)
    at com.liferay.portal.servlet.filters.uploadservletrequest.UploadServletRequestFilter.processFilter(UploadServletRequestFilter.java:111)
    at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:49)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDoFilter(InvokerFilterChain.java:207)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:112)
    at com.liferay.portal.servlet.filters.password.modified.PasswordModifiedFilter.processFilter(PasswordModifiedFilter.java:57)
    at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:49)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDoFilter(InvokerFilterChain.java:207)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:112)
    at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:144)
    at com.liferay.portal.servlet.filters.secure.BaseAuthFilter.processFilter(BaseAuthFilter.java:340)
    at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:49)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDoFilter(InvokerFilterChain.java:207)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:112)
    at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:144)
    at com.liferay.portal.monitoring.internal.servlet.filter.MonitoringFilter.processFilter(MonitoringFilter.java:178)
    at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:49)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDoFilter(InvokerFilterChain.java:207)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:112)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilter.doFilter(InvokerFilter.java:101)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:712)
    at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:459)
    at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:384)
    at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:312)
    at com.liferay.friendly.url.internal.servlet.FriendlyURLServlet.service(FriendlyURLServlet.java:372)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    at com.liferay.portal.servlet.ServletAdapter.service(ServletAdapter.java:98)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:119)
    at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:144)
    at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:103)
    at com.liferay.portal.apio.internal.architect.servlet.filter.APIDocumentationFilter.processFilter(APIDocumentationFilter.java:74)
    at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:49)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDoFilter(InvokerFilterChain.java:207)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:112)
    at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:144)
    at com.liferay.portal.servlet.filters.uploadservletrequest.UploadServletRequestFilter.processFilter(UploadServletRequestFilter.java:111)
    at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:49)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDoFilter(InvokerFilterChain.java:207)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:112)
    at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:144)
    at com.liferay.portal.servlet.filters.strip.StripFilter.processFilter(StripFilter.java:340)
    at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:49)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDoFilter(InvokerFilterChain.java:207)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:112)
    at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:144)
    at com.liferay.portal.servlet.filters.i18n.I18nFilter.processFilter(I18nFilter.java:360)
    at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:49)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDoFilter(InvokerFilterChain.java:207)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:112)
    at com.liferay.portal.servlet.filters.password.modified.PasswordModifiedFilter.processFilter(PasswordModifiedFilter.java:57)
    at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:49)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDoFilter(InvokerFilterChain.java:207)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:112)
    at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:144)
    at com.liferay.portal.servlet.filters.secure.BaseAuthFilter.processFilter(BaseAuthFilter.java:340)
    at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:49)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDoFilter(InvokerFilterChain.java:207)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:112)
    at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:144)
    at com.liferay.portal.servlet.filters.autologin.AutoLoginFilter.processFilter(AutoLoginFilter.java:260)
    at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:49)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDoFilter(InvokerFilterChain.java:207)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:112)
    at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:144)
    at com.liferay.portal.sharepoint.SharepointFilter.processFilter(SharepointFilter.java:88)
    at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:49)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDoFilter(InvokerFilterChain.java:207)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:112)
    at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:144)
    at com.liferay.portal.servlet.filters.virtualhost.VirtualHostFilter.processFilter(VirtualHostFilter.java:263)
    at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:49)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDoFilter(InvokerFilterChain.java:207)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:112)
    at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:144)
    at com.liferay.portal.monitoring.internal.servlet.filter.MonitoringFilter.processFilter(MonitoringFilter.java:178)
    at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:49)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDoFilter(InvokerFilterChain.java:207)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:112)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDirectCallFilter(InvokerFilterChain.java:188)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:96)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDirectCallFilter(InvokerFilterChain.java:188)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:96)
    at org.tuckey.web.filters.urlrewrite.RuleChain.handleRewrite(RuleChain.java:176)
    at org.tuckey.web.filters.urlrewrite.RuleChain.doRules(RuleChain.java:145)
    at org.tuckey.web.filters.urlrewrite.UrlRewriter.processRequest(UrlRewriter.java:92)
    at org.tuckey.web.filters.urlrewrite.UrlRewriteFilter.doFilter(UrlRewriteFilter.java:389)
    at com.liferay.portal.servlet.filters.urlrewrite.UrlRewriteFilter.processFilter(UrlRewriteFilter.java:65)
    at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:49)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDoFilter(InvokerFilterChain.java:207)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:112)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDirectCallFilter(InvokerFilterChain.java:168)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:96)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDirectCallFilter(InvokerFilterChain.java:168)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:96)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDirectCallFilter(InvokerFilterChain.java:188)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:96)
    at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilter.doFilter(InvokerFilter.java:101)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:491)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:764)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1388)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:748)

EDIT 2:
My connection class
package my.registration.form.portlet;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DatabaseConnection
{
     protected static Connection initializeDatabase()throws SQLException, ClassNotFoundException
     {
         String driver = "org.postgresql.Driver";
         String url = "jdbc:postgresql://localhost:5432/my_lportal";
         String user = "user";
         String password = "password";

         Class.forName(driver);
         Connection conn = DriverManager.getConnection(url,user,password);

         return conn;
     }
}

DAO:
public class RegistrationDAO
{
    public static void addOrganization(long OrganizationId, String organizationName, long countryId) throws ClassNotFoundException, SQLException
    {
        Connection conn = DatabaseConnection.initializeDatabase();

        String query = "insert into organization(OrganizationId, organizationName, countryId) values(?,?,?)";

        try
        {
            PreparedStatement prestmt = conn.prepareStatement(query);

            prestmt.setLong(1, OrganizationId);
            prestmt.setString(2, organizationName);
            prestmt.setLong(3, countryId);

            System.out.println("Organization Added Successfully in my_lportal Database !!");

            prestmt.executeUpdate();
        }
        catch (SQLException e)
        {
            e.printStackTrace();
        }
    }
}

Controller:
@ProcessAction(name = "addOrganization")
        public void addOrganization(ActionRequest actionRequest, ActionResponse actionResponse) throws IOException, PortletException
        {
            ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY);

            long UserId = themeDisplay.getUserId();
            String organizationName = ParamUtil.getString(actionRequest, "organizationName");
            String country = ParamUtil.getString(actionRequest, "country");
            String type = "organization";
            long countryId = ParamUtil.getLong(actionRequest, "countryId");
            long statusId = ParamUtil.getLong(actionRequest, "statusId");

            try
            {      // For storing in lportal(default)

                Organization organization = OrganizationLocalServiceUtil.addOrganization
                                            (
                                                UserId, 0, organizationName, type, 0,
                                                countryId, 12017, null, false, null
                                            );
                _log.info("Organization Added Successfully !!");

                   // For storing in my database
                long OrganizationId =  organization.getOrganizationId();

                RegistrationDAO.addOrganization(OrganizationId, organizationName, countryId);
                _log.info("Organization Added Successfully in my_lportal Database !!");

            }
            catch (Exception ex)
            {
                ex.printStackTrace();
            }
        }

A: First of all your question is very confusing. So you want to use a PostgreSQL for your Liferay Portal right?
You configured everything correctly and downloaded the driver from https://jdbc.postgresql.org/download/postgresql-42.4.1.jar?
Just put this driver in tomcat/lib not ext (maybe it is not configured to load). Restart the server.
Please provide the complete startup log output.
EDIT1:
Ok now I see what is wrong. Your gradle file need to compileInclude instead of compile the lib. The scope compile is only for compilation phase but you also need the library during runtime in the portlet so thats why you need to compileInclude it.
OSGI is a bit tricky when it comes to dependencies because you will get errors after this compileInclude. The portlet will tell you that there are missing dependencies. You can put them to an ignore list.
build.gradle - add line
compileInclude group: 'org.postgresql', name: 'postgresql', version: '42.4.1'

You need to put some packages to not import them in the bnd.bnd file. Just copy the Import-Package part. It needs to be copied in exact this way!
Bundle-Name: test-redirect-jsp
Bundle-SymbolicName: test.redirect.jsp
Bundle-Version: 1.0.0
Export-Package: test.redirect.jsp.constants
Import-Package:\
!com.sun.jna*,\
!org.osgi.service.jdbc*,\
!waffle.windows.auth*,\
*

The driver class should now be available during runtime.
MyTest
public class StaticTest {

    public static void test() {
        String driver = "org.postgresql.Driver";
        try {
            Class c = Class.forName(driver);
            System.out.println(c.getName());
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

Called
@ProcessAction(name = "addOrganization")
public void addOrganization(ActionRequest actionRequest, ActionResponse actionResponse)
        throws IOException, PortletException {
    StaticTest.test();

}

Please be adviced that my and your solution are very dirty. This is not how it would be done and recommended. The clean way would be setup a second datasource via properties and build your external entities via service builder.
Again - please refer to https://help.liferay.com/hc/en-us/articles/360018160911-Connecting-Service-Builder-to-External-Data-Sources

A: At start up liferay provides the option using which we can change liferay database. Following is the steps for the same.
1.1) Create a database in postgresql(like lportal).
1.2) Select the change database option at liferay start up.
1.3) Enter your databse url,username and password.
You can create a file with name portal-ext.properties in Liferay root folder(check attached screen shot).
Add following database configuration.
Postgresql
jdbc.default.driverClassName= enter driver
jdbc.default.url= enter URL
jdbc.default.username= enter UserName
jdbc.default.password= enter Password


text:
Q: How can I get Phone wallpaper in Android? I am working on an Android application. How can I get Phone wallpaper in Android? Please help me. Give me the sample code example.

A: You need to use WallpaperManager which, among other things mentioned in the documentation, allows you to get the current wallpaper.
The following snippet will get the current wallpaper (or the system default if no wallpaper is set).
final WallpaperManager wallpaperManager = WallpaperManager.getInstance(this);
final Drawable wallpaperDrawable = wallpaperManager.getDrawable();

A: final WallpaperManager wallpaperManager = WallpaperManager.getInstance(this);
final Drawable wallpaperDrawable = wallpaperManager.getDrawable();

A: From your activity call
this.getWallpaper();

A: Wallpaper can be get using getDrawable() of Wallpaper class How can I get Phone wallpaper in Android?

redpajama_set_name: RedPajamaStackExchange


text:
Q: build nginx with full webdav support (nginx-dav-ext-module) OS: Debian Squeeze
nginx: v.0.7.67

configure arguments: --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-client-body-temp-path=/var/lib/nginx/body --http-fastcgi-temp-path=/var/lib/nginx/fastcgi --http-log-path=/var/log/nginx/access.log --http-proxy-temp-path=/var/lib/nginx/proxy --lock-path=/var/lock/nginx.lock --pid-path=/var/run/nginx.pid --with-debug --with-http_dav_module --with-http_flv_module --with-http_geoip_module --with-http_gzip_static_module --with-http_realip_module --with-http_stub_status_module --with-http_ssl_module --with-http_sub_module --with-ipv6 --with-mail --with-mail_ssl_module --add-module=/home/thijs/nginx/nginx-0.7.67/modules/nginx-upstream-fair

And I want to patch this installation with nginx-dav-ext-module for full webdav support.
Here's how I tried to do it (with no success so far):

*

*get the sources to some folder in my home dir: apt-get source nginx

*download nginx-dav-ext-module unpack and place it into nginx-0.7.67/modules folder

*add:  --add-module=/full_path_to_source_folder/nginx-0.7.67/modules/nginx-dav-ext-module \ to  debian/rules file

*apt-get build-dep nginx

*dpkg-buildpackage

*dpkg -i nginx-dbg_0.7.67-3+squeeze3_amd64.deb

*and finally start nginx, but nginx -V gives me the same configure arguments as before adding nginx-dav-ext-module (info above)

What am I missing?
Any suggestions appreciated.


text:
Q: Filter Facebook profile pictures retrieved using Facepile I've implemented Facepile in my website and it works perfectly. It just displays the profile pictures of users who have liked my page. Now, I want to display the profile pictures of users from a particular area (Say India or Chennai). In other words, I just want to filter the profile pictures based on the location. Is this possible?

A: No, you can't filter users in facepile, you can't event get list of fanpage fan using API.
https://developers.facebook.com/docs/reference/plugins/facepile/


text:
Q: Group entries per week where each column got specific date validation I am trying to group tickets per week in a year when data field X are between that week. The final result should be something like Week,Datefield1,Datefield2..
What I reached so far:
DECLARE @YearStartDate datetime
SET @YearStartDate = '2016-01-04 00:00:00.000'
DECLARE @YearEndDate datetime
SET @YearEndDate = '2016-04-24 00:00:00.000'

SELECT
Year(T.CreateDate) as 'Year',
'Week ' + cast(datepart(wk, CreateDate) as varchar(2)) as 'Week',
Sum(CASE WHEN CreateDate BETWEEN @YearStartDate and @YearEndDate
    THEN 1 Else 0 End) 'Created'
FROM mytable AS T
GROUP BY Year(T.CreateDate),datepart(wk,T.CreateDate)
ORDER BY Year(T.CreateDate),datepart(wk, T.CreateDate)

Result:
Year        Week    Created
----------- ------- -----------
2016        Week 1      0
2016        Week 2      5
2016        Week 3      3
2016        Week 4      2

Goal:
Year        Week    Created    Schuduled    Closed
----------- ------- ----------- ----------- -----------
2016        Week 1       0          0          0
2016        Week 2       5          3          2
2016        Week 3       3          2          2
2016        Week 4       2          2          0

Suggestion?
SELECT
Year(..) as 'Year',
'Week ' + cast(datepart(wk, ...) as varchar(2)) as 'Week',
Sum(CASE WHEN CreateDate BETWEEN @YearStartDate and @YearEndDate
    THEN 1 Else 0 End) 'Created'
Sum(CASE WHEN ScheduledDate BETWEEN @YearStartDate and @YearEndDate
    THEN 1 Else 0 End) 'Scheduled'
Sum(CASE WHEN ClosedDate BETWEEN @YearStartDate and @YearEndDate
    THEN 1 Else 0 End) 'Closed'
FROM mytable AS T
GROUP BY Year(...)
ORDER BY Year(...)

Constraints:
I can count the entries per week for one datafield but for several datafields (created,scheduled,pending,closed) I think I need to change the logic. Maybe create a inner join or left join against the same table.
I was wondering if you could give me some guidance on finding the right path. Thanks for taking the time to help me.
All the best.

A: Right, join on other similar SELECTs for scheduled and closed should work. Something as
DECLARE @YearStartDate datetime = '2016-01-04 00:00:00.000';
DECLARE @YearEndDate datetime = '2016-04-24 00:00:00.000';

SELECT CLR.*, SCH.Schuduled, CLS.Closed FROM
    (SELECT
        Year(T.CreateDate) as 'Year',
        'Week ' + cast(datepart(wk, CreateDate) as varchar(2)) as 'Week',
        Sum(CASE WHEN CreateDate BETWEEN @YearStartDate and @YearEndDate THEN 1 Else 0 End) 'Created'
    FROM mytable AS T
    GROUP BY Year(T.CreateDate),datepart(wk,T.CreateDate)
    ) CRT

    JOIN
    (SELECT
        Year(T.ScheduleDate) as 'Year',
        'Week ' + cast(datepart(wk, ScheduleDate) as varchar(2)) as 'Week',
        Sum(CASE WHEN ScheduleDate BETWEEN @YearStartDate and @YearEndDate THEN 1 Else 0 End) 'Schuduled'
    FROM mytable AS T
    GROUP BY Year(T.ScheduleDate),datepart(wk,T.ScheduleDate)
    ) SCH
    ON CRT.Year = SCH.Year
        AND CRT.Week = SCH.Week

    JOIN
    (SELECT
        Year(T.ClosedDate) as 'Year',
        'Week ' + cast(datepart(wk, ClosedDate) as varchar(2)) as 'Week',
        Sum(CASE WHEN ClosedDate BETWEEN ClosedDate and @YearEndDate THEN 1 Else 0 End) 'Closed'
    FROM mytable AS T
    GROUP BY Year(T.ClosedDate),datepart(wk,T.ClosedDate)
    ) CLS
    ON CRT.Year = CLS.Year
        AND CRT.Week = CLS.Week
ORDER BY Year, Week

A: You have three different date columns.  One method would pre-aggregation along the dimensions and then use full outer join.  Alternatively, you can use union all and aggregation:
SELECT Year(dte) as [Year],
       'Week ' + datename(wk, dte) as [Week],
       Sum(Created) as Created,
       Sum(Scheduled) as Scheduled,
       Sum(Closed) as Closed
FROM ((SELECT createddate as dte, 1 as created, 0 as schedule, 0 as closed
       FROM mytable
      ) UNION ALL
      (SELECT scheduleddate as dte, 0 as created, 1 as schedule, 0 as closed
       FROM mytable
      ) UNION ALL
      (SELECT closeddate as date, 1 as created, 0 as schedule, 0 as closed
       FROM mytable
      )
     ) t
GROUP BY Year(date), datename(wk, dte)
ORDER BY Year(date), datename(wk, dte);

I would encourage a couple of things:

*

*Do not use single quotes for column aliases.  Only use single quotes for string and date names.

*Do not use reserved works such as "year" for column or table names.

Also note the use of datename().  This returns a string so no conversion is needed.


text:
Q: (inter portlet communication) IPC in liferay 6.0.5 and JSF1.2 We are trying to implement a portlet communication that will be able to simulate the classical redirect, but without success for now.
This looks to be a common question in the portlet world, but there is a lack of documentation/howtos/tutorials on specific portal implementations.
Does anyone have a positive experience achieving portlet communication in this environment:
 - liferay 6.0.5
 - JSF1.2 - richfaces 3.3.x implementation

A: IPC Public render parameters get passed to other portlets in the RENDER phase, IPC events get sent in the ACTION phase and passed to the other portlets in the EVENT phase. If you use JSF and don't reload the page then neither of these are possible so Portlet communication via IPC is not an option.
It is however possible to have them communicate using Javascript purely on the client side. The responsible way to manage this is to get each JS library to use the portlet namespace to prevent method and variable collision, but in a controlled environment (ie when you write all custom portlets running on the Portal server) you can omit this.
The other way is to have all communicating portlets to use the Portal server as a middleware container, and they all have to write data to the server and get updates by polling the server. This is not as clean or easy as talking JS to each other directly on the client.


text:
Q: Why $\hat{\mu}\in L^2(\mathbb{R}^n)$ implies $\mu$ absolutely continuous? Let $\mu$ be a compactly supported probability measure on $\mathbb{R}^n$.  Suppose that $\hat{\mu}\in L^2(\mathbb{R}^n)$, then $\mu$ must be absolutely continuous with respect the Lebesgue measure. How to prove ?
The Fourier transform $\hat{\mu}$ is given by
 $$
 \hat{\mu}(\xi)=\int e^{-2\pi i\langle\xi,x\rangle}d\mu(x).
 $$
Thank you and sorry if my English wasn't correct.

A: Hint
Prove that $\mu$ has a $L^2$ Lebesgue density.
Then conclusion is trivial since
$$\mu(E) = \int_E f_\mu \ \mathrm d\lambda$$

A: If you provide the definition of absolutely continuous measures, you will be able to prove it.


text:
Q: how to add multiple reference lines in SAPUI5 vizframe? My vizframe has multiple Measures. I want to have 1 reference line for each measure.
How can I add more than 1 reference line to the chart using setVizProperties?
current code which adding 1 reference line
var oChart = sap.ui.getCore().byId("mainPageView--idVizFrame");
oChart.setVizProperties({
    plotArea: {
        dataLabel: {
            visible: true
        },
        referenceLine: {
            line: {
                valueAxis: [{
                    value: value1,
                    visible: show,
                    size: 1,
                    type: "dotted",
                    label: {
                        text: "Target:" + value1 + strrange,
                        visible: show
                    }
                }]
            }
        }

    }
});

A: the following code solves this issue

var RefLines2 = [];
var TargetValues = [40, 50, 60, 70];
for (var i = 0; i < TargetValues.length; i++) {

    RefLines2.push({

            value: TargetValues[i],
            visible: show,
            size: 1,
            type: "dotted",
            label: {
                text: "Target:" + TargetValues[i] + strrange,
                visible: show
            }

        }

    );
}

oChart.setVizProperties({
    plotArea: {
        dataLabel: {
            visible: true
        },
        referenceLine: {
            line: {
                valueAxis: RefLines2
            }

        }

    }
});


text:
Q: How to refresh src tag for same URL with different images? Hi am using an Angular UI screen and having an Img tag and applying same URL for Src, but each time the image will be different but Url will be the same, now my issue is the Img tag can't refersh the Image. it only get refreshed on page load. how can i refresh img tag with same Url but different Image.

A: i got the solution, i have used MyImage.src = "http://localhost/image.jpg?" + new Date().getTime(); to refresh Src for same URL.

A: You should use the ng-src directive.
An example could be:

Angular


text:
Q: Guardar html en mysql por formulario Hola estoy haciendo un proyecto el cual requiere que guarde HTML insertado en una caja de texto dentro de un formulario, el envió del formulario se realiza por medio de ajax y el guardado lo relaizo con php, ya he intentado con esto:
function htmlEncode(value)
{
  return $('<div/>').text(value).html();
}

htmlStr = htmlEncode($('.caja').val());

pero no funciona por los caracteres especiales "&", que cortan la cadena, alguien tiene alguna sugerencia para realizar la operación de guardado a bd y recuperar de bd con php? gracias por su ayuda de antemano.

A: yo te recomiendo que codifiques tu formulario en base64 antes de enviarlo, así:
function htmlEncode(value)
{
  return window.btoa(value);
}

htmlStr = htmlEncode($('.caja').val());

Y una vez recibido en tu archivo php lo decodificas así:
$htmlStr = base64_decode($_POST['htmlStr']);

Saludos.


text:
Q: How to get rid of some spacing when website switches to mobile view I'm trying to create a landing page where people would click on which website they want to go to. I'm new to coding and need some help with the mobile version of the website. There is some spacing that I want to get rid of but I'm not sure how to go about this.
Seen here, I'm trying to get rid of the spacing in between the image blocks on the mobile version. Mobile version of site
Thanks!
CSS
 body {
      width:100%;
      height: 100%;
      margin: 0;
    }

    .flex {
   display:flex;
   max-width: 80%;
    }
    .flex div{
      flex:1;
      padding:20px;
    }

    img{
      margin:30% auto 30%;
      width:100%;

@media only screen and (max-width:620px) {
  .flex, .flex div, img {
    display:inline;
    width:100%;
    float:left;
  }
}

HTML
<!DOCTYPE html>

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

A: You should provide us more info. But to get rid of all the spacing you could try this for mobile:
@media only screen and (max-width:620px) {
  .flex, .flex div, img {
    display:inline;
    width:100%;
    float:left;
    max-width: 100%;
    padding: 0;
    margin: 0;
  }

A: A few things needed to change:

*

*kill the float that you have in the media query. You're using flex, so

*Add the reset to both html and body.

*In the media query use justify-content and flex-direction. Set the max-width to 100%
the TL:DR of what was wrong was that you we're floating elements on a media query, and giving them a width of less than 100% which is why they were not centered on mobile.

    html, body {
      width:100%;
      height: 100%;
      margin: 0;
      padding: 0;
    }
    .flex {
   display:flex;
   max-width: 80%;
    }
    .flex div{
      flex:1;
      padding:20px;
    }
    img{
      margin:30% auto 30%;
      width:100%;
      -moz-transition: all 0.3s;
      -webkit-transition: all 0.3s;
      transition: all 0.3s;
    }
    img:hover {
      -moz-transform: scale(1.1);
      -webkit-transform: scale(1.1);
      transform: scale(1.1);
    }

@media only screen and (max-width:620px) {
  .flex {
    justify-content: center;
    flex-direction: column;
    max-width:100%;
  }
}

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

Hope this helps.


text:
Q: Make $(z^2+a^2)(z^2+b^2)(z^2+c^2)$ into complete square form? How can I make $(z^2+a^2)(z^2+b^2)(z^2+c^2)$ into complete square form?
Consider $z$ to be complex number, $a$, $b$, and $c$ to be constants.
What I tried: I have expanded the polynomial but I don't have any clue about making it into the complete square form, other than
$$x+ax = \left(x + \frac {a}{2}\right)^2 - \frac {a^2}{4}$$
If not a complete square, is it possible to write the above polynomial in any reduced form?

A: A sixth degree polynomial that can be written as $P^2$ can have at most three distinct zeros in the complex plane, specifically the zeros of $P$. Your polynomial has zeros $\pm ia, \pm ib, \pm ic$, which are all distinct in the generic case.
So the answer is no, this cannot be written as a complete square.
The only "more reduced" form that I can think of is
$$
(z+ia)(z-ia)(z+ib)(z-ib)(z+ic)(z-ic)
$$


text:
Q: Attached icon to radcomobox Does someone might know how can I attached icon to RadComobobox here is my code:
I hope that someone can give me direction or example that working....thanks
<telerik:RadComboBox ID="rcbJobType" runat="server" EmptyMessage="Select Job Type" Width="248px">
                                  <Items>
                                  <telerik:RadComboBoxItem Text="Select Job Type" Value="Select Job Type" />
                                  <telerik:RadComboBoxItem Text="Long Term" Value="Long Term" />
                                  <telerik:RadComboBoxItem Text="Short Term" Value="Short Term" />
                                  <telerik:RadComboBoxItem Text="Last Minute" Value="Last Minute" />
                                  </Items>
</telerik:RadComboBox>

occurs on pageload
      Protected Sub IconAttached()
                Dim imgDir As New DirectoryInfo(Server.MapPath(Globals.gRootRelativeSecureURL("/Images/Layout/offDuty.png")))
                For Each file As FileInfo In imgDir.GetFiles("*.png")
                    Dim item As New RadComboBoxItem(file.Name.Replace(".png", ""))
                    item.ImageUrl = "Img/" + file.Name
                    rcbEditJobType.Items.Add(item)

                Next
               = "<img src='" + Globals.gRootRelativeSecureURL("/Images/Layout/offDuty.png") + "' border=""0"" align=""absmiddle"">"
    End Sub

A: Please try with the below code snippet.
ASPX
<telerik:RadComboBox runat="server" ID="RadComboBox1">
     <Items>
           <telerik:RadComboBoxItem Text="Select Job Type" Value="Select Job Type" />
           <telerik:RadComboBoxItem Text="Long Term" Value="Long Term" />
           <telerik:RadComboBoxItem Text="Short Term" Value="Short Term" />
           <telerik:RadComboBoxItem Text="Last Minute" Value="Last Minute" />
     </Items>
     <ItemTemplate>
           <div>
                <asp:Image ID="Image1"  runat="server">
                <asp:Label ID="Label1" Text='<%# Eval("Text") %>'  runat="server">
           </div>
     </ItemTemplate>
</telerik:RadComboBox>

ASPX.VB
For Each item As RadComboBoxItem In RadComboBox1.Items
    Dim Image1 As Image = DirectCast(item.FindControl("Image1"), CheckBox)
    Image1.ImageUrl = "Please add image url here"
Next


text:
Q: How do I move all the data from NSMutableArray to NSArray with a key I have an array NSMutableArray. It contained objects from the XML file - @"time". I need to move all records from NSMutableArray with key @"time" to NSArray. This is in order that would be based on the date on the calendar is highlighted markers. How can I implement it?
If I write the code:
NSDictionary *nItem = [rasp objectAtIndex:0]; //here instead of 0, you should put the number of elements in the array, but I do not get ((
NSArray *data = [NSArray arrayWithObjects:[nItem objectForKey:@"time"], nil];

NSMutableArray is allocated only a first date from the array, index 0.

A: You could do something like this.
NSMutableArray* mutable = [NSMutableArray arrayWithCapacity:0];

for(NSDictionary* nItem in rasp)
{
    [mutable addObject:[nItem objectForKey:@"time"]];
}
NSArray *data = [NSArray arrayWithArray:mutable];

Hope it helps!


text:
Q: LSTM: Figuring out the library? I'm using the library https://github.com/cazala/synaptic
I am trying to predict the next value (value X) in the following series:
0 0 0 1 0 0 0 1 0 0 0 X

Which should be a 1.
Here is the code:
const options = {
    peepholes: Layer.connectionType.ALL_TO_ALL,
    hiddenToHidden: false,
    outputToHidden: false,
    outputToGates: false,
    inputToOutput: true,
};
// 1 input, 3 hidden layers (4 nodes per layer), 1 output
const lstm = new Architect.LSTM(1, 4, 4, 4, 1, options);
const trainingArray = [
    {
        input: [0],
        output: [0],
    },
    {
        input: [0],
        output: [0],
    },
    {
        input: [0],
        output: [1],
    },
    {
        input: [1],
        output: [0],
    },
    {
        input: [0],
        output: [0],
    },
    {
        input: [0],
        output: [0],
    },
    {
        input: [0],
        output: [1],
    },
    {
        input: [1],
        output: [0],
    },
];
const trainingOptions = {
    rate: 0.1,
    iterations: 100000,
    error: 0.05,
    cost: null,
    crossValidate: null,
};
let results = lstm.trainer.train(trainingArray, trainingOptions);
console.log(results);
array = [
    0,
    0,
    0,
    1,
    0,
    0,
    0,
    1,
    0,
    0,
    0,
];
results = lstm.activate(array);
console.log(results);

The output in the console:
{ error: 0.049765018466871494, iterations: 673, time: 392 }
[ 0.05010961302724895 ]

I was expecting the result of the activation to be a value closer to 1 than 0 (much closer). I don't know if this is the library of my lack of knowledge with LSTM. Can someone point me in the correct direction?

A: I read through the source code and figured it out.
const synaptic = require('synaptic');

const Architect = synaptic.Architect;
const Layer = synaptic.Layer;

const lstmOptions = {
    peepholes: Layer.connectionType.ALL_TO_ALL,
    hiddenToHidden: false,
    outputToHidden: false,
    outputToGates: false,
    inputToOutput: true,
};
const lstm = new Architect.LSTM(1, 4, 4, 4, 1, lstmOptions);

const trainSet = [
    { input: [0], output: [0.1] },
    { input: [1], output: [0.2] },
    { input: [0], output: [0.3] },
    { input: [1], output: [0.4] },
    { input: [0], output: [0.5] },
];
const trainOptions = {
    rate: 0.2,
    iterations: 10000,
    error: 0.005,
    cost: null,
    crossValidate: null,
};
const trainResults = lstm.trainer.train(trainSet, trainOptions);
console.log(trainResults);

const testResults = [];
testResults[0] = lstm.activate([0]);
testResults[1] = lstm.activate([1]);
testResults[2] = lstm.activate([0]);
testResults[3] = lstm.activate([1]);
testResults[4] = lstm.activate([0]);
console.log(testResults);

Results in:
{ error: 0.004982436660844655, iterations: 2010, time: 384 }
[ [ 0.18288280009908592 ],
  [ 0.2948083898027347 ],
  [ 0.35061782593064206 ],
  [ 0.3900799575806566 ],
  [ 0.49454852760556606 ] ]

Which is accurate.


text:
Q: Rails 2.3.8 form_for partials not generating correct action url Hey, I have a bunch of forms for different controllers all on the same page. This is because theres a bunch of models which stack on each other and this is the best way to edit them.
I'm using partials to include each form into the view, passing locals for the object and url params to be used by form_for
The first (top level) form partial:
- form_for :person, local_assigns[:obj], :url => local_assigns[:url] do |person_form|
  = person_form.error_messages

  %p
    = person_form.label :first_name
    = person_form.text_field :first_name
  %p
    = person_form.label :last_name
    = person_form.text_field :last_name
  %p
    = person_form.submit 'Save'
    - if local_assigns[:obj]
      = link_to 'Destroy', local_assigns[:obj], :confirm => 'Are you sure?', :method => :delete

which is included into the view via
= render :partial => 'person_form', :locals => { :url => { :controller => 'people', :action => 'create' }, :obj => @person }

to create a new Person, and
= render :partial => 'person_form', :locals => { :url => "people/update/#{person.id}", :obj => person }

within this block:
- Person.all.each do |person|

to edit all existing people.
My problem is that every form, excluding the first (top level) person create and edit forms, the action gets set to the current controller.
The form_for partials for all other forms are very similar:
- form_for :day, local_assigns[:obj], local_assigns[:url] do |day_form|
  = day_form.error_messages

  %p
    = day_form.label :effective_date, 'Date'
    = day_form.datetime_select :effective_date
    = day_form.label :person_id
    = day_form.collection_select(:person_id, Person.all, :id, :full_name, { :selected => local_assigns[:ref] ? local_assigns[:ref].id : 1 } )
  %p
    = day_form.submit 'Save'
    - if local_assigns[:obj]
      = link_to 'Destroy', local_assigns[:obj], :confirm => 'Are you sure?', :method => :delete

included via
= render :partial => 'day_form', :locals => { :url => { :controller => 'days', :action => 'create' }, :obj => @day, :ref => person }

for the create form, and
= render :partial => 'day_form', :locals => { :url => "days/update/#{day.id}", :obj => day, :ref => person }

for the edit forms.
The two models, Person and Day, are linked together by Person having many :days and Day belonging to :person. The associations are all setup correctly and working, the problem is with rendering all the forms with different controllers to generate the correct action url.
Any suggestions?
(I'm using haml btw)

A: Your syntax seems a bit weird to me. If pass an actual object to form_for, it automatically figures out where to submit the form to depending on whether it is a new or existing record.
Something like this should do the trick for you:
# In your controller
# Create a new record
@new_person = Person.new
# And pull out all existing records for editing
@all_people = Person.all

# In whatever view is wrapping your form partials
%h1 Create a new person
= render :partial => 'person_form', :locals => { :person => @new_person }

%h1 Or edit any of the existing people
= render :partial => 'person_form', :collection => @all_people, :as => :person

# In your `person_form` partial
form_for person do |person_form|
  ... # your usual code here

In the last line of code, where you call form_for, you pass in an actual object - and the URL to submit the form to is inferred based on whether the record is new (as it is for @new_person) or already exists in the database (as it does for each person in @all_people).
Does that make sense? Have I understood the problem correctly?

A: If Person and Day are specified as resources in your routes, form_for can infer the correct controller and action from the object.  For example...
In your person partial:
- form_for @person do |f|
  = f.error_messages
  = # ...etc...

In your day partial (where Person has_many Days):
- form_for [@person, @day] do |f|
  = f.error_messages
  = # ...etc...


text:
Q: How to signup to run a code after the name/method has been defined using jQuery? I am trying to run a code but I get
$.uniform is undefined
[Break on this error] $.uniform.restore("#f_variedbyoperator");

How can I use jQuery, to detect if .uniform has been defined? And to signup the code to run after that.

A: The same way you'd test any other property:

*

*$.hasOwnProperty('uniform') (true if it is defined), or

*typeof $.uniform === 'undefined' (true if it is not defined), or

*!!$.uniform (true if it is a truthy value - anything other than undefined, null, 0, false, or '' - the empty string)

What do you mean "signup the code to run?"

var i = setInterval(function ()
{
    if ($.uniform)
    {
        clearInterval(i);
        $.uniform.restore("#f_variedbyoperator");
    }
}, 1000); // check for $.uniform every 1000 ms

A: If all you want to do is check that an element exists, try:
if($('element').length)
{
  // exists!
}


text:
Q: Haskell cant read this double: ".3". Is this a bug? GHC Haskell seems to require a number in front of a decimal point in order to read a Double. Here's the code:
main :: IO ()
main = do
  let d1 = read "0.3" :: Double
      d2 = read ".3"  :: Double
  print d1
  print d2

Running this produces:
0.3
*** Exception: Prelude.read: no parse

Is this a GHC bug or just a major limitation?
(I tried reading ".3" with C, Javascript and MS Excel, and all of these could successfully parse ".3" and understand it as a number.  I think I'm seeing the effects of this issue in other areas of my program, including reading command line arguments with the parseargs package and reading Doubles in html forms with Yesod's MForms.)
Is there a known fix or work-around for this issue?

A: From the Haskell report:
2.5 Numeric Literals

A floating literal must contain digits both before and after the
  decimal point; this ensures that a decimal point cannot be mistaken
  for another use of the dot character

So this is the expected behaviour.

A: I'm accepting iand675's answer, but he left it only as a comment so I'm copying it here:
All of the standard types in Haskell that have Read instances are written to read valid Haskell. If you are using read on inputs that aren't parseable as valid Haskell, you should probably be using something besides read.
Lee's answer was helpful because it defined Haskell's numeric literals.


text:
Q: How to change input of a tensorflow.layers.dense() layer? In tensorflow layers.dense(inputs, units, activation) implements a Multi-Layer Perceptron layer with arbitrary activation function.
Say i defined my dense layer like this:
inputx = tf.placeholder(float, shape=[batch_size, input_size])
dense_layer = tf.layers.dense(inputx, 128, tf.nn.relu)

Now later i want to feed it some other input, say after restoring it from a checkpoint or just merely in the same graph for some reason:
inputx_2 = tf.some_operation(whatever_thisdoes, shape = [batch_size_2, input_size])
inputx = tf.placeholder(float, shape=[batch_size, input_size])
dense_layer = tf.layers.dense(inputx, 128, tf.nn.relu)

How could i now get dense_layer and it's possibly already pretrained weights to apply to inputx_2? (Without assigning input_y the value of inputx_2 if possible?)
Would having a different batch_size (batch_size_2 instead of batch_size) cause any trouble?

A: You can use the 'name' and 'reuse' argument to achieve this behaviour:
inputx = tf.placeholder(float, shape=[batch_size, input_size])
inputx_2 = tf.some_operation(whatever_thisdoes, shape = [batch_size_2, input_size])

dense_layer = tf.layers.dense(inputx, 128, tf.nn.relu, name='dense_layer')
dense_layer2 = tf.layers.dense(inputx_2, 128, tf.nn.relu, name='dense_layer', reuse=True)

Both dense_layer and dense_layer2 share weights thanks to the 'reuse' attribute, but dense_layer is applied to input_x and dense_layer2 to inputx_2.

Would having a different batch_size (batch_size_2 instead of batch_size) cause any trouble?

No. You can verify this easily:
with tf.Session() as sess:
    out = dense_layer.eval({inputx: np.ones([batch_size, input_size])})
    out2 = dense_layer2.eval({inputx_2: np.ones([batch_size_2, input_size])})
    assert np.array_equal(out[0,:], out2[0,:])

I advise you to create a forward pass function to easily reproduce this behaviour for all your models, for example:
def forward_pass(x, name='Model', reuse=False):
     with tf.variable_scope(name, reuse=reuse):
         x = tf.some_ops(x, ...)
         ...
     return x

You can then pass any tensor to forward pass, in your case:
 out = forward_pass(inputx)
 out2 = forward_pass(inputx_2, reuse=True)


text:
Q: WordPress: is it a good idea to improve meta query performance by adding tax query? I'm aware that using taxonomies over metadata is preferred when it comes to posts grouping. In simple words this and this are saying  "use meta for unique data and taxonomy for repeating data(the one which groups posts)".
But I'm wondering if it is possible to improve meta query performance by introducing a taxonomy that will represent different ranges of that meta?
Let's suppose I have a shop with post type Products. Each Product has Price meta. I have millions of rows in the database meta table.
What if I'll add a Price Range taxonomy which will be used on front-end filters? Price Range will be like "1-100$", "100-1000$", etc. User clicks on "100-1000$" + sort by Price. This way I'll query posts tagged by "100-1000$" and only after that will sort them by Price meta. Will it increase query performance?
And how could it be implemented in case the user is allowed to input "from" and "to" Price? It is probably a good idea to use the approach above and just to add taxonomy meta for Price Range? This will look like this:
- User selects "90-900$"
- Fetch all the Price Range terms which match that range. Ie. "1-100" and "100-1000"
- Query posts that are in  "1-100" and "100-1000" Price Range(terms) and set meta value Price as >90 and <900
Will it increase performance too? This approach requires 2 queries : get terms(filtered by term meta), get posts.
I have no chance to check that with a really huge database as all my projects are not so big. But I'm still interested if any of my approaches will work for big sites?
Edited (1): I'm attaching PHP and SQL
Query by meta only:
new WP_Query([
    'post_type' => 'my_product',
    'meta_query' => [
        [
            'key'     => 'price',
            'value'   => 90,
            'compare' => '>=',
            'type'    => 'NUMERIC'
        ],
        [
            'key'     => 'price',
            'value'   => 900,
            'compare' => '<=',
            'type'    => 'NUMERIC'
        ]
    ]
]);

EXPLAIN SELECT  SQL_CALC_FOUND_ROWS wp_posts.ID
    FROM  wp_posts
    INNER JOIN  wp_postmeta  ON ( wp_posts.ID = wp_postmeta.post_id )
    INNER JOIN  wp_postmeta AS mt1  ON ( wp_posts.ID = mt1.post_id )
    WHERE  1=1
      AND  ( ( wp_postmeta.meta_key = 'price'
                      AND  CAST(wp_postmeta.meta_value AS SIGNED) >= '90' )
              AND  ( mt1.meta_key = 'price'
                      AND  CAST(mt1.meta_value AS SIGNED) <= '900' )
           )
      AND  wp_posts.post_type = 'my_product'
      AND  (   wp_posts.post_status = 'publish'
           OR  wp_posts.post_status = 'acf-disabled'
           OR  wp_posts.post_author = 1 AND  wp_posts.post_status = 'private'
           )
    GROUP BY  wp_posts.ID
    ORDER BY  wp_posts.post_date DESC
    LIMIT  0, 10

1   SIMPLE  wp_postmeta ref     post_id,meta_key    meta_key    767 const   1   Using where; Using temporary; Using filesort
1   SIMPLE  mt1         ref     post_id,meta_key    meta_key    767 const   1   Using where
1   SIMPLE  wp_posts    eq_ref  PRIMARY,...         PRIMARY       8 loc.own-acf-plugin.wp_postmeta.post_id  1   Using where

Query by tax and meta:
new WP_Query([
    'post_type' => 'my_product',
    'meta_query' => [
        [
            'key'     => 'price',
            'value'   => 90,
            'compare' => '>=',
            'type'    => 'NUMERIC'
        ],
        [
            'key'     => 'price',
            'value'   => 900,
            'compare' => '<=',
            'type'    => 'NUMERIC'
        ]
    ],
    'tax_query' => [
        [
            'taxonomy' => 'category',
            'field'    => 'slug',
            'terms'    => [ '0-100', '100-1000' ]
        ]
    ]
])

EXPLAIN SELECT  SQL_CALC_FOUND_ROWS wp_posts.ID
    FROM  wp_posts
    LEFT JOIN  wp_term_relationships  ON (wp_posts.ID = wp_term_relationships.object_id)
    INNER JOIN  wp_postmeta  ON ( wp_posts.ID = wp_postmeta.post_id )
    INNER JOIN  wp_postmeta AS mt1  ON ( wp_posts.ID = mt1.post_id )
    WHERE  1=1
      AND  ( wp_term_relationships.term_taxonomy_id IN (1,2) )
      AND  ( ( wp_postmeta.meta_key = 'price'
                      AND  CAST(wp_postmeta.meta_value AS SIGNED) >= '90' )
              AND  ( mt1.meta_key = 'price'
                      AND  CAST(mt1.meta_value AS SIGNED) <= '900' )
           )
      AND  wp_posts.post_type = 'my_product'
      AND  (   wp_posts.post_status = 'publish'
           OR  wp_posts.post_status = 'acf-disabled'
           OR  wp_posts.post_author = 1 AND  wp_posts.post_status = 'private'
           )
    GROUP BY  wp_posts.ID
    ORDER BY  wp_posts.post_date DESC
    LIMIT  0, 10

1   SIMPLE  wp_term_relationships   index   PRIMARY,term_taxonomy_id    PRIMARY 16
    NULL
    1   Using where; Using index; Using temporary; Using f...
1   SIMPLE  wp_postmeta             ref     post_id,meta_key
   meta_key 767 const   1   Using where
1   SIMPLE  mt1                     ref     post_id,meta_key    meta_key    767 const   1   Using where
1   SIMPLE  wp_posts                eq_ref  PRIMARY,type_status_date,post_author    PRIMARY 8   loc.own-acf-plugin.wp_term_relationships.object_id  1   Using where

A: The following issues are causing poor performance.  (I don't know which of these can be improved in WP.)

*

*OR is hard to optimize

*Two JOINs to wp_postmeta.  Can that be fixed by making it JOIN only once and do a BETWEEN..AND..?

*Adding an extra JOIN (to a taxonomy) probably slows it down.

*EAV schema pattern sucks anyway.

*WP's EAV schema has inefficient indexes.  See http://mysql.rjweb.org/doc.php/index_cookbook_mysql#speeding_up_wp_postmeta

*SQL_CALC_FOUND_ROWS costs something.  In particular, it can't quit after finding the desired 10 (the LIMIT).

*The GROUP BY and ORDER BY are different, thereby necessitating an extra sort.  Changing both to ID would fix this.

Even if your one addition helps, it won't be enough to counteract the other 6 problems.
Perhaps the biggest fix would be to have a numeric column called price (and suitably indexed) in wp_posts.  But that is quite alien to the WP schema philosophy.


text:
Q: Add or remove items from comma separated list I'm having some issues adding and/or removing items from a comma separated list. I'm using the <select> form field to choose what items to add and/or remove.
<select name="choices[]" multiple>
    <option value="1">Option 1</option>
    <option value="2">Option 2</option>
    <option value="3">Option 3</option>
    <option value="4">Option 4</option>
    <option value="5">Option 5</option>
    <option value="6">Option 6</option>
</select>

// explode list from database (choices column)
$array = explode(',', $row->choices);

// loop through html select options
foreach(Input::get('choices') as $value)
{
    // add selected items
    if($value && !in_array($value, $array))
    {
        $array[] = $value;
    }

    // remove deselected items
    if(!$value && in_array($value, $array))
    {
        $index = array_search($value, $array);
        unset($array[$index]);
    }
}

// re-delimit list; update database
$row->choices = trim(implode(',', $array), ',');

The function to add items to the list works as intended. However, when deselecting items, it does not remove them from the list.
Any ideas?

A: When you loop over Input::get('choices'), that array only gives you the user-selected items (which you'd have seen had you printed it out). Input::get doesn't know what possible values were in your HTML; it only knows what values were submitted via HTTP GET.
So, your checking for !$value does nothing — unselected values simply won't be handled at all. If the unselected values started off in the database then they will remain there.
Wouldn't it be better to start off with an empty $array? Then just copy the elements of Input::get('choices') into it? Then store that in the database.

A: Values which are not selected will not be present in Input::get('choices'), so if you select Option 2 and Option 3, Input::get('choices') will contain only them: ["2", "3"]. All you have to do is join and save values from request:
$choices = join(',', Input::get('choices'));
$row->choices = $choices;
$row->save();


text:
Q: Changing Chrome's text zoom when connected to an external monitor I have a laptop with a rather small builtin monitor, making it very hard to read stuff unless the chrome text zoom level is increased to 125%.
One of the external monitors that I connect the laptop to has a low resolution, so 125% zoom is actually not a good setting for that monitor, and I need to use 100% whenever I'm connected to it.
Is there a chrome setting or extension that switches the zoom level according to the resolution and screen size of the monitor I'm plugged into? I would like to just use 125% zoom whenever I'm not connected to an external monitor, and 100% when I am.

A: As far as I'm aware, there isn't a built-in way to do that. There might be an extension, which would require more research though.
I know that you can create multiple profiles in Chrome, so maybe you could use one profile for when you have two monitors and one profile for when you have a single monitor. You might need to make a second Google account for that though, but you can still log in with your normal accounts for everything else. You might even be able to transfer all your passwords and accounts between profiles which could make things easier.
If any of that works, let me know! Hope this helped!


text:
Q: Can one prove $\int^b_a f(t) \ dt = - \int^a_b f(t) \ dt$ ? Similarly can one prove $\int^a_a f(t) \ dt = 0$ ? Is equality only by definition in both? Can one prove $$\int^b_a f(t) \ dt = - \int^a_b f(t) \ dt$$ ? Similarly can one prove $$\int^a_a f(t) \ dt = 0$$ ? Is equality only by definition in both?
I've learned that $\int^b_a f(t) \ dt$ represent the equal values of the lower and upper integrals (supremum and infimum with respect to lower and upper sums of partitions). Also a partition is defined as follows: $$a = x_0 < x_1 < ... < x_n = b$$, which imply $a < b$.
So how does one make any sense of the equalities above ? Can one prove them by means of theory (please show me how), or why have people chosen these definitions ?

A: Alternatively, if you use Riemann sums,
$$\int_a^b f(x) dx = \lim_{N \to \infty} \frac{b-a}{N}\sum_{k=0}^{N-1} f\left(a+k \frac{b-a}{N}\right),$$
then swapping $a$ and $b$ reverseing the order of the sum using $k=N-j$, you will get the same expression but with a minus sign (up to a small error term that goes away in the limit).

A: Notice that $$\int_a^b f(t)dt+\int_b^c f(t) dt=\int_a^c f(t) dt $$ thus if $c=a$ rigth hand side become zero and we are done.
$$\int_a ^a f(t)dt$$ being zero is clear from many aspect.

A: Let $F(x)=\int f(x)dx$ (Indefinite)
then your first equation is $F(b)-F(a)$ (Arbitrary constant gets cancelled).
I assume you can carry on from here. And those partitions need are true even if inequalities don't hold but we like to define it that way as integral from a to b represents area under curve from a to b. Just google geometrical significance of integral.


text:
Q: Chainsaw log format pattern syntax We have a log4j file that has the following pattern:
@|%d{yyyy-MM-dd HH:mm:ss.SSS}|%X{Machine}|%X{CorrelationId}|%X{Sender}|%X{Receiver}|%-5p|%X{Runtime}|%X{ClientUser}|%c|%M|%L|%m%n

I created a LogFilePatternReceiver with the following pattern:
@|TIMESTAMP|PROP(MACHINE)|PROP(CORRELATIONID)|PROP(SENDER)|PROP(RECEIVER)|LEVEL|PROP(RUNTIME)|PROP(CLIENTUSER)|CLASS|METHOD|LINE|MESSAGE

But when I start that receiver I get an error:
java.lang.IllegalArgumentException: invalid expression:
    at org.apache.log4j.rule.ExpressionRule$PostFixExpressionCompiler.compileExpression(ExpressionRule.java:132)
    at org.apache.log4j.rule.ExpressionRule.getRule(ExpressionRule.java:64)
    at org.apache.log4j.rule.ExpressionRule.getRule(ExpressionRule.java:56)
    at org.apache.log4j.varia.LogFilePatternReceiver.initialize(LogFilePatternReceiver.java:557)
    at org.apache.log4j.varia.LogFilePatternReceiver$1.run(LogFilePatternReceiver.java:801)
    at java.lang.Thread.run(Unknown Source)

regexp is @|(\w+-\w+-\w+ \w+:\w+:\w+.\w+)|(.+?)|(.+?)|(.+?)|(.+?)|(.+?)|(.+?)|(.+?)|(.+?)|(.+?)|(.+?)|(.+)

I don't really see where the error is? Any input? Can I use the "PROP(...)" keyword like that for columns that are non-standard?

A: Yes, you can use the PROP keyword for your own columns..
Can you try the latest developer snapshot of Chainsaw?  It can parse your log4j.xml or log4j.properties configuration containing FileAppender entries and will build a matching Chainsaw config to process that.
Snapshot available here..the new version also has a lot of new features:
http://people.apache.org/~sdeboy
What usually trips people up is timestamp formatting and special characters, but I don't see anything weird here, so see if the latest developer snapshot helps.
Scott


text:
Q: Why opening cmd.exe causes to run 2 processes? Before:

After:

As you can see the number of processes increases by 2 from 103 to 105 processes! Why should it increase by 2? I only ran cmd.exe which is by far one process!

A: conhost.exe is also started when you run cmd.exe. Check this MS-thread for more info.

A: When you run cmd.exe, a second process called conhost.exe is always started. This is why you see 2 more processes. This conhost.exe was added in Windows 7, to increase security:

In previous versions of Windows, all GUI activity on behalf of non-GUI
  applications that ran on the desktop (console applications) was
  brokered by the system process CSRSS.exe.  When a console application
  wanted to receive characters, it called one of a small set of "Console
  APIs" implemented in Kernel32.dll, and Kernel32 made an LPC call to
  CSRSS.  CSRSS checked the input queue associated with the console
  window and returned the appropriate character-mode input through
  Kernel32 back to the console application.
The problem with this was that even if an application ran in the
  context of a regular user's account, CSRSS.EXE runs under the Local
  System account.  So it was possible under certain circumstances for
  malware to exploit weaknesses in an application in order to execute
  code under the more privileged Local System account in CSRSS.EXE.
  This kind of exploit is known as a "shatter attack" .
This exposure was addressed in Windows 7 and Windows Server 2008 R2 by running the console messaging code in the context of a new process,
  ConHost.exe. ConHost (Console Host) runs in the same security context
  as its associated console application.  Instead of issuing an LPC
  request to CSRSS for message-handling, the request goes to ConHost.
  As a result, any attempts to exploit the message-handing code of the
  application will not result in an automatic escalation of
  privileges.

So calm down, everything is fine with your Windows.


text:
Q: Multiple settings Wordpress Options Page plugin I want to make an Options page with multiple settings for my plugin. I want to use this code as a start: http://codex.wordpress.org/Creating_Options_Pages#Example_.232
<?php
class wctest{
    public function __construct(){
        if(is_admin()){
            add_action('admin_menu', array($this, 'add_plugin_page'));
            add_action('admin_init', array($this, 'page_init'));
        }
    }

    public function add_plugin_page(){
        // This page will be under "Settings"
        add_options_page('Settings Admin', 'Settings', 'manage_options', 'test-setting-admin', array($this, 'create_admin_page'));
    }

    public function create_admin_page(){
    ?>

        <?php screen_icon(); ?>

Settings

        <form method="post" action="options.php">
            <?php
                    // This prints out all hidden setting fields
            settings_fields('test_option_group');
            do_settings_sections('test-setting-admin');
        ?>
            <?php submit_button(); ?>
        </form>

    <?php
    }

    public function page_init(){
        register_setting('test_option_group', 'array_key', array($this, 'check_ID'));

        add_settings_section(
            'setting_section_id',
            'Setting',
            array($this, 'print_section_info'),
            'test-setting-admin'
        );

        add_settings_field(
            'some_id',
            'Some ID(Title)',
            array($this, 'create_an_id_field'),
            'test-setting-admin',
            'setting_section_id'
        );
    }

    public function check_ID($input){
        if(is_numeric($input['some_id'])){
            $mid = $input['some_id'];
            if(get_option('test_some_id') === FALSE){
                add_option('test_some_id', $mid);
            }else{
                update_option('test_some_id', $mid);
            }
        }else{
            $mid = '';
        }
        return $mid;
    }

    public function print_section_info(){
        print 'Enter your setting below:';
    }

    public function create_an_id_field(){
        ?><input type="text" id="input_whatever_unique_id_I_want" name="array_key[some_id]"    value="<?=get_option('test_some_id');?>" /><?php
    }
}

$wctest = new wctest();

Everything works as shown below the code on the page, but I want to add a second setting. How do I add another settings section and a settings field and being able to safe the values? I have been puzzling for half a day now, but no luck.
Could someone help me out please? This is my first plugin and if I understand this part I can do the rest.

A: I just modified the example in the Codex: Creating_Options_Pages#Example_.232. Now it includes a second Settings Field. The sanitization function is simpler to understand and expand. Also changed the names of the variables and added documentation in the code. I think it's easier to follow the logic now. Here it is in full:
<?php
class MySettingsPage
{
    /**
     * Holds the values to be used in the fields callbacks
     */
    private $options;

    /**
     * Start up
     */
    public function __construct()
    {
        add_action( 'admin_menu', array( $this, 'add_plugin_page' ) );
        add_action( 'admin_init', array( $this, 'page_init' ) );
    }

    /**
     * Add options page
     */
    public function add_plugin_page()
    {
        // This page will be under "Settings"
        add_options_page(
            'Settings Admin',
            'My Settings',
            'manage_options',
            'my-setting-admin',
            array( $this, 'create_admin_page' )
        );
    }

    /**
     * Options page callback
     */
    public function create_admin_page()
    {
        // Set class property
        $this->options = get_option( 'my_option_name' );
    ?>

        <?php screen_icon(); ?>

My Settings

        <form method="post" action="options.php">
        <?php
            // This prints out all hidden setting fields
            settings_fields( 'my_option_group' );
            do_settings_sections( 'my-setting-admin' );
            submit_button();
        ?>
        </form>

    <?php
    }

    /**
     * Register and add settings
     */
    public function page_init()
    {
        register_setting(
            'my_option_group', // Option group
            'my_option_name', // Option name
            array( $this, 'sanitize' ) // Sanitize
        );

        add_settings_section(
            'setting_section_id', // ID
            'My Custom Settings', // Title
            array( $this, 'print_section_info' ), // Callback
            'my-setting-admin' // Page
        );

        add_settings_field(
            'id_number', // ID
            'ID Number', // Title
            array( $this, 'id_number_callback' ), // Callback
            'my-setting-admin', // Page
            'setting_section_id' // Section
        );

        add_settings_field(
            'title',
            'Title',
            array( $this, 'title_callback' ),
            'my-setting-admin',
            'setting_section_id'
        );
    }

    /**
     * Sanitize each setting field as needed
     *
     * @param array $input Contains all settings fields as array keys
     */
    public function sanitize( $input )
    {
        $new_input = array();
        if( isset( $input['id_number'] ) )
            $new_input['id_number'] = absint( $input['id_number'] );

        if( isset( $input['title'] ) )
            $new_input['title'] = sanitize_text_field( $input['title'] );

        return $new_input;
    }

    /**
     * Print the Section text
     */
    public function print_section_info()
    {
        print 'Enter your settings below:';
    }

    /**
     * Get the settings option array and print one of its values
     */
    public function id_number_callback()
    {
        printf(
            '<input type="text" id="id_number" name="my_option_name[id_number]" value="%s" />',
            isset( $this->options['id_number'] ) ? esc_attr( $this->options['id_number']) : ''
        );
    }

    /**
     * Get the settings option array and print one of its values
     */
    public function title_callback()
    {
        printf(
            '<input type="text" id="title" name="my_option_name[title]" value="%s" />',
            isset( $this->options['title'] ) ? esc_attr( $this->options['title']) : ''
        );
    }
}

if( is_admin() )
    $my_settings_page = new MySettingsPage();

If you want to add new Settings Sections, just do it and point the desired Settings Fields to the new section.
Pull the information wherever needed using: get_option( 'my_option_name' );.

A: To add additional section you must set the ID parameter, the first one, to something different than the ID of the first setting.
    add_settings_section(
        'setting_section_new', // ID
        'My Custom Settings', // Title
        array( $this, 'print_section_info' ), // Callback
        'my-setting-admin' // Page
    );


text:
Q: How to mock CanCan's "authorize!" method in a controller spec? The simplest way to write specs checking that a controller is authorizing the signed-in current_user to use the said action is to explicitly write two specs checking that a user with permission can run that action, and another cannot. For example:
 # The controller action:

 def some_action
   authorize! :do_this_action, @some_object
 end

 # The spec:

 it "should work when authorized" do
   sign_in @user
   get :some_action
   response.should be_success
 end

 it "should not work when not authorized" do
   sign_in @other_user
   get :some_action
   response.should_not be_success
 end

But this is not great, as it requires a great amount of code (two or more specs) and doesn't actually test directly that the authorization is being checked (do_this_action in the example).
I would like to be able to write a simpler spec, e.g. (an example using 'rr' for mocking)
 it "should check the user can do_this_action" do
   mock(controller).authorize!(:do_this_action, some_object)
   get :some_action
 end

I think this would be shorter and directly test that the authorization check I want to be used is being run. But, I can't figure out how to write the mock. mock(controller) isn't correct, nor does mocking ApplicationController or Ability seem to work.
How do I write this kind of mock?

A: I believe it would be better to test authorization in another spec like ability_spec.rb in order for you to separate their responsibilities. By doing so you won't have to test the same authorization method that you use on different controllers.
heres some other details

A: It turns out the way I was writing above works.. must have had a typo earlier.
So, to check that an authorize! check is invoked in the controller, you just need to write:
 it "should check the user can do_this_action" do
   mock(controller).authorize!(:some_action, some_object)
   get :some_action
 end


text:
Q: Putting points at the bottom right corner of the question I am preparing an exam and want to state the score to the relevant question in the very next line at the bottom right corner of the statement of the question, like [5 points].
I looked at this, which is created in the exam environment. I've already prepared the exam in article class with each question under \begin{enumerate} ...... \end{enumerate}.
Any help in achieving this is much appreciated.


text:
Q: How to disable EditText control during activity load and enable it by user action I have an activity that loads that has multiple EditText controls and a button.  The EditText controls display values from a SQLlite DB.  I want the EditTtext controls to be read-only (not clickable even) when the activity loads and then to become editable/clickable when the user clicks a button.
I've read a bunch of the other threads here and it seems like you can do this a couple different ways.

*

*Disable control in XML and enable in code (user action)

*Disable the control in code (onCreate) and enable in code (user action)

Right now I can't get either way to work.  It seems like if I disable it, I can never enable it again for user input.  And if I enable it, It's always enabled and I can never disable it.
Here is my current code:
XML - This is the control I want disabled until the user does something (clicks button)

        <EditText
            android:layout_width="0dp"
            android:layout_weight="1.5"
            android:layout_height="wrap_content"
            android:cursorVisible="true"
            android:editable="false"
            android:inputType="numberDecimal"
            android:id="@+id/itemPrice"/>
    </TableRow>
    <!-- End Item Price -->

JAVA - This is the code that just clears the form/UI and attempts to enable the 2 EditText fields for user input
//Add item to the inventory.  Enables the EditText control for user intput (name and price)
public void addNewItem(View view)
{
    try
    {
        //Clear the fields on the form/UI
        itemId.setText("");
        itemName.setText("");
        itemPrice.setText("");
        itemDelete.setText("");

        //Enable the controls
        itemName.setEnabled(true);
        itemPrice.setEnabled(true);
        itemName.setFocusable(true);
        itemPrice.setFocusable(true);
        itemName.setClickable(true);
        itemPrice.setClickable(true);
    }
    catch(Exception erMsg)
    {
        erMsg.printStackTrace();
    }
}

I still have setEnabled(true) on each control even though it has never been disabled, but the latest code is just attempting anything to enable it.
I don't want to make this question subjective, but is there a better way if there is priority (XML or Java)?  For instance, if XML sets a field to :focusable:false and Java sets the field setFocusable(true), is there priority?

A: you may set the android:editable dynamically, after the loading is completed, as   android:editable ="true"

A: I'll put the answer here as it seems this question is asked a lot and the answers are never really understood or clear.
This is the way that I did it without using XML
In the onCreate() method, I disabled user input by the following code:
//Disable the itemName control
        itemName.setInputType(InputType.TYPE_NULL);
        itemName.setFocusable(false);

        //Disable the itemPrice control
        itemPrice.setInputType(InputType.TYPE_NULL);
        itemPrice.setFocusable(false);

I enabled the controls after the user clicked a button, but it wasn't done in the actionListener for the button, just a method that is called when the button is clicked.
//Enable the controls
            itemName.setInputType(InputType.TYPE_CLASS_TEXT);
            itemName.setFocusableInTouchMode(true);
            itemName.setFocusable(true);

        itemPrice.setInputType(InputType.TYPE_CLASS_TEXT);
        itemPrice.setFocusableInTouchMode(true);
        itemPrice.setFocusable(true);

This fully works and when the EditText is not enabled for editing, it is still visible (not greyed out when setDisabled(true)


text:
Q: Update already existing columns in table in database in postgresql? Hi I have a task of assigning nick_name to new users, I added a new column and when a new user is getting created, a nick_name is assigned to it, but what should I do for already existing  users (default is not an option here). Every time I do this manually using update statement, Is there a better way to do it?
Thanks

A: The basic sql-command is
update my_table set nick = username where nick is null;

So you can adjust it to fit the nickname to your needs.


text:
Q: The set of inputs x(n) to a system is described with a small superscript T - what is that? I think it means TRANSPOSE, but I can't figure out the need to perform a transpose operation:

Similarly, the set of weights that go with the inputs is written with a small T as well:

There is also some algebraic operation with this T that I don't understand (why is the T interchangeable?):

A: The $T$ is indeed transpose. The reason it used is to define a column vector using less space.
The equality for $y$ is a dot product between two vectors defined as
$$u\cdot v =u^T v$$ which coincides with a matrix vector product (the matrix is $n\times 1$ in this case and a vector $1\times n$). Particularly you have
$$u\cdot v =u^T v= \sum_i u_i v_i =\sum_i  v_i u_i = v^T u =v\cdot u$$


text:
Q: sudo dkms add command issue I am trying to setup my WIFI adapter settings. I have already run command
sudo apt install git build-essential dkms

when i try to do this
sudo dkms add ./rtlwifi_new

that shows me following error
Error! Could not find module source directory.
Directory: /usr/src/.-rtlwifi_new does not exist.

how I can fix this?

A: don't run this command in "rtlwifi_new" directory
so back one directory
cd ..


text:
Q: Getting StringIndexOutOfBoundsException while sending text message to another bluetooth device I am working on an android app where I need to send text over Bluetooth. I have come up with a piece of code to achieve this.My problem is that it crashed after sending the message to the device throwing StringIndexOutOfBoundsException . How can I fix this.My full code is:
package com.example.blueremote;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.UUID;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends Activity {
    private BluetoothAdapter btadapter;
    private BluetoothSocket socket;
    private Button btnSend;
    private ArrayList<BluetoothDevice> foundDevices;
    private ArrayAdapter<BluetoothDevice> aa;
    private Handler handler = new Handler();

    private ListView list;
    private TextView tvmsg;
    private static int DISCOVERY_REQUEST = 1;
    private UUID uuid = UUID.fromString("a60f35f0-b93a-11de-8a39-08002009c666");
    ImageButton up;
    private String address = "D8:50:E6:8A:16:0F";

    private String text = "up";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btadapter = BluetoothAdapter.getDefaultAdapter();
        Intent disc;
        disc = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
        startActivityForResult(disc, DISCOVERY_REQUEST);
        up = (ImageButton) findViewById(R.id.btn_up);

        registerReceiver(discoveryResult, new IntentFilter(
                BluetoothDevice.ACTION_FOUND));
        AsyncTask<Integer, Void, Void> connectTask = new AsyncTask<Integer, Void, Void>() {

            @Override
            protected Void doInBackground(Integer... params) {
                // TODO Auto-generated method stub
                try {
                    Log.v("Main Activity", " AsyncTask started");
                    BluetoothDevice device = btadapter.getRemoteDevice(address);

                    socket = device.createRfcommSocketToServiceRecord(uuid);
                    Log.v("Main Activity", "Socket Created");
                    socket.connect();

                    Log.v("Main Activity", "Socket Connected");
                } catch (IOException e) {
                    Log.d("BLUETOOTH_CLIENT", e.getMessage());
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void result) {
                // Log.v("Main Activity", "Invoking switchUI");
                // switchUI();

            }
        };
        connectTask.execute();
        up.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Log.v("Main Activity", "In up Button");
                // Log.v("Main Activity", "Invoking switchUI");
                switchUI();
            }
        });
    }

    private void switchUI() {
        Log.v("Main Activity", "In SwitchUI Method");

        Log.v("Main Activity", "Invoking sendMessage Method ");
        sendMessage(socket, text);
        Log.v("Main Activity", "Message Sent");

        BluetoothSocketListener bsl = new BluetoothSocketListener(socket,
                handler);
        Thread messageListener = new Thread(bsl);
        messageListener.start();
    }

    private void sendMessage(BluetoothSocket socket, String msg) {
        msg = "UP";
        OutputStream outStream;
        try {
            Log.v("Main Activity", "Inside sendMessage Method ");

            outStream = socket.getOutputStream();
            Log.v("Main Activity", "Outstream:" + outStream);
            byte[] byteString = (msg + " ").getBytes();
            Log.v("Main Activity", "byteString:" + byteString);

            outStream.write(byteString);
            Log.v("Main Activity", "outstream written:");
        } catch (IOException e) {
            Log.d("BLUETOOTH_COMMS", e.getMessage());
        }
    }

    private class MessagePoster implements Runnable {
        private TextView textView;
        private String message;

        public MessagePoster(String message) {
            // this.textView = textView;
            this.message = message;
        }

        public void run() {
            // textView.setText(message);
        }
    }

    private class BluetoothSocketListener implements Runnable {
        private BluetoothSocket socket;
        private TextView textView;
        private Handler handler;

        public BluetoothSocketListener(BluetoothSocket socket, Handler handler) {
            this.socket = socket;
            // this.textView = textView;
            this.handler = handler;
        }

        public void run() {
            int bufferSize = 2048;
            byte[] buffer = new byte[bufferSize];
            try {
                InputStream instream = socket.getInputStream();
                int bytesRead = -1;
                String message = "";
                while (true) {
                    message = "";
                    bytesRead = instream.read(buffer);
                    if (bytesRead != -1) {
                        while ((bytesRead == bufferSize)
                                && (buffer[bufferSize - 1] != 0)) {
                            message = message
                                    + new String(buffer, 0, bytesRead);
                            bytesRead = instream.read(buffer);
                        }
                        message = message
                                + new String(buffer, 0, bytesRead - 1);
                        handler.post(new MessagePoster(message));
                        socket.getInputStream();
                    }
                }
            } catch (IOException e) {
                Log.d("BLUETOOTH_COMMS", e.getMessage());
            }
        }
    }

    BroadcastReceiver discoveryResult = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            BluetoothDevice remoteDevice;
            remoteDevice = intent
                    .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            if (btadapter.getBondedDevices().contains(remoteDevice)) {
                foundDevices.add(remoteDevice);
                aa.notifyDataSetChanged();
            }
        }
    };

    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(discoveryResult);
    }

}

Logcat:
E/AndroidRuntime(10360): FATAL EXCEPTION: Thread-1585

E/AndroidRuntime(10360): java.lang.StringIndexOutOfBoundsException: length=2048; regionStart=0; regionLength=65534

E/AndroidRuntime(10360):    at java.lang.String.failedBoundsCheck(String.java:587)

E/AndroidRuntime(10360):    at java.lang.String.<init>(String.java:247)

E/AndroidRuntime(10360):    at java.lang.String.<init>(String.java:171)

E/AndroidRuntime(10360):    at com.example.blueremote.MainActivity$BluetoothSocketListener.run(MainActivity.java:177)

A: In reference to the String class, we see that calling String (byte[] data, int offset, int byteCount) will throw a IndexOutOfBoundsException when one of three scenarios occur:

*

*offset > 0 -  if the offset passed to the method is less than 0, an Exception will be thrown. Since you pass 0 and and not a variable to your method call, this is not causing the Exception.

*offset + byteCount > data.length - in this scenario an Exception will be thrown when offset plus byteCount is larger than the length of the buffer. In your code, offset is always 0 and byteCount, which in your example is bytesRead - 1, can never exceed 2048, since instream.read(buffer) cannot read more bytes than buffer itself can hold. This means that offset (0) + byteCount (-1 ≤ byteCount ≤ 2047) will never be greater than data.length (2048), so this is not the cause of the Exception.

*byteCount < 0 - the third scenario that will throw the mentioned Exception is when you pass a byte count that is less than 0. In your example, you pass bytesRead - 1 as the byte count. While you check to make sure that bytesRead != -1, which will occur if the end of the stream has been reached, you do not check to make sure that at least 1 byte was read. This is most likely the culprit...
Per your example, let us consider what happens when bytesRead = instream.read(buffer); returns 0, meaning no bytes were read...

*

*The first check you perform, if (bytesRead != -1), will pass, since bytesRead is equal to 0.

*Inside the if statement is while ((bytesRead == bufferSize) && (buffer[bufferSize - 1] != 0)), which will of course also fail since bytesRead, which is 0, is not equal to bufferSize, which is 2048.

*The final call is message = message + new String(buffer, 0, bytesRead - 1);, which we can translate to message = message + String(buffer, 0, -1). As you can see, since bytesRead was 0, the above call will generate IndexOutOfBoundsException.
To fix this issue simply make sure that you do not call String(buffer, 0, bytesRead - 1) if bytesRead is less than 1.


text:
Q: Removing padding on columns makes horizontal scrollbar I wanted to remove the padding from the bootstrap grid column classes.
So I did
.col-x {
    padding: 0;
}

But this is kind of breaking the whole layout because a horizontal scrollbar appears.
I've created a pen for this so you can see it.
What is causing the horizontal scrollbar and how to fix it?

A: The .row has minus margins on them. Also the .content-fluid has padding applied to them. So you just need to add this to your CSS:
.row {
  margin:0;
}
.container-fluid {
  padding:0;
}

A: You have .row elements nested in your columns. .row has a negative margin and always needs to be wrapped in a .container, which has padding that the negative margin offsets. The padding on your columns were doing that. I would just wrap all of your rows in .container-fluid

Rows are placed within a fixed or full-width Container (.container or .container-fluid, respectively) for proper alignment.

/* removing padding on columns makes horizontal scrollbar */
.column {
    padding: 0;
}

.column {
    min-height: 100vh;
    border-right: 1px solid #ccc;
}
.column-header {
    border-bottom: 1px solid #ddd;
}
.column.sidebar {
    position: fixed;
    top: 0; left: 0;
    border-right: 1px solid #ccc;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>

      fixed side

              Title

              Right

              Title

              Right


text:
Q: Does a partially traced density operator also become a Boltzmann density operator under Wick rotation to Euclidean space? I know that, under the Wick rotation $(i\Delta t/\hbar,p_0)\to(-\beta,-ip_{0,E})$, Feynman's path integral supposedly transforms into the traced-over Boltzmann partition function, $trace(e^{-\beta H})=trace(\rho_B)$. Furthermore, I realize that this suggests that, if one defines the total system's density operator by $\rho_{Total}=\psi^\dagger|0\rangle \langle0|\psi$, with $\psi$ the field annihilation operator, then the $e^{i[\int p \cdot dx-\int Hdt]/\hbar}=e^{i\int [p \cdot \frac{dx}{dt}-H]dt/\hbar}=e^{iS/\hbar}$ in the field operator becomes a central part of $\rho_{Total}$ and we can, in a manner of speaking, interpret the said Wick rotation as taking $\rho_{Total}\to \rho_{Total,E}$ (with E denoting the Euclidean version). (While the argument here is informal, a more exacting derivation leads to essentially the same conclusion.)
However, I'm wondering how general this transformation actually is: I'm currently working with the partial trace of $\rho_{Total}$, a pure density operator, and need to know if, following a partial trace, this Wick-rotation-induced transformation continues to work? That is, I'm sure it is valid for the total system's (pure) density operator, but does the transformation continue to be applicable if, say, the space or the time dependence is traced(/integrated) out (i.e., does $tr_t(\rho_{Total})\to e^{-\beta H'}=\rho'_B$ with a different Hamiltonian operator continue to be valid)?