text:
Q: HTTP Status 500 - An exception occurred processing JSP page /WEB-INF/jsp/index.jsp at line 6 В общем, пишу код на одном компьютере. Работает. Делаю update через github, запускаю на другом. Вылезает ошибка:
HTTP Status 500 - An exception occurred processing JSP page /WEB-INF/jsp/index.jsp at line 6

type Exception report

message An exception occurred processing JSP page /WEB-INF/jsp/index.jsp at line 6

description The server encountered an internal error that prevented it from fulfilling this request.

exception

org.apache.jasper.JasperException: An exception occurred processing JSP page /WEB-INF/jsp/index.jsp at line 6

3: <%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
4:
5:
6: <jsp:include page="fragments/headTag.jsp"/>
7:
8: <jsp:include page="fragments/bodyHeader.jsp"/>
9:

Стектрейс:
12-Sep-2017 22:27:07.415 SEVERE [http-nio-8080-exec-3] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [mvc-dispatcher] in context with path [/topjava] threw exception [An exception occurred processing JSP page /WEB-INF/jsp/index.jsp at line 6

3: <%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
4:
5:
6: <jsp:include page="fragments/headTag.jsp"/>
7:
8: <jsp:include page="fragments/bodyHeader.jsp"/>
9:

Stacktrace:] with root cause
 javax.servlet.jsp.JspTagException: No message found under code 'app.title' for locale 'ru'.
    at org.springframework.web.servlet.tags.MessageTag.doEndTag(MessageTag.java:200)
    at org.apache.jsp.WEB_002dINF.jsp.fragments.headTag_jsp._jspx_meth_spring_005fmessage_005f0(headTag_jsp.java:182)
    at org.apache.jsp.WEB_002dINF.jsp.fragments.headTag_jsp._jspService(headTag_jsp.java:128)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:443)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:385)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:329)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:726)
    at org.apache.catalina.core.ApplicationDispatcher.doInclude(ApplicationDispatcher.java:592)
    at org.apache.catalina.core.ApplicationDispatcher.include(ApplicationDispatcher.java:526)
    at org.apache.jasper.runtime.JspRuntimeLibrary.include(JspRuntimeLibrary.java:887)
    at org.apache.jsp.WEB_002dINF.jsp.index_jsp._jspService(index_jsp.java:126)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:443)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:385)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:329)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:726)
    at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:469)
    at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:394)
    at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:311)
    at org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:168)
    at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:303)
    at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1286)
    at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1041)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:984)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:208)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:474)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:783)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:798)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1434)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)

Как видим, проблема в якобы отсутствии сообщения для локали ru. Но она есть, есть и соответствующий тэг app.title=Подсчет калорий
Вот вся страница:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>

<jsp:include page="fragments/headTag.jsp"/>

<jsp:include page="fragments/bodyHeader.jsp"/>

        <form method="post" action="users">
            <spring:message code="app.login"/>: <select name="userId">
            <option value="100000" selected>User</option>
            <option value="100001">Admin</option>
        </select>
            <button type="submit"><spring:message code="common.select"/></button>
        </form>

<spring:message code="user.title"/>

<spring:message code="meal.title"/>

<jsp:include page="fragments/footer.jsp"/>

Страница подтягивает дополнительные страницы в качестве headTag и bodyHeader. Если я комментирую строчку 6, то та же ошибка в строчке 8.
headTag.jsp:
<%@page contentType="text/html" pageEncoding="UTF-8" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title><spring:message code="app.title"/></title>
    <base href="${pageContext.request.contextPath}/"/>

    <link rel="stylesheet" href="resources/css/style.css">
    <link rel="stylesheet" href="webjars/bootstrap/3.3.7-1/css/bootstrap.min.css">
    <link rel="stylesheet" href="webjars/datatables/1.10.15/media/css/dataTables.bootstrap.min.css">
    <link rel="stylesheet" href="webjars/noty/3.1.0/lib/noty.css"/>
    <link rel="shortcut icon" href="resources/images/icon-meal.png">

bodyHeader.jsp:
<%@page contentType="text/html" pageEncoding="UTF-8" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>

        <spring:message code="app.title"/>

            <form class="navbar-form navbar-right">
                <spring:message code="user.title"/>

            </form>

A: В общем, как выяснилось, при переносе проекта с одного компьютера на другой нельзя забывать про переменные окружения. В моём случае, переменная окружения была внесена в настройки Tomcat, в раздел Startup/Connection. Поэтому приложение и не могло найти папку config с локалями.
Также, если такая ошибка появляется в Debug-режиме, значит, Вы не прописали переменные окружения для Debug, это делается в Tomcat -> Edit Configurations -> Startup/Connections -> Debug.


text:
Q: NSUserActivity handoff not working for custom data I'm trying to test out the iOS 8.1 handoff feature with NSUserActivity between my iPhone and my iPad. For this, I tried both implementing my own solution, and to use Apple's PhotoHandoff project. However, it's not working.
If I provide a webpageURL, the handover works fine, but when I try to use userData or addUserInfoEntriesFromDictionary nothing works, and I can't for the life of me figure out what the catch is to make the data work.
Sample code:
NSUserActivity *activity = [[NSUserActivity alloc] initWithActivityType:@"com.company.MyTestApp.activity"];
activity.title = @"My Activity";
activity.userInfo = @ {};
//    activity.webpageURL = [NSURL URLWithString:@"http://google.com"];

self.userActivity = activity;

[self.userActivity becomeCurrent];
[self.userActivity addUserInfoEntriesFromDictionary:@ { @"nanananan": @[ @"totoro", @"monsters" ] }];

(I'm also unable to make it work with a Mac app with a corresponding activity type)

A: I hope you found the solution already, but in case somebody stumbles upon this problem too, here is a solution. (Actually not very different from the previous answer)
Create user activity without userInfo, it will be ignored:
NSUserActivity *activity = [[NSUserActivity alloc] initWithActivityType:@"..."];
activity.title = @"Test activity";
activity.delegate = self;
activity.needsSave = YES;

self.userActivity = activity;
[self.userActivity becomeCurrent];

Implement the delegate to react to needSave events:
- (void)userActivityWillSave:(NSUserActivity *)userActivity {
    userActivity.userInfo = @{ @"KEY" : @"VALUE" };
}

When needsSave is set to YES this method will be called and userActivity will be updated.
Hope this helps.

A: To update the activity object's userInfo dictionary, you need to configure its delegate and set its needsSave property to YES whenever the userInfo needs updating.
This process is described in the best practices section of the Adopting Handoff guide.
For example, with a simple UITextView, you need to specify the activity type ("com.company.app.edit") identifier in the Info.plist property list file in the NSUserActivityTypes array, then:
- (NSUserActivity *)customUserActivity
{
    if (!_customUserActivity) {
        _customUserActivity = [[NSUserActivity alloc] initWithActivityType:@"com.company.app.edit"];
        _customUserActivity.title = @"Editing in app";
        _customUserActivity.delegate = self;
    }

    return _customUserActivity;
}

- (void)textViewDidBeginEditing:(UITextView *)textView
{
    [self.customUserActivity becomeCurrent];
}

- (void)textViewDidChange:(UITextView *)textView
{
    self.customUserActivity.needsSave = YES;
}

- (BOOL)textViewShouldEndEditing:(UITextView *)textView
{
    [self.customUserActivity invalidate];

    return YES;
}

- (void)userActivityWillSave:(NSUserActivity *)userActivity
{
    [userActivity addUserInfoEntriesFromDictionary:@{ @"editText" : self.textView.text }];
}

A: FWIW, I was having this issue. I was lucky that one of my Activity types worked and the other didn't:
Activity: Walking
(UserInfo x1,y1)
(UserInfo x2,y2)
(UserInfo x3,y3)
Activity: Standing
(UserInfo x4,y4)
Activity: Walking
etc.

I got userInfo if the handoff occured when standing but not walking. I got other properties such as webpageURL in all cases; just userInfo came through null.
The fix for me was to invalidate & recreate the NSUserActivity object every time (e.g. when Walking to x2/y2 from x1/y1), instead of only when Activity type changed (e.g. from walking to standing). This is very much not the way the doc is written, but fixed the issue on iOS 9.
UPDATE: This workaround doesn't work on iOS 8. You need to implement this via the userActivityWillSave delegate, as gregoryM specified. Per Apple's doc:

To update the activity object's userInfo dictionary efficiently,
  configure its delegate and set its needsSave property to YES whenever
  the userInfo needs updating. At appropriate times, Handoff invokes the
  delegate's userActivityWillSave: callback, and the delegate can update
  the activity state.

This isn't a "best practice", it is required!
[Note: issue occurred on iOS 9 devices running code built on Xcode 6.x. Haven't tested Xcode 7 yet, and issue may not occur on iOS 8.]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Purpose of Movable Type mt-*.cgi scripts? I'm building an extra layer on top of Movable Type for integration with another system. Part of this involves pre-processing and filtering requests before they get to the MT scripts (comment control, translating external users into MT users etc).
For example, new comments to posts are submitted to a script in the new layer before requests are passed on to mt-comments.cgi. In this instance, I'm denying access to mt-comments.cgi from all but a specific IP as I don't want people being able to post new comments 'directly'.
I'd like to know the general purpose of all mt-*.cgi scripts such that I can deny access to those not relevant and control access to all others.
The mt-*.cgi scripts I have, along with their (estimated) purpose, are:

*Script*             *Private access?*   *Purpose*
mt-add-notify.cgi     ?                   ?
mt-atom.cgi           ?                   ?
mt.cgi                Yes                 Main MT engine
mt-check.cgi          ?                   ?
mt-comments.cgi       Yes                 Handles inbound new comments
mt-config.cgi         Yes                 Stores main MT configuration
mt-feed.cgi           ?                   ?
mt-ftsearch.cgi       ?                   ?
mt-search.cgi         Yes                 Handles search requests, returns results
mt-tb.cgi             ?                   ?
mt-testbg.cgi         ?                   ?
mt-upgrade.cgi        Yes                 Upgrade tool
mt-wizard.cgi         Yes                 Setup/config wizard
mt-xmlrpc.cgi         ?                   ?

I'd appreciate answers to fill in the blanks.
By 'private access', I mean: can access be limited (e.g. via .htaccess) to a known set of IPs only? The inverse of this being: must access be available to all IPs?
Answers clearly elaborating on the purpose and use of a script, such that it may be of use to others, are always welcome.
Thanks very much to anyone who can help!

A: I've filled in the purpose on each of these.  I'm pretty sure everything can be private as long as you proxy requests properly, but not positive.  Some of these scripts can (and should) be blocked out completely.
*Script*             *Private access?*   *Purpose*
mt-add-notify.cgi     ?                   Provide Movable Type email notification support
mt-atom.cgi           ?                   An Atom Publishing API interface for communicating with Movable Type.
mt.cgi                Yes                 Main MT engine
mt-check.cgi          ?                   Determines whether you have all of the components you need to run Movable Type
mt-comments.cgi       Yes                 Handles inbound new comments
mt-config.cgi         Yes                 Stores main MT configuration
mt-feed.cgi           ?                   Movable Type application for producing activity feeds.
mt-ftsearch.cgi       ?                   Freetext search
mt-search.cgi         Yes                 Handles search requests, returns results
mt-tb.cgi             ?                   Handles blog trackbacks
mt-testbg.cgi         ?                   Tests for background tasks
mt-upgrade.cgi        Yes                 Upgrade tool
mt-wizard.cgi         Yes                 Setup/config wizard
mt-xmlrpc.cgi         ?                   XML RPC interface (external blog tool posting)

I knew a few of these, but the easiest way to find out what each does is crack open the file and see which Perl module it calls (such at MT::Trackback), then run perldoc lib/MT/Trackback.pm for each.  It will give you all sorts of information about what each script can do.


text:
Q: Spring security 3.1: Where to check user password with PasswordEncoder As Spring Security 3.1 provides a new convenient PasswordEncoder and an implementation StardardPasswordEncoder, I try to implement them into current project. However, there is question about how the PasswordEncoder should work when save/verify user password. Here is code for the new PasswordEncoder:
    private static final String SALT_AS_TOP_SECRET = "mysalt";
    private static final PasswordEncoder encoder = new StandardPasswordEncoder(
        SALT_AS_TOP_SECRET);

    public static String encrypt(String rawPassword) {
        return encoder.encode(rawPassword);
    }

    public static boolean match(String rawPassword, String password) {
        return encoder.matches(rawPassword, password);
    }

My applicaiton is Spring with JPA, so there is a User entity implements UserDetails with basic getter/setter for the password, also there is a service class implement the UserDetailService in the service layer.
I am confused about the UserDetailService only requires a loadUserByUsername method which doesn't check password. So here are other questions:

*

*Where shall I place the match method from PasswordEncoder?

*Shall I implement another interface for the service class?

*Shall I give any logic within User entity when setting password?

*As the new PasswordEncoder interface is independent to other security package, I bet there is no need to initiate/inject the bean from xml? I try to pu the salt inside the class instead of external storage.

Please give a hint, thanks in advance.


text:
Q: Is posible to retrieve info from Microsoft Teams directly? I'm trying to retrieve, with c#, info like chats names or chat participants, but all the documentation I can found if about using bots to retrieve this info, so, is possible access to the teams client  with some type of connector to retrieve this info directly?
Tnx in advance.
Just for clarify, I don't want to create Teams app, has to be 100% client, listening the possible Teams events to retrieve info.

A: If you aren't creating a Teams app, here's what's supported today, with more coming all the time: https://developer.microsoft.com/en-us/graph/docs/api-reference/beta/resources/teams_api_overview.


text:
Q: Entity Framework Model First 1:0..1 Relationship I created the following model in the Entity Framework 5 Model Designer in Visual Studio 2012:

Then I generated the database from the model, which resulted in the following tables in my database:

Please help me understand why Entity Framework is generating a one-to-many relationship for a one-to-zero-or-one association.

Update #1
Furthermore, if I change the association from 1:0..1 to 1:1 like this:

Then not only is there still no one-to-one relationship in the database, but now the one-to-many relationship is flipped around, which seems even more weird to me:

Update #2
In response to Mystere Man's comment and answer, the structure I'm expecting to see in SQL Server, which is a valid 1:0..1 relationship is as follows:

Furthermore, I am able to get this working exactly as intended with the following Code First fluent mapping:
public class UserMap : EntityTypeConfiguration<User>
{
    public UserMap()
    {
        ToTable("Users");

        HasKey(t => t.UserId);

        Property(t => t.UserId)
            .HasColumnName("UserId");

        Property(t => t.Name)
            .HasColumnName("Name")
            .IsRequired()
            .HasMaxLength(50);

        Property(t => t.EmailAddress)
            .HasColumnName("EmailAddress")
            .IsRequired()
            .HasMaxLength(254);

        Property(t => t.CreatedDateTime)
            .HasColumnName("CreatedDateTime");

        HasOptional(t => t.Subscription)
            .WithRequired(t => t.User);
    }
}

public class SubscriptionMap : EntityTypeConfiguration<Subscription>
{
    public SubscriptionMap()
    {
        ToTable("Subscriptions");

        HasKey(t => t.SubscriptionId);

        Property(t => t.SubscriptionId)
            .HasColumnName("SubscriptionId");

        Property(t => t.TypeValue)
            .HasColumnName("TypeValue");

        Property(t => t.CreatedDateTime)
            .HasColumnName("CreatedDateTime");

        Property(t => t.ExpiresDateTime)
            .HasColumnName("ExpiresDateTime");

        HasRequired(t => t.User)
            .WithOptional(t => t.Subscription);
    }
}

So, I know it's possible to achieve this behavior with Code First Entity Framework. My question is why it's not possible to do it with the Model First approach.
What's going on here and why?
Thanks!

A: SQL does not have a way to define a true 1:1 or 1:0..1 data model, except when both entities have the same primary key.  Even so, you can't have a 1:1 because you can't insert records into more than one table in a single statement, so the data model has to allow 1:0..1 by virtue of there being a intermediate state where one record will exist without the other.
The only way to do this in SQL is to do exactly what EF is doing here, create a 1:*, and then impose constraints ensure uniqueness (such as a Unique Constraint).  However, EF doesn't support constraints (you would have to create them manually) so it's possible to insert more than one record and violate your model.
EDIT:
Since you've clarified that you're talking about Model First, and that you are looking for a shared primary key, then here's what you have to do.
Right click on the Association, and create a referential constraint between Subscription and User.  This will then cause EF to generate the 1:0..1 relationship you are looking for.


text:
Q: FigureCanvasWxAgg not resizing properly in panel (or notebook) in linux I've written a program in wxpython that works just fine in windows but when tested in lunix I have some Display issues that that all occur in linux.
Here is a testapp that demonstrates the problem with the resizing of the FigureCanvasWxAgg in a panel, as seen the panel it self follows the resizingevent but the FigureCanvasWxAgg doesn't follow, this however is not a problem in Windows.
import wx
import matplotlib.figure as plt
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas
import wx.lib.inspection

class Test(wx.Frame):

    def __init__(self):
        super(Test, self).__init__(parent=None, id=-1)
        self.figure = plt.Figure()
        self.panel = wx.Panel(self, 1)
        self.figurepanel = FigureCanvas(self.panel, -1, self.figure)
        self.axes1 = self.figure.add_subplot(111)
        frame_box = wx.BoxSizer(wx.VERTICAL)
        frame_box.AddStretchSpacer(prop=1)
        frame_box.Add(self.panel, flag=wx.EXPAND, proportion=2)
        frame_box.AddStretchSpacer(prop=1)
        main_box = wx.BoxSizer(wx.HORIZONTAL)
        main_box.AddStretchSpacer(prop=1)
        main_box.Add(frame_box, flag=wx.EXPAND, proportion=1)
        main_box.AddStretchSpacer(prop=1)
        self.SetSizer(main_box)
        self.Show()
        self.Layout()

def main():
    app = wx.App()
    Test()
    wx.lib.inspection.InspectionTool().Show()
    app.MainLoop()

if __name__ == '__main__':
    main()

What I would be very grateful to have answered is:

*

*How do I resolve this issue of reszing FigureCanvasWxAgg in linux

*Is there any difference in the general way of GUI programming with wxPython on  Windows and in Linux

A: There are several issues with the code you posted:

*

*You have horizontal and vertical spacer that expand as needed, which causes the central region to remain the same shape

*self.figurepanel is not part of any sizer, which means it will not resize even if its container, self.panel does.

The code below produces a window filled by plot that resizes with the window:
import wx
import matplotlib.figure as plt
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas
import wx.lib.inspection

class Test(wx.Frame):

    def __init__(self):
        super(Test, self).__init__(parent=None, id=-1)
        self.panel = wx.Panel(self, 1)
        self.panel.SetBackgroundColour('RED')

        self.figure = plt.Figure()
        self.axes1 = self.figure.add_subplot(111)
        self.figurepanel = FigureCanvas(self.panel, -1, self.figure)

        main_box = wx.BoxSizer(wx.HORIZONTAL)
        main_box.Add(self.figurepanel, flag=wx.EXPAND, proportion=1)
        self.panel.SetSizer(main_box)

        frame_box = wx.BoxSizer(wx.VERTICAL)
        frame_box.Add(self.panel, flag=wx.EXPAND, proportion=1)

        self.SetSizer(frame_box)
        self.Show()
        self.Layout()

def main():
    app = wx.App()
    Test()
    wx.lib.inspection.InspectionTool().Show()
    app.MainLoop()

if __name__ == '__main__':
    main()

There is no need to do any manual resizing yourself, and there is no problem, I think, with resize event propagation. If there is there would be a lot more breakage than what you are seeing.

A: I think I fixed the problem. The problem is caused by the wx.EVT_SIZE witch seems to be automatic in Windows but not in Linux. So to fix the problem in Linux all you have to do is to bind the the wx.Panel  to the wx.EVT_SIZE and then define an apropriate eventhandler that takes care of the resizing.
What did the trick for me was:
#code beneath is a part if the __init__ metod
self.panel = wx.Panel(self, -1)
self.figurepanel = FigureCanvas(self.panel, -1, self.figure)
self.panel.Bind(wx.EVT_SIZE, self.on_size)
....
#the eventhandler for the panel. The method resizes the the figurepanel and the figure.
def on_size(self, event):
    pix = self.panel.GetClientSize()
    self.figure.set_size_inches(pix[0]/self.figure.get_dpi(),
                                pix[1]/self.figure.get_dpi())
    x,y = self.panel.GetSize()
    self.figurepanel.SetSize((x-1, y-1))
    self.figurepanel.SetSize((x, y))
    self.figurepanel.draw()
    event.Skip()


text:
Q: Function expressions not updating values, functions beeing called only once (module) So basicly this.acceleration doesn't get updated whatever I do. I need a way to make a function update its values, so when they get changed from another function, it still works correctly. Here is what I mean:
function PropellingNozzle(power) {

    this.power = power;
    this.afterburner = "off";

    function acceleration (afterburner, power) {

        this.afterburner = afterburner;
            console.log(this.power);
        if(this.afterburner == "on") {
            this.acceleration = this.power*2;
        }
        else if(this.afterburner == "off") {
            this.acceleration = this.power;
        }
            console.log("called");
            return this.acceleration
    }

    return {

        power: this.power,
        afterburner: this.afterburner,
        switchAfterburner: function() {
            if(this.afterburner == "off") {
                    this.afterburner = "on";
                }

                else if(this.afterburner == "on") {
                    this.afterburner = "off";
                }
        },
        acceleration: acceleration(this.afterburner, this.power)
    };
}

As you can see, I know started parsing the values and what no, just experimenting and it still does not work. Here is the whole code part with the tests in jsfiddle. Preferebly, switchAfterburner should also be in PropellingNozzle function, but if it cannot work there is no problem for it to remain in the return. My task is to write the code as object oriented as possible with my knowledge so far

A: You are calling it only once - when assigning the value to the acceleration property. You're not assigning the function expression to get re-evaluated whenever one of the values changes, but you're assigning its result value.
So what to do against this? You can

*

*update the acceleration property whenever one of the values it depends on changes. When they're only set by your functions (like switchAfterBurner) and not directly assigned from outside, it's easy to put the re-computation within those setters.

*use a getter method for the acceleration. Instead of just reading a property, the outside will call a getAcceleration() function which dynamically computes the correct value.

Btw, please use either
function PropellingNozzle(power) {
    this.power = power;
    this.afterburner = "off";
    this.switchAfterburner =  function() {…};
    …
}
var example = new PropellingNozzle(…);

or
function makePropellingNozzle(power) {
    …
    return {
        power: power,
        afterburner: "off",
        switchAfterburner: function() {…},
        …
    };
}
var example = makePropellingNozzle(…);

but not a mixture of both.


text:
Q: WordPress: Remove admin pages but still can access directly. I am trying to make a WordPress installation on my test server secure so that I can give a client access but they can't f*$K it up (which I just spent a few hours fixing) by installing themes and plugins etc...
So I looked around and found a solution which you add to the functions.php file:
function custom_remove_admin_menus (){

  if ( function_exists('remove_menu_page') ) {
    remove_menu_page('themes.php');
    remove_menu_page('plugins.php');
  }
}

add_action('admin_menu', 'custom_remove_admin_menus');

This works in the respect as it removed the links in the admin panel sidebar, however if you go to those pages directly they still show up.
Is there a way to restrict these pages to a certain user like super_admin or something. I do not want to install another plugin or faff around with having to update it or edit the core so I hope there is a simple solution I can add to the functions file.

A: You can create user account on admin dashboard and assign role as editor or author. Editor / Author does not have permissions to do anything with themes and plugins. When a user(Role : Author/ Editor) logs in admin dashboard, he/she won't see appearance and plugins in sidebar.
Hope this helps

A: You can use current screen id using get current screen function. check current user id and and redirect user. current screen function may not work in init of admin_init hook, so you can add it in enqueue scripts hook and redirect user using JS code.


text:
Q: need assistance with writing test cases for cosine similarity This is my function I made below.
def cosine_similarity(a,b):
    """
    Determins the similarity between two vectors, by computing the cosine of the angle between them
    :param Union[ndarray, Iterable, int, float] a: a non zero numeric vector
    :param Union[ndarray, Iterable, int, float] b: a non zero numeric vector
    :return: ndarray

    """
    norm_a = numpy.linalg.norm(a)
    norm_b = numpy.linalg.norm(b)
    if norm_a ==0 or norm_b ==0:
        raise ZeroDivisionError("Can not find the cosine between two vectors with following norms:{} {}".format(norm_a,norm_b))
    return numpy.dot(a,b)/(norm_a * norm_b)

I need help with writing test cases I have started it but am lost as i've never writing a test case
class TestCosineSimilarity(TestCase):
    def test_cosine_similarity_with_zero(self):

A: Classic libraries for testing in python are doctest and unittest. If you are just looking at using a few manually creates test cases, I'd recommend doctest. For more thorough testing using randomly generated test cases unittest is the library to use.
From your comment above, it looks like you are after a unittest solution. In essence, what you'll want to do here, it to

*

*Provide an alternative implementation - unless you can come up with a different way of testing cosine similarity (e.g. you could generate cases where the cosine similarity is known a priori, but I'm not seeing how you can do that except for special cases).

*Randomly generate pairs of vectors.

*For each vector pair, evaluate your function and the alternative implementation, and compare the results. Beware of rounding errors.


text:
Q: Big speed difference with c style linked list and c++ std::vector From what I have read, and the way I understand how memory structures work, the vector creates an array where all the values are aligned after each other, while the linked list I have put together below will point to a random point in memory where the next object is allocated. Hence the vector should be faster for this code.
When I compile the following code I get runtimes of 4 sec for the linked list, while the vector runs in 21 sec, thats a 5 times speed increase for the vector.
Am I missing something here? Or does anyone have an explanation for this?
#include <vector>
#include <iostream>
#include <ctime>

using namespace std;

struct point{
    float t;
    float v;
};

struct pointlist{
    float t;
    float v;
    struct pointlist *next;
};

void fillpoints(std::vector<struct point> &points, struct pointlist *pointlist) {
    int i;

    for (i = 0; i<8;i++) {
        struct point newpoint; // Fill vector
        newpoint.t = (float)i;
        newpoint.v = (float)i/2;
        points.push_back(newpoint);

        pointlist->t = (float)i; // Fill linked list
        pointlist->v = (float)i/2;
        struct pointlist *temppoint = (struct pointlist *)malloc(sizeof(struct pointlist));
        pointlist->next = temppoint;
        pointlist = temppoint;
    }

    struct point newpoint;
    newpoint.t = 0;
    newpoint.v = (float)i/2;
    points.push_back(newpoint);
    pointlist->t = 0;
    pointlist->v = (float)i/2;
    pointlist->next = NULL;
}

float areavec(std::vector<struct point> pointlist) {
    float y1, z1, y2, z2, area;

    area = 0;
    y2 = pointlist[0].t - pointlist[0].v;
    z2 = pointlist[0].t + pointlist[0].v;

    for (unsigned int i = 1; i<pointlist.size();i++) {
        y1 = y2;
        z1 = z2;
        y2 = pointlist[i].t - pointlist[i].v;
        z2 = pointlist[i].t + pointlist[i].v;
        area += (y1*z2) - (y2*z1);
    }
    return area;
}

float arealist(struct pointlist *pointlist) {
    float y1, z1, y2, z2, area;

    area = 0;
    y2 = pointlist->t - pointlist->v;
    z2 = pointlist->t + pointlist->v;

    while (pointlist->next != NULL) {
        y1 = y2;
        z1 = z2;
        y2 = pointlist->next->t - pointlist->next->v;
        z2 = pointlist->next->t + pointlist->next->v;
        area += (y1*z2) - (y2*z1);

        pointlist = pointlist->next;
    }
    return area;
}

void main() {
    int runs = 200000000;
    float a;
    std::vector<struct point> points;
    struct pointlist *pointlist = (struct pointlist *)malloc(sizeof(struct pointlist));

    struct pointlist *test = pointlist;
    fillpoints(points, pointlist);

    clock_t start = clock();
    for (int i=0; i<runs; i++) {
        a = arealist(pointlist);
    }
    cout << "Time: " << (clock()-start)/CLOCKS_PER_SEC << " Area: " << a << endl;

    start = clock();
    for (int i=0; i<runs; i++) {
        a = areavec(points);
    }
    cout << "Time: " << (clock()-start)/CLOCKS_PER_SEC << " Area: " << a << endl;

    cin.get();
}

A: float areavec(std::vector<struct point> pointlist)

Here, I'll fix that:
float areavec(const std::vector<struct point>& pointlist)

You were copying the vector 200000000 times.  Whereas with the linked list, you were just copying a pointer.


text:
Q: what coule be request type for express-fileupload I try to upload a file in the node js application
Usually I use express.Request as request and express.Response for response
But If i use that the file is not accusable
app.post('/upload', function(req: express.Request , res : express.Response) {
   console.log(req.files.foo); // the uploaded file object
});

with this, if I try access files like, It gives me error
req.files

I do not want to use : any

A: Have a look at @types/express-fileupload, it should provide the missing type declarations
npm i -D @types/express-fileupload


text:
Q: Cannot receive props from Link I'm learning react and am trying to pass a prop(named as classId) to another component(ClassPage.js) through Link, however I cannot receive the prop and it is returning undefined. Thanks for your time, appreciate that.
App.js - i want to access classId(from the link in ClassList) in my ClassPage component )
<Route path="/classpage/:classId" exact render={() => <ClassPage isLoggedIn={this.state.isLoggedIn} user={this.state.user}/>} />

ClassList.js - try to pass data to ClassPage component through Link
import React, { Component } from "react";
import { Link } from "react-router-dom";
import "./ClassList.css";

class ClassList extends Component {

render() {

console.log(this.props.classId); //recived
console.log(this.props.classTitle); //recived
console.log(this.props.classDescription); //recived
console.log("click link and direct to Class Page");

// Problem located in here, try to pass data to ClassPage.js
return (

    <Link to={"/classpage/"+this.props.classId}>

{this.props.classTitle}

    </Link>

        Instructor: {this.props.instructor}

        Meeting day: {this.props.meetingDay}

);
}
}

export default ClassList;

ClassPage.js - unable receiving classId from ClassList component
import React from 'react';
import Navbar from "../Components/Navbar.js";
import Footer from "../Components/Footer.js";
import PostTable from "../Components/PostTable.js";

class ClassPage extends React.Component {
  constructor(props) {
    super(props);

    console.log("class ID");
    console.log(this.props.classId); //Problem located in here
    //cannot receive - this.props.classId

    this.state  = {
      classPostsData: []
    };
  }

componentDidMount() {
    fetch("https://api.myjson.com/bins/jfuqc")
    // fetch from localhost by this.props.classId
        .then(data => data.json())
        .then(data => this.setState({classPostsData: data}))
  }

render() {
    return(

        <Navbar isLoggedIn={this.props.isLoggedIn} />

{this.props.classTitle}

{this.props.classDescription}

        {this.state.classPostsData.map(post => {
          return (
            <PostTable
              key={post.post_ID}
              post_ID={post.post_ID}
              post_Title={post.post_Title}
              post_note={post.post_note}
            />
          );
        })}

    );
  }
}

export default ClassPage;

Updated:
ClassList.js
const toClassPage = {
   pathname: "/classpage/" + this.props.classId,
   state: {
            classId: this.props.classId,
            classTitle: this.props.classTitle,
            classDescription: this.props.classDescription
          }
}

<Link to={toClassPage}>

{this.props.classTitle}

</Link>

ClassPage.js
constructor(props) {
    super(props);

    console.log("class ID/Title/Description");
    console.log(this.props.location.state.classId);
    console.log(this.props.location.state.classTitle);
    console.log(this.props.location.state.classDescription);

    this.state  = {
        classPostsData: []
    };
}

Error from Chrome:
TypeError: Cannot read property 'state' of undefined
new ClassPage
src/Pages/ClassPage.js:13

   10 | super(props);
   11 |
   12 | console.log("class ID/Title/Description");
 > 13 | console.log(this.props.location.state.classId);
      | ^  14 | console.log(this.props.location.state.classTitle);
   15 | console.log(this.props.location.state.classDescription);
   16 |

A: You shouldn't need to access class id according to your route. You can just rip it out of the href.
let id = window.location.href.split("/")[window.location.href.split("/").length -1];

If you only need that id from the address bar the code above should do the trick.
If you need more than just the class id you can also pass props to the state through link.
   <Link to={{
      pathname: `/classpage/${this.props.classId}`,
      state: {
        classId: this.props.classId,
        title: this.props.classTitle,
        description: this.props.classDescription
      }
    }}>

{this.props.classTitle}

</Link>

You would then access that through this.props.location.state

A: I followed this example and finally it works well. Thanks for the help
Cannot read property 'params' of undefined (React Router 4)


text:
Q: Getting java.net.SocketException: Connection reset error on RabbitMQ connection using JDK1.7 JDK Version

*

*1.7

RabbitMQ:
AWS RabbitMQ - amqps protocol
Java Client Maven:
<dependency>
        <groupId>com.rabbitmq</groupId>
        <artifactId>amqp-client</artifactId>
        <version>4.12.0</version>
    </dependency>

I am trying to create the RabbitMQ connection using the below code,
        //Establish the Rabbbit MQ connection;
        ConnectionFactory factory = new ConnectionFactory();
        factory.setUsername(userName);
        factory.setPassword(password);
        factory.setHost(hostName);
        factory.setPort(5671);
        factory.useSslProtocol();
        connection = factory.newConnection();

But I am getting below error,
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:196)
at java.net.SocketInputStream.read(SocketInputStream.java:122)
at sun.security.ssl.InputRecord.readFully(InputRecord.java:442)
at sun.security.ssl.InputRecord.readV3Record(InputRecord.java:554)
at sun.security.ssl.InputRecord.read(InputRecord.java:506)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:934)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1332)
at sun.security.ssl.SSLSocketImpl.writeRecord(SSLSocketImpl.java:709)
at sun.security.ssl.AppOutputStream.write(AppOutputStream.java:122)
at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:82)
at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:140)
at java.io.DataOutputStream.flush(DataOutputStream.java:123)
at com.rabbitmq.client.impl.SocketFrameHandler.sendHeader(SocketFrameHandler.java:160)
at com.rabbitmq.client.impl.SocketFrameHandler.sendHeader(SocketFrameHandler.java:170)
at com.rabbitmq.client.impl.AMQConnection.start(AMQConnection.java:312)
at com.rabbitmq.client.impl.recovery.RecoveryAwareAMQConnectionFactory.newConnection(RecoveryAwareAMQConnectionFactory.java:63)
at com.rabbitmq.client.impl.recovery.AutorecoveringConnection.init(AutorecoveringConnection.java:177)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:1181)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:1138)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:1096)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:1256)

Can someone please help me to resolve this issue using the JDK 1.7? The same code is working in the Java 8.

A: If you take a look at the Java libraries for RabbitMQ, you can see that the minimum JDK version of all supported libraries is JDK version 8:

That means that it'll only work with JDK version 8 (1.8) or higher.
Also, just some extra info, but Oracle is also dropping support for JDK 1.7 from july 2022 onwards. Meaning there won't be any security patches and bugfixes anymore.


text:
Q: why my code have to call the function 2 times to get the correct value? I call a function with the following codes on the client side, post the array to server side.
but the server side responses 0 for the return value first. I have to call the function again, then it returns the correct value. wondering if anyone know what is wrong with my code? thx!
client side:
var array = [];
array.push(1, 2, 3);

google.script.run.withSuccessHandler(returnedScore).calScore(array);
function returnedScore(value) {
score = value;
return score;
}

server side:
function calScore(array) {
var value = 0;
value = array[0] - 5*array[1]*array[2]*2;
return value;
}

A: This works for me:
function launchMyStupidDialog() {
  let html='

';
  html+='';
  SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutput(html),'test');
}

function calScore(array) {
var value = 0;
value = array[0] - 5*array[1]*array[2]*2;
return value;
}


text:
Q: React.js useState hook causes too many re-renders and cant update my state I am a student trying to get the hang of React. So far I would like to be able to cut my data array that I receive from the API into chunks so that I can use a pagination effect later down the road. I cant figure out why the function arrayChunk() ends up causing too many renders. How can set my function to push the chunkedArray in to setChunkedYearArray?
here is my full code:

import React, { useState, useEffect } from 'react';
import InformationBox from '../../component/InformationBox/InformationBox';
import arrowButton from '../../assets/arrow-button.svg';

const InformationBoxLayout = (props) => {
    const [activeYear, setActiveYear] = useState([]);
    const [chunkedYearArray, setChunkedYearArray] = useState([]);
useEffect(() => {
        axios
            .get('http://www.mocky.io/v2/5ea446a43000005900ce2ca3')
            .then((response) =>
                setActiveYear(
                    response.data.timelineInfo.filter((item) => item.year === '2018')
                )
            );
    }, []);

    const arrayChunk = (array, chunkSize) => {
        const chunkedArray = [];
        let clonedArray = [...array];
        const splitPieces = Math.ceil(clonedArray.length / chunkSize);
        for (let i = 0; i < splitPieces; i++) {
            chunkedArray.push(clonedArray.splice(0, chunkSize));
        }
        setChunkedYearArray(chunkedArray);
    };

    return (

            <button className={style.leftArrow}>

            </button>
            {activeYear.length > 6
                ? arrayChunk(activeYear, 6)
                : console.log('no split')}

            <button className={style.rightArrow}>

            </button>

    );
};

export default InformationBoxLayout;

A: Anytime you call setState the component will re-render, so you can't call setState in the render function.  There is no reason to use state for the chunkedYearArray.  Just return the value from the function and then use it:
const InformationBoxLayout = props => {
  const [activeYear, setActiveYear] = useState([]);

  useEffect(() => {
    axios
      .get("http://www.mocky.io/v2/5ea446a43000005900ce2ca3")
      .then(response =>
        setActiveYear(
          response.data.timelineInfo.filter(item => item.year === "2018")
        )
      );
  }, []);

  const arrayChunk = (array, chunkSize) => {
    const chunkedArray = [];
    let clonedArray = [...array];
    const splitPieces = Math.ceil(clonedArray.length / chunkSize);
    for (let i = 0; i < splitPieces; i++) {
      chunkedArray.push(clonedArray.splice(0, chunkSize));
    }
    return chunkedArray;
  };

  // Now you have calculated it, so use it for whatever you want in your JSX
  const chunkedYearArray = activeYear.length > 6
        ? arrayChunk(activeYear, 6)
        : [];

  return (

      <button className={style.leftArrow}>

      </button>

      <button className={style.rightArrow}>

      </button>

  );
};

export default InformationBoxLayout;

Alternatively, if you truly want it in state you could do the calculation in then then from your API call:
  const [chunkedYearArray, setChunkedYearArray] = useState([]);
  useEffect(() => {
    axios
      .get("http://www.mocky.io/v2/5ea446a43000005900ce2ca3")
      .then(response =>
        setActiveYear(
          response.data.timelineInfo.filter(item => item.year === "2018")
        )

        const arrayChunk = (array, chunkSize) => {
          const chunkedArray = [];
          let clonedArray = [...array];
          const splitPieces = Math.ceil(clonedArray.length / chunkSize);
          for (let i = 0; i < splitPieces; i++) {
            chunkedArray.push(clonedArray.splice(0, chunkSize));
          }
          return chunkedArray;
        };

        const newChunkedYearArray = activeYear.length > 6 ? arrayChunk(activeYear, 6)
        : [];

        // Because we are in useEffect we are only calculated once!
        setChunkedYearArray(newChunkedYearArray)
      );
  }, []);

There is definitely room for clean up here, but I think either one of those will put you on the right track.  Hope that helps!

A: You end up calling arrayChunk every render which sets some state and triggers a rerrender. Using an effect hook to only recompute the chunked array when activeYear updates should help.
useEffect(() => {
  activeYear.length > 6 && arrayChunk(activeYear, 6);
}, [activeYear]);

Then just render { chunkedYearArray }


text:
Q: CC2540 HIDAdvRemoteControl pairing and bonding I'm trying to flash this configuration (HIDAdvRemoteDongle) to my CC2540 USB dongle.
What we are trying to achieve here is
1) Configure CC2540 with the example (HIDAdvRemoteDongle)
2) Do some changes in HIDAdvRemotedongle so that it pairs with an iPhone or Android which is compatible with BLE.
3) Develop and Android/iPhone App which can send the HID key event to CC2540 dongle.
Note: CC2540 is connected to a target (linux OS machine) where the HID event shall be taken up to a HMI event change in the machine.
I am only successful till Step 1.
Step 2 I need your help?
Step 3 I have the understanding of the Core Bluetooth framework of iOS but not sure if this is achievable in Android, so please confirm that as well?
Awaiting for your reply.

A: I found a solution on my own.
Just trying to explain here so that it shall be useful for others who is in the same page.
HIDAdvRemoteDongle is only for the HID configuration and does it for three things
1) Keyboard
2) Consumer keyboard
3) Mouse
SimpleBLEPeripheral is for the BLE connection (Pairing and bonding) and 5 characteristics (Read,Read/Write & Notify)
If you can integrated both HIDAdvRemoteDongle and SimpleBLEPeripheral projects in the CC2540 Ble project you will have a complete solution
And sending the reports to the host to which dongle is connected is the next episode, which some code needs to be hacked on your own.
Do let me know if anybody need some hands on it, I can help


text:
Q: Gin not finding @Provides method Here is my Gin module:
public class FooGinModule extends AbstractGinModule {

  @Override
  protected void configure() {
    ...

    bind(ActivityManager.class).asEagerSingleton();

    ...
  }

  @Provides
  @Singleton
  public ActivityManager getActivityManager(EventBus eventBus, SimplePanel display,
      ActivityMapper activityMapper) {
    final ActivityManager activityManager = new ActivityManager(activityMapper, eventBus);
    activityManager.setDisplay(display);
    return activityManager;
  }

}

When I try to gwt-compile, I get the following error:

[ERROR] No @Inject or default constructor found for class
  com.google.gwt.activity.shared.ActivityManager

Am I specifying the @Provides method wrong?

A: You don't need the explicit binding, and in fact I think it will override the @Provides method. I don't know of a nice way to use asEagerSingleton() with a @Provides method, instead consider a Provider<T> implementation.
bind(ActivityManager.class)
    .toProvider(MyActivityManagerProvider.class)
    .asEagerSingleton();

Looking at the actual stuff you are generating/wiring, I find it useful to actually @Inject the ActivityManager instance to the parent of the SimplePanel (or whatever you are using as the display), and calling setDisplay there instead. At least to me, this makes it easier to replace the display or change it, as it is part of that block of code instead of part of the module. It also removes the need to create an eager singleton.


text:
Q: How do I do two different selects? In postgresql how do I do something like below? I MUST be able to return a string (when there's a logical error) and multiple rows on my typical case.
\set placeholder 5

IF :placeholder<1000 THEN
   select 'Value to small';
ELSE
   select unnest(ARRAY[2,8,9]);
END IF;

A: SELECT fields_of_your_choice,
 CASE
  WHEN (placeholder<1000) THEN 'Value to small'
  ELSE  unnest(array_field_name)
 END AS p
FROM your_table;


text:
Q: On the dual of Banach space let $X$ be a (complex) Banach space, and $\{x_n\}$ is a sequence in $X$. Suppose that for any $f\in X'$, $$\sum_{n=1}^\infty |f(x_n)|<\infty.$$ Show that there exists a constant $\mu>0$ such that $$\sum_{n=1}^\infty |f(x_n)|\leq \mu ||f||.$$
Here, $X'$ is the Banach space consisting of all linear bounded functionals on $X$.
clearly,
$$p(f)=\sum_{n=1}^\infty |f(x_n)|$$ is a sub-additive functional on $X'$. Can you use the equivalent norm theorem on Banch space?
I have not get a solution.

A: You can prove the desired as follows. Consider the map from $X'$ to $\ell_1$ defined by $f\mapsto \{f(x_n)\}_{n=1}^\infty$. Show that it satisfies the assumptions of the Closed Graph Theorem, conclude that it is a continuous operator. The desired inequality follows.


text:
Q: Where does Cygwin64 store/look for Python packages? I'm trying to use Cygwin64 to run a python script, but it's not working because for some reason it can't find the module.
Traceback (most recent call last):
File "makeplot.py", line 1, in <module>
    import vplanet
ModuleNotFoundError: No module named 'vplanet'

Where are modules installed in Cygwin64 and How do I make sure my module is installed?

A: It seems you are expecting that Cygwin version of Python should contain any type of module around.
If you look for vplanet, you will find the specific instruction for installation
https://virtualplanetarylaboratory.github.io/vplanet/install.html
python -m pip install vplanet

Have you tried it ?


text:
Q: How to convert, sort and save to CSV MS Access database .mdb file in Python I tried researching the answer but was not able to find a good solution. I have files with  strange extensions .res. I was told that they are MS Access files. Not sure if they are the same as .mdb but I was able to open them in MS Access. How can I open those files, extract necessary data, sort that data and produce .csv file? I tried using this script: http://mazamascience.com/WorkingWithData/?p=168 and mdb tools on Linux. I got some output with errors in terminal but all the files produced were blank. It could be due to encoding. I am not sure. The file is in ASCII encoding I think.
Error: Table fo_Table
Smart_Battery_Data_Table
MCell_Aci_Data_Table
Aux_Global_Data_Table
Smart_Battery_Clock_Stretch_Table
 does not exist in this database.

On Windows I have no idea how to do it. My first step for now is just to dump the necessary table from that database file into .csv. But ideally I need the script to take the file, sort it, extract necessary data, do some calculations (like data in one column divided by data in another column) and save all that stuff into nice .csv.
Thanks a lot. I am not an experienced programmer so please have mercy.

A: Using the generic pyodbc library should do it. Looks like it has already an embedded MS access driver. This question can probably help you out.
I dont have any MS Access database files with me (It has been ages that I dont have to work with them), but following the examples your code should be something like this:
import pyodbc

db_file = r'''/path/to/the/file.res'''
user = 'admin'
password = 'password'
odbc_conn_str = 'DRIVER={Microsoft Access Driver (*.mdb)};DBQ=%s;UID=%s;PWD=%s' % (db_file, user, password)

conn = pyodbc.connect(odbc_conn_str)

cursor = conn.cursor()

cursor.execute("select * from table order by some_column")

for row in cursor.fetchall():
    print ", ".join((row.column1, row.column2, row.columnN))


text:
Q: Can you make electricity from the bound charges in magnets? Magnetostatics is the study of magnetic fields in systems where the currents are steady. If inside magnets that give off magnetic fields there are bound charges, is there any possible way to make them free charges and therefore get electricity from them?

A:
if inside magnets ... there are bound charges, is there any possible way to make them freee charges and therefore get electrity from them?

Hardly.
Let us see, how permanent magnets could be made. You use materials which obey a strong magnetic dipole moment, melt the material to powder and press (sinter) the powder under the influence of a strong external magnetic field to a rigid body.
What happens in detail?

The overall magnetic behavior of a material can vary widely, depending on the structure of the material, particularly on its electron configuration. (Wikipedia)

Under the electron configuration you have to understand the sum of the magnetic dipole moments of the involved subatomic particles. Usually the are oriented in all directions. Under the influence of the external magnetic field they get aligned. This happens mostly by rotation into the aligned direction. No electric current is involved.
To destroy the alignment you may drop the magnet but this is not recommended because you can injure yourself. Or you heat the magnet and at some moment the increasing vibrations on the atomic level destroy the magnetization. But hardly any electric current will occur.


text:
Q: Ubuntu 20.04 loses connexion after sometime I hope I will find any help here.
I have a server running Ubuntu 20.04 LTS 64bit fresh. Everything is working fine.
I installed there only docker where I run another ubuntu container which is quite heavy like 40Go.
I can run this ubuntu container and everything inside.
But suddenly, I get thrown out of server when using ssh and from that point of time, nothing works. I can neither access the port 80 on the browser nor reconnect with ssh.
I always need to hard reboot the server.
I took a look at the journal log and I saw the following:
Aug 31 10:51:17 myserverXXX systemd[1]: Finished Create System Users.
Aug 31 10:51:17 myserverXXX systemd[1]: Starting Create Static Device Nodes in /dev...
Aug 31 10:51:17 myserverXXX systemd[1]: Started Journal Service.
Aug 31 10:51:17 myserverXXX systemd-journald[27]: Received client request to flush runtime journal.
Aug 31 10:51:17 myserverXXX systemd-logind[918]: Watching system buttons on /dev/input/event2 (Power Button)
Aug 31 10:51:17 myserverXXX systemd-logind[918]: Watching system buttons on /dev/input/event0 (Sleep Button)
Aug 31 10:51:17 myserverXXX systemd-logind[918]: Watching system buttons on /dev/input/event1 (Power Button)
Aug 31 10:51:18 myserverXXX systemd-logind[918]: Watching system buttons on /dev/input/event3 (HID 0557:2419)
Aug 31 10:51:18 myserverXXX systemd-networkd[586]: vethf4b126a: Gained IPv6LL
Aug 31 10:51:18 myserverXXX systemd-journald[27]: File /var/log/journal/4e719740d1fa86abf29ff1e361223c8a/system.journal corrupted or uncleanly shut down, renaming and replacing.
Aug 31 10:51:18 myserverXXX audit[162669]: AVC apparmor="STATUS" operation="profile_replace" info="same as current profile, skipping" profile="unconfined" name="nvidia_modprobe" pid=162669 comm="apparmor_parser"
Aug 31 10:51:18 myserverXXX audit[162669]: AVC apparmor="STATUS" operation="profile_replace" info="same as current profile, skipping" profile="unconfined" name="nvidia_modprobe//kmod" pid=162669 comm="apparmor_parser"
Aug 31 10:51:18 myserverXXX audit[162668]: AVC apparmor="STATUS" operation="profile_replace" info="same as current profile, skipping" profile="unconfined" name="lsb_release" pid=162668 comm="apparmor_parser"
Aug 31 10:51:18 myserverXXX audit[162670]: AVC apparmor="STATUS" operation="profile_replace" info="same as current profile, skipping" profile="unconfined" name="/usr/bin/man" pid=162670 comm="apparmor_parser"
Aug 31 10:51:18 myserverXXX audit[162670]: AVC apparmor="STATUS" operation="profile_replace" info="same as current profile, skipping" profile="unconfined" name="man_filter" pid=162670 comm="apparmor_parser"
Aug 31 10:51:18 myserverXXX audit[162670]: AVC apparmor="STATUS" operation="profile_replace" info="same as current profile, skipping" profile="unconfined" name="man_groff" pid=162670 comm="apparmor_parser"
Aug 31 10:51:18 myserverXXX kernel: audit: type=1400 audit(1630403478.827:59): apparmor="STATUS" operation="profile_replace" info="same as current profile, skipping" profile="unconfined" name="nvidia_modprobe" pid=162669 comm="apparmor_parser"
Aug 31 10:51:18 myserverXXX kernel: audit: type=1400 audit(1630403478.827:60): apparmor="STATUS" operation="profile_replace" info="same as current profile, skipping" profile="unconfined" name="nvidia_modprobe//kmod" pid=162669 comm="apparmor_parser"
Aug 31 10:51:18 myserverXXX kernel: audit: type=1400 audit(1630403478.827:61): apparmor="STATUS" operation="profile_replace" info="same as current profile, skipping" profile="unconfined" name="lsb_release" pid=162668 comm="apparmor_parser"
Aug 31 10:51:18 myserverXXX kernel: audit: type=1400 audit(1630403478.827:62): apparmor="STATUS" operation="profile_replace" info="same as current profile, skipping" profile="unconfined" name="/usr/bin/man" pid=162670 comm="apparmor_parser"
Aug 31 10:51:18 myserverXXX kernel: audit: type=1400 audit(1630403478.827:63): apparmor="STATUS" operation="profile_replace" info="same as current profile, skipping" profile="unconfined" name="man_filter" pid=162670 comm="apparmor_parser"
Aug 31 10:51:18 myserverXXX kernel: audit: type=1400 audit(1630403478.827:64): apparmor="STATUS" operation="profile_replace" info="same as current profile, skipping" profile="unconfined" name="man_groff" pid=162670 comm="apparmor_parser"
Aug 31 10:51:19 myserverXXX kernel: proc: Bad value for 'hidepid'
Aug 31 10:51:19 myserverXXX kernel: proc: Bad value for 'hidepid'
Aug 31 10:51:19 myserverXXX kernel: proc: Bad value for 'hidepid'
Aug 31 10:51:19 myserverXXX kernel: proc: Bad value for 'hidepid'
Aug 31 10:51:22 myserverXXX kernel: proc: Bad value for 'hidepid'
Aug 31 10:51:23 myserverXXX kernel: rfkill: input handler disabled
Aug 31 11:11:23 myserverXXX kernel: PM: suspend entry (s2idle)

Where myserverXXX stands for my server domain.
Please, can someone help me? I'm struggling on this problem since almost one week.
Aug 31 17:32:07 775fcd1e77c8 ModemManager[137]: <info>  [sleep-monitor] system is about to suspend
Aug 31 17:32:07 775fcd1e77c8 NetworkManager[103]: <info>  [1630423927.0678] manager: sleep: sleep requested (sleeping: no  enabled: yes)
Aug 31 17:32:07 775fcd1e77c8 NetworkManager[103]: <info>  [1630423927.0679] manager: NetworkManager state is now ASLEEP
Aug 31 17:32:07 775fcd1e77c8 gnome-shell[558]: Screen lock is locked down, not locking
Aug 31 17:32:07 775fcd1e77c8 systemd[1]: Reached target Sleep.
Aug 31 17:32:07 775fcd1e77c8 systemd[1]: Starting Suspend...
Aug 31 17:32:07 775fcd1e77c8 systemd-sleep[7303]: Suspending system...
Aug 31 17:32:07 775fcd1e77c8 kernel: PM: suspend entry (s2idle)

Thanks in advance.


text:
Q: Is $L=\{\,a^ib^jc^k \mid i=2j=3k\, \}$ a Turing language? Is $L= \{a^ib^jc^k \mid i=2j=3k\}$ a Turing language?
At first I thought it was possible to scan the tape and for each $c$ delete the amount of $a$ by the amount of $b$, it works when the input is $aaaaaabbbcc$ but if the input is $aaaaaaaaaaaabbbbbbcccc$ it is not.
How can I figure it out the algorithm, which technique can I use to solve this?

A: A simple way to solve your question is to start with the context-sensitive language $C= \{a^nb^nc^n \mid n \geqslant 0\}$ and use the fact that the class of context-sensitive languages is closed under non-erasing morphisms. Now, consider the non-erasing morphism $f$ defined by $f(a) = a^6$, $f(b) = b^3$ and $f(c) = c^2$. Then
$$f(C)  = \{a^{6n}b^{3n}c^{2n} \mid n \geqslant 0 \} = L.$$ Thus $L$ is context-sensitive.


text:
Q: Shows Logout Button after confirm login and goes to activity while login using Facebook Login Integration Android I am using Facebook login integration for my android application. I can login and go to the next activity but the problem is that , after login using facebook login button  it shows facebook logout button for a while after clicking yes for confirm page and goes to my activity. Please help me to solve this problem.

A: Facebook login button if you success login.. it will change the wording from "Log In Facebook" to "Logout".. if you dont want to see that, just setVisibility GONE or Intent to desired activity. If you using intent, set the flag like below
Intent next = new Intent(getApplicationContext(), MenuActivity.class);
next.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(next);

Below is the example of facebook loginbutton
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {

            @Override
            public void onSuccess(LoginResult loginResult) {
                GraphRequest request = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(), (object, response) -> {
                    // hide this facebook login button
                    // Intent to your desired activity

                });
                Bundle parameters = new Bundle();
                parameters.putString("fields", "id,name,email,birthday,gender,first_name,last_name");
                request.setParameters(parameters);
                request.executeAsync();
            }

            @Override
            public void onCancel() {
                Toast.makeText(getApplicationContext(), Message.LOGINCANCEL, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(FacebookException e) {
                Toast.makeText(getApplicationContext(), Message.LOGINFAILED, Toast.LENGTH_SHORT).show();
            }
        });

If you want to change the "Logout" facebook button to "Log in Facebook" use below code.. just create BUtton and do onClick() to trigger below code
if (AccessToken.getCurrentAccessToken() != null && com.facebook.Profile.getCurrentProfile() != null){
            LoginManager.getInstance().logOut();
        }


text:
Q: Can "standalone" ever be an adverb? Is it correct to use word standalone as an adverb?
All the major dictionaries only mention that it is an adjective. However, I've seen many sources use it as an adverb. For example:

This program can be run standalone.

Does this usage make sense? If not, then what's the adverbial form corresponding to standalone?


text:
Q: Linux network troubleshooting and debugging From time to time, Linux and Unix users are faced with various network problems. Many of these problems are presented here and at some other troubleshooting forums, but they are very concrete and contain a lot of additional technical information, and sometimes it's rather difficult to understand the main point and the real reason of buggy system behavior.
By asking this question, my intention is to start a community wiki page which allows generalizing our network troubleshooting and debugging experience. I hope the Linux and Unix users will be able to easier recognize and solve ("divide and conquer") their network problems using this page.
The parent of this page should be Best practise to diagnose problems. But here we should focus on troubleshooting the network problems from user- and kernel-space.
I suppose, if you:

*

*share the information about using some great network diagnostic tool with concrete usage examples and examples of network bugs which they help to catch,

*share the link to the great network tutorial connected with this subject,

*tell us about a general method or recipe which allows to tackle some class of network problems, or

*share information about your tool set for network debugging and troubleshooting

then it perfectly fits this topic.

I'll begin by sharing the link to various diagnostic tools and a 12 year old simple tutorial. Also this Arch Linux tutorial seems to have actual information about our subject. And for diving into Linux networking, we definitely need to visit the Linux Networking-HOWTO.

A: Cabling problems can exist.  If you have access to the hardware, ensure that the cables are all plugged in and mechanically engaged. If you can see routers or ethernet interfaces, ensure that the link lights are on.
Remotely, you have to depend on ethtool and mii-tool.
[root@flask ~]# ethtool eth0
Settings for eth0:
        Supported ports: [ TP MII ]
        Supported link modes:   10baseT/Half 10baseT/Full
                                100baseT/Half 100baseT/Full
        Supported pause frame use: No
        Supports auto-negotiation: Yes
        Advertised link modes:  10baseT/Half 10baseT/Full
                                100baseT/Half 100baseT/Full
        Advertised pause frame use: Symmetric
        Advertised auto-negotiation: Yes
        Speed: 10Mb/s
        Duplex: Half
        Port: MII
        PHYAD: 24
        Transceiver: internal
        Auto-negotiation: on
        Supports Wake-on: g
        Wake-on: d
        Current message level: 0x00000001 (1)
                               drv
        Link detected: yes

"Link detected: yes" is good, but 10Mb/s and Half duplex are not good, as the NIC on that computer can do better.  I need to figure out if the NIC is goofed up or the cable is.  Another computer plugged into the same router says 100Mb/s, Full duplex.

A: A surprising number of "network problems" boil down to DNS problems of one kind or another. Initial troubleshooting should use ping -n w.x.y.z in order to leave out DNS resolution of a hostname, and just check IP connectivity. After that, use route -n to check the default IP route without DNS resolution.
After verifying IP connectivity and routing, nslookup, host, and dig can yield information. Remember that "locking up" can indicate that DNS timeouts are occurring.
Don't forget to check the existence and the contents of /etc/resolv.conf. DHCP clients change that file with every lease, and sometimes they get it wrong, or if disk space is tight, an update might not happen.

A: I think, general principles of network troubleshooting are:

*

*Find out at what level of the TCP/IP stack (or some other stack) the problem occurs.

*Understand what the correct system behavior is and what the deviation from the normal system state is.

*Try to express the problem in one sentence or in several words.

*Using obtained information from the buggy system, your own experience, and experience of other people (Google, various forums, etc.), try to solve the problem until success (or failure).

*If you fail, ask other people about help or some advice.

As for me, I usually obtain all required information using all needed tools, and try to match this information to my experience. Deciding what level of the network stack contains the bug helps to cut off unlikely variants. Using experience of other people helps to solve the problems quickly, but often it leads to a situation, where I can solve some problem without its understanding and if this problem occurs again, it's impossible for me to tackle it again without the Internet.
And in general, I don't know how I solve network problems. It seems that there is some magic function in my brain named SolveNetworkProblem(information_about_system_state, my_experience, people_experience), which could sometimes return exactly the right answer, and also could sometimes fail (like here TCP dies on a Linux laptop).
I usually use utils from this set for network debugging:

*

*ifconfig (or ip link, ip addr) - for obtaining information about network interfaces

*ping - for validating if the target host is accessible from my machine. ping could also be used for basic DNS diagnostics - we could ping a host by its IP address or by its hostname and then decide if DNS works at all. And then traceroute or tracepath or mtr to look what's going on on the way there.

*dig - diagnose everything DNS

*dmesg | less or dmesg | tail or dmesg | grep -i error - for understanding what the Linux kernel thinks about some trouble.

*netstat -antp + | grep smth - my most popular usage of the netstat command, which shows information about TCP connections. Often I perform some filtering using grep. See also the new ss command (from iproute2 the new standard suite of Linux networking tools) and lsof as in lsof -ai tcp -c some-cmd.

*telnet <host> <port> - is very useful for communicating with various TCP services (e.g. on SMTP, HTTP protocols), also we could check general opportunity to connect to some TCP port.

*iptables-save (on Linux) - to dump the full iptables tables

*ethtool - get all the network interface card parameters (status of the link, speed, offload parameters...)

*socat - the Swiss army tool to test all network protocols (UDP, multicast, SCTP...). Especially useful (more so than telnet) with a few -d options.

*iperf - to test bandwidth availability

*openssl (s_client, ocsp, x509...) to debug all SSL/TLS/PKI issues.

*wireshark - the powerful tool for capturing and analyzing network traffic, which allows you to analyze and catch many network bugs.

*iftop - show big users on the network/router.

*iptstate (on Linux) - current view of the firewall's connection tracking.

*arp (or the new ip neigh in Linux) - show the ARP table status.

*route or the newer (on Linux) ip route - show the routing table status.

*strace (or truss, dtrace or tusc depending on the system) - is a useful tool that shows which system calls the problematic process performs. It also shows error codes (errno) when system calls fail. This information often says enough for understanding the system behavior and solving a problem. Alternatively, using breakpoints on some networking functions in gdb can let you find out when they are made and with which arguments.

*to investigate firewall issues on Linux: iptables -nvL shows how many packets are matched by each rule (iptables -Z to zero the counters). The LOG target inserted in the firewall chains is useful to see which packets reach them and how they have already been transformed when they get there. To get further, NFLOG (associated with ulogd) will log the full packet.


text:
Q: In mocha unit test, how to mock a global variable? How are you doing?
I am developing unit tests with mocha, and I need to mock a global variable.
let logger = {
    info: () => ({}),
};

exports.findCallCenters = (req, res, next) => {
    logger.info("findCallCenters", req.params);
};

When I run my test, it says that logger is undefined. That's why I need to mock it.
I don't know how to proceed to test my function.
Thanks for your help!


text:
Q: Why my nginx redirection doesnt work I`m trying to do redirection via Nginx
webmail.mywebsite.to to gmail.com
I`m trying with
server {
  listen      80;
  server_name webmail.mywebsite.com;
  return      301 https://www.gmail.com;
}

But I stil get error

webmail.mywebsite.com server IP address could not be found.

I'm usin ec2 (where I install SSL ) and I'm using Route53 for my domain too ..

A: Based on the notification you attached, webmail.mywebsite.com not resolv in your network.
Im suggest you to add A record for webmail.mywebsite.com on your DNS Zone.
If you already add A record for webmail.mywebsite.com then you must be waiting for DNS Propagation to resolving your DNS Record to all network.
You can do a make sure by mapping the hostname locally at /etc/hosts (linux) or c:\Windows\System32\Drivers\etc\hosts (windows).


text:
Q: Why is openstack Keystone not listening on port 5000 I have install keystone following this link . The installation process was okay until I got the point where I need to ask for token. The admin token request was okay but I could not get a token for the non-admin user (demo user). I check network ports and it seems keystone is not listening on port 5000. Previously, keystone is not listening on any port and I have to change the port number in /etc/apache2/sites-available/keystone.conf to 35357. After the change and restarting apache2, I was able to get the token for admin but could not get the token for the non admin user. I'm using ubuntu 18.04.
Can anyone help solve this problem.
ubuntu@controller:~$ sudo netstat -plnt
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 0.0.0.0:4369            0.0.0.0:*               LISTEN      23399/epmd
tcp        0      0 127.0.0.53:53           0.0.0.0:*               LISTEN      3328/systemd-resolv
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      1824/sshd
tcp        0      0 0.0.0.0:25672           0.0.0.0:*               LISTEN      23541/beam.smp
tcp        0      0 192.168.9.111:3306      0.0.0.0:*               LISTEN      22608/mysqld
tcp        0      0 192.168.9.111:11211     0.0.0.0:*               LISTEN      24834/memcached
tcp6       0      0 :::80                   :::*                    LISTEN      11240/apache2
tcp6       0      0 :::4369                 :::*                    LISTEN      23399/epmd
tcp6       0      0 :::22                   :::*                    LISTEN      1824/sshd
tcp6       0      0 :::35357                :::*                    LISTEN      11240/apache2
tcp6       0      0 :::5672                 :::*                    LISTEN      23541/beam.smp

A: I am using the stein version.
Did you change the 5000 port to 35357 port in keystone.conf setting?
For me, both 5000 and 35357 port settings were required.
My settings were as below.
Listen 5000
Listen 35357

<VirtualHost *:5000>
    WSGIDaemonProcess keystone-public processes=5 threads=1 user=keystone group=keystone display-name=%{GROUP}
    WSGIProcessGroup keystone-public
    WSGIScriptAlias / /usr/bin/keystone-wsgi-public
    WSGIApplicationGroup %{GLOBAL}
    WSGIPassAuthorization On
    <IfVersion >= 2.4>
      ErrorLogFormat "%{cu}t %M"
    </IfVersion>
    ErrorLog /var/log/apache2/keystone.log
    CustomLog /var/log/apache2/keystone_access.log combined

    <Directory /usr/bin>
        <IfVersion >= 2.4>
            Require all granted
        </IfVersion>
        <IfVersion < 2.4>
            Order allow,deny
            Allow from all
        </IfVersion>
    </Directory>
</VirtualHost>

<VirtualHost *:35357>
    WSGIDaemonProcess keystone-admin processes=5 threads=1 user=keystone group=keystone display-name=%{GROUP}
    WSGIProcessGroup keystone-admin
    WSGIScriptAlias / /usr/bin/keystone-wsgi-admin
    WSGIApplicationGroup %{GLOBAL}
    WSGIPassAuthorization On
    <IfVersion >= 2.4>
      ErrorLogFormat "%{cu}t %M"
    </IfVersion>
    ErrorLog /var/log/apache2/keystone.log
    CustomLog /var/log/apache2/keystone_access.log combined

    <Directory /usr/bin>
        <IfVersion >= 2.4>
            Require all granted
        </IfVersion>
        <IfVersion < 2.4>
            Order allow,deny
            Allow from all
        </IfVersion>
    </Directory>
</VirtualHost>

Change the Apache settings and try restarting.
Please check again when port number 5000 and 35357 port are up.
Thank you.


text:
Q: How to submit prompt=consent via ueberauth_google When a user has already given consent for an app (e.g. when a user abandons account creation during an initial attempt, then tries again), Google will not re-prompt for consent unless prompt=consent is passed (see documentation). Without prompting for consent, Google will not provide a refresh token to the calling server. And without a refresh token, the server cannot interact with the user's resources (e.g. sending email on the user's behalf).
ueberauth_google has a mechanism for setting approval_prompt, but this is a different parameter than prompt. Is there a way to send prompt=consent using ueberauth_google? (Note, if I add %26prompt%3Dconsent to the url that ueberauth_google sends me to, then Google does prompt me and our server does receive the refresh token.)

A: On your config.exs you need to add prompt: "consent"
config :ueberauth, Ueberauth,
  providers: [
    google:
      {Ueberauth.Strategy.Google,
       [
         access_type: "offline",
         prompt: "consent",
         default_scope:
           "https://www.googleapis.com/auth/youtube https://www.googleapis.com/auth/youtube.upload https://www.googleapis.com/auth/userinfo.profile"
       ]}
  ]

But this hasn't been merged to ueberauth_google yet. For the time being, you can go to your:
deps/ueberauth_google/lib/ueberauth/strategy/google.ex
And edit this line manually


text:
Q: How to configure alternatives for Python? I am installing python 3.10 without the use of a package manager on Rocky Linux 8 and would like to use alternatives version 1.19.1 (manpage) to manage different versions of python installations in the future.
These are my steps:

*Install prerequisites dnf -y install "Development Tools" (Make sure you also have  wget, openssl-devel, bzip2-devel, libffi-devel)

*Download Python 3.10 from  https://www.python.org/ftp/python/3.10.9/Python-3.10.9.tgz

*unarchive to /opt/python

*In /opt/python/Python-3.10.9 run ./configure --enable-optimizations

*In /opt/python/Python-3.10.9 run make altinstall

*Add a group of alternatives where

*

*link=/usr/bin/python

*name=python

*path=/usr/local/bin/python3.10

*priority=50
alternatives --install /usr/bin/python python /usr/local/bin/python3.10 50
Now I would like to have python3 also point to the same thing that python would be pointing to. I guess I could create a symlink pointing to /usr/bin/python, but I was wondering if I should use alternatives in a way I am not understanding right now?
How ca I achieve that?
I tried alternatives --install /usr/bin/python3 python3 /usr/local/bin/python3.10 50, but this creates a whole new group.
This question makes me realize that maybe alternatives focuses only on the 1 to n relations between what the user types (python) and what it points to (python3.10). rather than a n to n relation. Not sure.

A: You are right because alternatives are built to maintain the relationship between a single command name and a single executable path, therefore it may not be the greatest tool for managing a many-to-many relationship between multiple Python versions and their command names.
You may, however, employ alternatives to operate the python3 command independently of the python command. You may make a new Python3 group with the same link and priority settings as previously, but a different name and path:
alternatives --install /usr/bin/python python /usr/local/bin/python3.10 50 --slave /usr/bin/python3 python3 /usr/local/bin/python3.10

The —slave option establishes a symlink to the same directory as the python command for the python3 command. This implies that both python and python3 will point to the same Python 3.10 installation.
You can even establish separate groups for any future Python versions you install if you wish to handle them individually with alternatives. For example, to signal that Python 2.7 is an older version, you may establish a group with a lower priority number (e.g. 40):
alternatives --install /usr/bin/python python /usr/local/bin/python2.7 40 --slave /usr/bin/python2 python2 /usr/local/bin/python2.7

By altering the alternative with the greatest priority value, you may switch between Python 2.7 and 3.10.


text:
Q: How To 301 Redirect 40k pages without htaccess I know how to redirect a page to other page with htaccess but how to redirect 40k pages without htaccess? I have read from other source, the maximum limit for htaccess is about 1500 line and larger than that will make my web slow.
example, i have:
mysite/book/titlepage1
mysite/book/titlepage2
mysite/book/titlepage3
mysite/book/titlepage4
:
:
mysite/book/titlepage50K

I need redirect for example:
mysite/book/titlepage10
mysite/book/titlepage11
mysite/book/titlepage12
mysite/book/titlepage13
:
:
mysite/book/titlepage40k

to mysite2.com

A: You could make a php code that receives the URL that the user requests and redirects to the right page. If you use PHP, then the server will process the request, and not the computer of the user.


text:
Q: Qwt : align center the date/time label text on an bottom axis With Qwt, I want that the time and the date are both center under the tick under a bottom axis, but the time is still on the left side like in this picture :

I have tried to use
QwtDateScaleDraw::setLabelAlignment(Qt::AlignHCenter|Qt::AlignBottom);

But the time is still on the left.
I have tried to subclass the QwtScaleDraw like this:
class MyDateScaleDraw:public QwtDateScaleDraw
{
public:
    QwtText label(double value) const override
    {
        QwtText txt=QwtDateScaleDraw::label(value);
        txt.setRenderFlags(Qt::AlignHCenter);
        return txt;
    }
};

But the time is still on the left side.
Somebody know how to center the time ?
UPDATE :
I have found in the source code of Qwt this:
const QwtText &QwtAbstractScaleDraw::tickLabel(const QFont &font, double value ) const
{
    QMap<double, QwtText>::const_iterator it = d_data->labelCache.find( value );
    if ( it == d_data->labelCache.end() )
    {
        QwtText lbl = label( value );
        lbl.setRenderFlags( 0 );
        lbl.setLayoutAttribute( QwtText::MinimumLayout );

        ( void )lbl.textSize( font ); // initialize the internal cache

        it = d_data->labelCache.insert( value, lbl );
    }

    return ( *it );
}

It is the method who, I guess, generate the QwtText Label.
It seems that the line 8 set the render flags to '0'. May be it why changing the renderFlags of the label don't change the alignement of the label under the tick.
What do you think ?

A: Found !!!
Instead of override the method
Qt Code:
Switch view
label(double value)

To copy to clipboard, switch view to plain text mode
.
I have to override the drawLabel method of QwtDateScaleDraw :
void drawLabel( QPainter *painter, double value ) const override
        {
                QwtText lbl = tickLabel( painter->font(), value );
                if ( lbl.isEmpty() )
                    return;

                lbl.setRenderFlags(Qt::AlignCenter); //<---- add this line

                QPointF pos = labelPosition( value );

                QSizeF labelSize = lbl.textSize( painter->font() );

                const QTransform transform = labelTransformation( pos, labelSize );

                painter->save();
                painter->setWorldTransform( transform, true );

                lbl.draw ( painter, QRect( QPoint( 0, 0 ), labelSize.toSize() ) );

                painter->restore();

        }

To copy to clipboard, switch view to plain text mode
And after the label is really center !
The setRenderFlags method can not do the job !!!


text:
Q: mysql stored procedure call works manually, but not from java I'm calling a mysql stored procedure from Java like this:
public void deleteMyProduct(final String country, final String someId) throws EntityDoesNotExistException {
        getHibernateTemplate().execute(new HibernateCallback() {

            public Object doInHibernate(final Session session) {
                session.clear();
                Connection con = session.connection();
                try {
                    CallableStatement cst = con.prepareCall("{call deleteProduct( ?, ? )}");
                    cst.setString(1 , country);
                    cst.setString(2 , someId);
                    cst.execute();
                    cst.close();
                }
                catch(SQLException e){
                    logger.error("Error deleting product, someId:  "+ someId, e);
                }
                return null;
            }
        });

It's not successfully deleting the product; however when I run it manually, it does. Any idea what the problem could be?
p.s. the stored procedure is pretty large and contains identifiable info, so I'm not at liberty to post it. However, it's been in production for a while and only recently just stopped working.

A: *

*Are you sure the code is getting executed?

*Are variables country and someId actually correct?

*What does the SQLException say?

*Do get a successful connection - Connection con = session.connection();?

*Are you passing the right types of variables(should you send Int instead of String)?


text:
Q: Working with Umbraco Node factory in ajax webservice I created an .asmx web service which i call via Ajax. i used the following code
Node iLike = Node.GetCurrent().Parent as Node;
       Property Subject = iLike.GetProperty("emailToAdminSubject") as Property;
       Property BodyText = iLike.GetProperty("fbEmailToAdmin") as Property;

but Node.GetCurrent() returning a null. is there any way to get current node in an asmx Web service ?

A: Node.GetCurrent() won't work in the context of a web service. (See this forum topic.) You could pass the current node's Id to the web service with your ajax call and then use...
Node iLike = new Node(id).Parent;

...from there.


text:
Q: Does VS2012 Documentation work with VS2013? I recently decided to try out VS2013 before making the jump from VS2010 and I found that I have to download the help files too. After searching online, it appears there is no ISO of the VS2013 documentation. I rather found documentation for VS2012 and this VS Help Downloader.
What I would like to know is:

Does Visual Studio 2013 use the same documentation as Visual Studio 2012?

I need to be sure of this before I commence downloading the fairly large VS2012 Documentation ISO on my slow internet connection.

A: The short answer is "yes", any VS2012 Help Viewer Content you have downloaded/installed will be used by the VS2013 Help Viewer. Additionally, when you use VS2013's Help Viewer to install help from online you may notice that only VS2012 help is (currently) available (there is no VS2013-specific Help Viewer content, yet.)
By default VS2013 uses MSDN Online, which is a change from prior VS versions (which relied on a local Help and/or MSDN installation.) This is why the VS2013 installation behaves differently and does not prompt for your Help preferences when installation finishes.
If you just want to download for offline use rather than constantly load content from online, from VS2013 navigate to Main Menu -> Help > Set Help Preference -> Launch in Help Viewer, this should prompt you to download the documentation if not already installed. You can also use the downloader built into the latest Help Viewer to download any content you're missing.
If you want to download help once and store it for later such as for multiple installations, limited/paid-for bandwidth, etc then you can consider using the Visual Studio 2012/2013 Help Downloader (an open-source project on CodePlex.) This allows you to download the content files and then import them into any installation of Help Viewer.

A: I have not used VS 2012. i m using VS 2013. after hectic search i found the following link for documentation from microsoft.com for VS 2012 and VS 2013. whatever your choice you can go for it
http://www.microsoft.com/en-us/download/details.aspx?id=34794


text:
Q: Java comparator for sorting double-nested generics array With Java 17 I want to compare map entries based upon some criteria, where the map entries are Java classes associated with some value, like this:
Comparator<Map.Entry<Class<?>, Integer>> MY_COMPARATOR =
    new Comparator<Map.Entry<Class<?>, Integer>>() { … }

Later I have a list of a list of classes and their associated values (whether it's counts, memory size, or whatever). The twist is that my code is so refined (tongue in cheek) that I happen to know that all these classes extend from FooBar:
List<Map.Entry<Class<? extends FooBar>, Integer>> foobarValues = new ArrayList<>();

Now I just want to sort those map entries using MY_COMPARATOR (to find the smallest/largest classes, the classes most encountered, or whatever MY_COMPARATOR uses as its criteria). But this doesn't work:
java.util.Collections.sort(foobarValues, MY_COMPARATOR);

Java (actually Eclipse 2022-09) tells me:

The method sort(List<T>, Comparator<? super T>) in the type Collections is not applicable for the arguments (List<Map.Entry<Class<? extends FooBar>,Integer>>, Comparator<Map.Entry<Class<?>,Integer>>)

I've been working with Java generics for a long time, and my best simplified explanation of what's happening is that the ? super T in Collections.sort() "hides" the lower layer of generics, and that ? super Map.Entry<Class<?>> has no relation to ? super Map.Entry<Class<? extends FooBar>>. (But still, really?.) Actually my mind can't quite grasp the full intricacies of the problem.
But let's say I don't care so much about the problem; I just want the code to work with no warnings. You and I know that the comparator can work with any class that is possible to exist, so it will never cause a ClassCastException and it will never cause heap pollution, and it will never even sneak into your house at night and kill your bamboo plant.
How can I tell Java that it's OK for me to use this comparator? This does not work:
Collections.sort(foo, (Comparator<Map.Entry<Class<? extends FooBar>, Integer>>)MY_COMPARATOR);

I would be happy casting the list being sorted, but this doesn't work either:
Collections.sort((List<Map.Entry<Class<?>, Integer>>)foo, MY_COMPARATOR);

This does work!
Collections.sort(foo, (Comparator<Map.Entry<Class<? extends FooBar>, Integer>>)(Object)comparator);

But to use it I have to add @SuppressWarnings("unchecked"), and Java 17 javac with -Xlint:all still complains, and besides I feel dirty using it.
I would be content with some workaround that would allow me to suppress the warning with @SuppressWarnings("unchecked") as long as javac lint still didn't complain. But the intermediate cast to Object is too much of a kludge for me to accept.
What should I be doing?

A: I would suggest that you declare the comparator by applying the PECS principle. It should have the type:
Comparator<Map.Entry<? extends Class<?>, Integer>>

Both type parameters for Map.Entry should have ? extends (though just the first one is enough to fix the error) because a map entry is a producer of its keys and value types.
You could also add ? super to the type parameter of Comparator, since the comparator is a consumer of map entries, but that is not needed here because it is actually already written in the method signature of sort.
void sort(Comparator<? super E> c)

After that, you can write:
foobarValues.sort(MY_COMPARATOR);

If you cannot change the type of MY_COMPARATOR, one way to get the compiler to "just shut up" is to cast to Object first:
(Comparator<Map.Entry<Class<? extends FooBar>, Integer>>) (Object) MY_COMPARATOR

Casting from Object to a parameterised type is an unchecked cast, which is presumably what you are looking for.
This unchecked cast would be safe as far as I know, since a map entry cannot be used as a consumer of its key type. You can only get, but not set, its key.


text:
Q: Resizing an Image? I am trying to get a big size image programmatically , but app is crashing.
Here is what I'm doing:
public static Bitmap getImageFromResult(Context context, int resultCode, Intent imageReturnedIntent) {
    Bitmap bitmap = null;
    File imageFile = getTempFile(context);

    if (resultCode == Activity.RESULT_OK) {
        Uri selectedImage;
        boolean isCamera = (imageReturnedIntent == null || imageReturnedIntent.getData() == null || imageReturnedIntent.getData().toString().contains(imageFile.toString()));

        if (isCamera) {
            // From Camera
            selectedImage = Uri.fromFile(imageFile);
        } else {
            // From Storage
            selectedImage = imageReturnedIntent.getData();
        }

        //bitmap = getResizedImage(context, selectedImage);
        bitmap = getResizedImage(context, selectedImage);

    }
    return bitmap;
}

And the resizemethod` :
//*********** Resize to avoid using too much Memory loading Big Images (2560*1920) ********//

private static Bitmap getResizedImage(Context context, Uri selectedImage) {
    Bitmap resizedBitmap = null;
    int[] sampleSizes = new int[]{8,7,6,5, 4, 3, 2, 1};

    int i = 0;
    do {
        resizedBitmap = decodeBitmap(context, selectedImage, sampleSizes[i]);
        i++;

    } while (resizedBitmap.getWidth() < minWidthQuality && i < sampleSizes.length);

    return resizedBitmap;
}

A: Try this - you can resize the Bitmap to another height/width
 public static Bitmap getResizedBitmap(Bitmap bm, float newHeight, float newWidth) {
        float width = bm.getWidth();
        float height = bm.getHeight();
        float scaleWidth = (newWidth) / width;
        float scaleHeight = (newHeight) / height;
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        return Bitmap.createBitmap(bm, 0, 0, (int) width, (int) height, matrix, false);
    }

Then just make your new Bitmap
 Bitmap bitmap = BitmapFactory.decodeFile(pathname);
 Bitmap newBitmap = getResizedBitmap(bitmap,400,320);

A: If you are getting image live from internet then obviously you need to first download the image but it will take time according to internet speed  or you want to load image from memory  then you can apply this  stack over answer
method here to get decrease the image quality