text:
Q: What could cause one model's views to find another controller's helper file? Rails 2.3.11
I have a view site.com/events/past which sorts a list of events according to either date or category (depending on which is specified).  The sorting is done in the events helper.  For some reason, views/events/past.html.erb is finding the methods (by the same name) in /helpers/places_helper.rb instead of /helpers/events_helper.rb.
What could be causing this, and how can I fix it?

A: All helpers are included by default on all controllers due to this method call:
class ApplicationController < ActionController::Base
  helper :all
end

To change this behavior you will have to remove this call (or change it to helper :application) and at each controller add a:
helper :places

To include specific helpers as needed.


text:
Q: Control 3 instances of a class, using 3 sets of GUI I have 3 identical physical instruments. I can control each instrument separately by instanciating an InstrumentDriver class.
I have a Ui_MainWindow class, automatically created from Qt Designer (via pyuic5). This class contains "duplicated" controls: I have 3 identical sets of UI controls (buttons, lineEdits, etc.), each one is used to control one instrument.
I have a InstrumentGui class doing the mapping between the UI elements defined in Ui_MainWindow and the actions allowed by InstrumentDriver. InstrumentGui is also instanciated 3 times.
I don't know how to bind a GUI control to a specific instance of InstrumentDriver class:
class InstrumentGui :
    def __init__(self, instrument: InstrumentDriver, ui: Ui_MainWindow, type: str)
        # How do I reach toolButton_startA if type=="A",
        # toolButton_startB if type == "B", etc.?
        ui.toolButton_startA.clicked.connect(instrument.start)

ui = Ui_MainWindow()

instrumentA = InstrumentDriver(address=1)
instrumentGuiA = InstrumentGui(instrumentA, ui, "A")

instrumentB = InstrumentDriver(address=2)
instrumentGuiB = InstrumentGui(instrumentB, ui, "B")

instrumentC = InstrumentDriver(address=3)
instrumentGuiC = InstrumentGui(instrumentC, ui, "C")

My first idea was to use variable variable name, something like setattr(self, "start_button", "toolButton_start"+type), but appart from the fact that I didn't manage to get it work, I read everywhere that it is a bad practice.
What is the smart way of doing that, if possible keeping the Qt Designer way of building GUI layout?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Typing indicator in Microsoft Teams through Graph API - chatMessageType 'typing'? Currently using the graph API to show messages from a chat outside of microsoft teams.
I am looking for a way to display a typing indicator in my app. However, I need to know when a user is typing in an ms teams chat through the Graph API and can not find anything in the docs about this other than this mention of a 'typing' chatMessageType for messageType.
I don't know what this 'typing' type is or when it comes about. I am subscribed to messages in a chat but they all come through as 'message' when they're sent or after they're edited (editing the message/typing in the chat box does not trigger any events)
(I am aware of the bot framework but would rather not use it at this time)
Thanks

A: Adding comment as answer for more visibility.
Currently Graph API do not process Typing indicators. So it is not possible to know when a user is typing in an MS Teams chat through the Graph API.
You can raise it on Microsoft Uservoice.


text:
Q: Bidirectional communication between unmanaged C++ (no CLR) and managed C# I am working with a C++ MFC plug-in dll which is automatically launched from an off-the-shelf application at runtime.  I need to modify the plugin to support bidirectional communication with a .NET based C# application.
I have access to the plugin source code but I am not able to change the C++ project to use /clr.  I get a runtime error from the off-the-shelf application:
'r6033 attempt to use msil code from this assembly during native code initialization'
I have tried to use "#pragma unmanaged" around the Main method with no luck.  So I decided to go the COM route.
I have successfully created a COM based C# dll with a UI and methods implemented which I can call from C++.  That gets me one direction.  I need to implement a way of making calls to the C++ plugin from the C# application.  I started down the path of events. I created an event in C# which are raised on the C# side from the new UI but I was not able to figure out how to create and hook to the events on the C++ side.  Any help would be appreciated.
Here is the C# COM Code:
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.IO;

namespace MyInterop
{
[Guid("03AD5D2D-2AFD-439f-8713-A4EC0705B4D9")]
public interface IMyDotNetInterface
{
    void ShowCOMDialog();
}

[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
[Guid("63058ba6-5675-43d6-b38b-fd261fe64950")]
public interface IIntelliWaveEvents
{
    [DispId(1)]
    void CallIWave(string a_IWaveCommand);
}

[ClassInterface(ClassInterfaceType.None)]
[ComSourceInterfaces(typeof(IIntelliWaveEvents))]
[Guid("0490E147-F2D2-4909-A4B8-3533D2F264D0")]
public class MyDotNetClass : IMyDotNetInterface
{

    public IIntelliWaveEvents callbackObject;

    // Need a public default constructor for COM Interop.
    public MyDotNetClass()
    { }

    public void ShowCOMDialog()
    {
        MainForm frm = new MainForm()
        {
            StartPosition = FormStartPosition.CenterScreen,
            TopMost = true
        };

        frm.CallIWave += new MainForm.CallIWaveEventHandler(frm_CallIWave);
        frm.Show();
    }

    void frm_CallIWave(object sender, Events.IWaveEvents.CallIWaveEventArgs e)
    {
        string filename = @"C:\Companies\ComEvent.txt";

        File.WriteAllText(filename, "COM Event Called at " + DateTime.Now);

        //Pass the event to c++
        if (callbackObject != null)
        {
            callbackObject.CallIWave(e.Message);
        }
    }
}
}

Here is the interface WaveDLL_PAI.cpp code:
#include "stdafx.h"
#include "WaveDLL_PAI.h"
#include "IUserPrograms1.h"

using namespace std;

#import "C:\Program Files\SampleCOM\com.MyInterop.tlb" named_guids raw_interfaces_only
using namespace MyInterop;

//------------------------------------------------------------------------
// This function must exist in all PlugIn(s).
// It creates an instance of the API class and returns a pointer to it.
HRESULT CreateInstance(void **p)
{
*p = new CWaveDLL_PAI();
return (*p != NULL);
}

//---------------------------------------------------------------------------------------------------
// Initialize native variables here
CWaveDLL_PAI::CWaveDLL_PAI() : CWaveDLL_BaseI()
{

}

//---------------------------------------------------------------------------------------------------
// deallocate any memory here
CWaveDLL_PAI::~CWaveDLL_PAI()
{
Release();
}

//---------------------------------------------------------------------------------------------------
// This function releases any memory allocated for this class
ULONG CWaveDLL_PAI::Release()
{
return 0;
}

//---------------------------------------------------------------------------------------------------
// This function must be used to create the class including memory allocation.
// Allocate memory or objects here only.
// Do not display any window or dialog here
ULONG CWaveDLL_PAI::Create(CWnd *pParent, void *a, void *b, void *c)
{
CoInitialize(NULL);   //Initialize all COM Components

MyInterop::IMyDotNetInterfacePtr pDotNetCOMPtr;
HRESULT hRes =  pDotNetCOMPtr.CreateInstance(MyInterop::CLSID_MyDotNetClass);
if (hRes == S_OK)
{
    BSTR str;
    pDotNetCOMPtr->ShowCOMDialog(); //call .NET COM exported function ShowDialog ()
}

CoUninitialize();   //DeInitialize all COM Components

return true;
}

//---------------------------------------------------------------------------------------------------
// This function gives the PlugIn access to data and controls
// This function must be defined and have the code listed below.
long CWaveDLL_PAI::SetData(CUserControl *ctrl, SIntelliWaveDataExt *data, LPCTSTR path)
{
CWaveDLL_BaseI::SetData(ctrl,data,path);
return true;
}

Here is the interface WaveDLL_PAI.h Code:
#include "WaveDLL_BaseI.h"

class AFX_EXT_CLASS CWaveDLL_PAI : public CWaveDLL_BaseI
{
public:

int MyVariable;

CWaveDLL_PAI();
~CWaveDLL_PAI();

int    MyFunction(int hello = 0);

ULONG Release();
ULONG Create(CWnd *pParent=0, void *a = 0, void *b = 0, void *c = 0);

long SetData(CUserControl *ctrl, SIntelliWaveDataExt *data, LPCTSTR path = 0);
long Execute(LPCTSTR cmd, void *a = 0, void *b = 0, void *c = 0);
};

Here is the WaveDLL_PA.cpp Code:
#include "stdafx.h"
#include <afxdllx.h>

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

HINSTANCE hInstanceOptic01;

static AFX_EXTENSION_MODULE WaveDLL_PADLL = { NULL, NULL };

extern "C" int APIENTRY
DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved)
{
// Remove this if you use lpReserved
UNREFERENCED_PARAMETER(lpReserved);

hInstanceOptic01 = hInstance;

if (dwReason == DLL_PROCESS_ATTACH)
{
    TRACE0("WaveDLL_PA.DLL Initializing!\n");

    // Extension DLL one-time initialization
    if (!AfxInitExtensionModule(WaveDLL_PADLL, hInstance))
        return 0;

    // Insert this DLL into the resource chain
    // NOTE: If this Extension DLL is being implicitly linked to by
    //  an MFC Regular DLL (such as an ActiveX Control)
    //  instead of an MFC application, then you will want to
    //  remove this line from DllMain and put it in a separate
    //  function exported from this Extension DLL.  The Regular DLL
    //  that uses this Extension DLL should then explicitly call that
    //  function to initialize this Extension DLL.  Otherwise,
    //  the CDynLinkLibrary object will not be attached to the
    //  Regular DLL's resource chain, and serious problems will
    //  result.

    new CDynLinkLibrary(WaveDLL_PADLL);
}
else if (dwReason == DLL_PROCESS_DETACH)
{
    TRACE0("WaveDLL_PA.DLL Terminating!\n");
    // Terminate the library before destructors are called
    AfxTermExtensionModule(WaveDLL_PADLL);
}
return 1;   // ok
}


text:
Q: hadoop-connectors/gcsio - no message in exception GoogleCloudStorageExceptions.java
It looks like HttpResponseException is created without message.
  public static GoogleJsonResponseException createJsonResponseException(
      GoogleJsonError e, HttpHeaders responseHeaders) {
    if (e != null) {
// ISSUE: HttpResponseException.Builder() constructor below doesn't set HttpResponseException.Builder.message.
//        HttpResponseException.Builder.message is passed to Throwable.detailMessage that is printed in Throwable.toString().
//        As a result, received from server exception doesn't print any information, it prints: null.
      return new GoogleJsonResponseException(
          new HttpResponseException.Builder(e.getCode(), e.getMessage(), responseHeaders), e);
    }
    return null;
  }


text:
Q: How to be warned when downgrading a package will break a depender When I want to install a package, but that package depends on a package version older than what is installed on my system, how can I determine whether downgrading the package will break any other packages that may have depended on a higher version?
I've had to do this for a lot of packages since reinstalling Ubuntu 12.10 over 12.04. is that a related problem?
What I've tried:-

*

*Searching Ubuntu Forums and AskUbuntu (not relevant questions)

*Googling (again, gives irrelevant or no results)

*Trying it out for myself (couldn't find a set of suitable packages to try on)

I apologize if this question has been asked before already on this site as I probably hadn't framed my searches with the correct terminology. 10x.

A: Let's take evince and gedit as examples. Open a terminal and run:
apt-cache show evince | grep Conflicts
apt-cache show evince | grep Breaks

This pair of commands will tell you if evince breaks or conflicts with something else. In my case I get
$ apt-cache show evince | grep Conflicts
Conflicts: evince-gtk

$ apt-cache show evince | grep Breaks
<blank>

so evince conflicts with evince-gtk that means they shouldn't be installed at the same time (APT will complain if this ever happens).
In my case evince doesn't declare to break any package so let's skip to gedit. Now, run
$ apt-cache show gedit | grep Conflicts
<blank>

$ apt-cache show gedit | grep Breaks
Breaks: gedit-plugins (<< 2.91)

As you can see gedit does not conflict with anyone. Nonetheless, it does break the package called gedit-plugins for versions strictly less than 2.91. That means gedit-plugins most be more recent than this version to work correctly with gedit and in particular APT will refuse to install gedit unless you remove gedit-plugins (<< 2.91) first.
Notice that even though the gedit-plugins in the official repositories are recent enough, you might want to download (from github maybe) a particular GEdit plugin that is older, this line serves you as a remainder that this older version should not work with the current GEdit version.
For more details about package relationships (and the official definitions of Breaks and Conflicts) refer to Debian Policy Manual - Chapter 7.


text:
Q: Dimensional regularization: order of integration This is a two-loop calculation in dim reg where I seem to be getting different results by integrating it in different orders. I am expanding it about $D=1$. What rule am I breaking?
$$\int \frac{d^{D} p}{(2\pi)^D}\frac{d^{D}q}{(2\pi)^D}\frac{p^2+4m^2}{(q^2+m^2)((q-p)^2+m^2)}=?$$

If we integrate $q$ first, the inner integral converges in $D=1$
$$\int \frac{d^{D}q}{(2\pi)^D}\frac{1}{(q^2+m^2)((q-p)^2+m^2)}=\frac{1}{m}\frac{1}{p^2+4m^2}$$
then integrating over $p$, by the rules of dimensional regularization we have
$$\int \frac{d^{D} p}{(2\pi)^D}\frac{1}{m}\frac{p^2+4m^2}{p^2+4m^2}=0.$$

If we integrate $p$ first we have
$$\int \frac{d^{D} p}{(2\pi)^D}\frac{p^2+4m^2}{(q-p)^2+m^2}=\int \frac{d^{D} u}{(2\pi)^D}\frac{u^2+2u\cdot q +q^2+4m^2}{u^2+m^2}=\frac{q^2+4m^2}{2m}+\int \frac{d^{D} u}{(2\pi)^D}\frac{u^2}{u^2+m^2}$$
where in the last equality we threw away the $u\cdot q$ term by symmetric integration, and split off the terms in the numerator that converge in $D=1$. The remaining term is a common integral in dim reg (though perhaps the limit $D=1$ is not)
$$\int \frac{d^{D} u}{(2\pi)^D}\frac{u^2}{u^2+m^2}=\frac{1}{(4\pi)^{D/2}}\frac{D}{2}\Gamma(-D/2)(m^2)^{D/2}= -\frac{m^2}{2m}$$
where we used $\Gamma(-1/2)=-2\sqrt{\pi}$.
Now integrating the outer integral over $q$ using the same rules discussed above,
$$\int \frac{d^{D} q}{(2\pi)^D}\frac{1}{2m}\frac{q^2+3m^2}{q^2+m^2}=\frac{1}{2}\neq 0$$
What part is invalid?

A: I'd say, when you set
$$
\int \frac{d^{D}q}{(2\pi)^D}\frac{1}{(q^2+m^2)((q-p)^2+m^2)}=\frac{1}{m}\frac{1}{p^2+4m^2}
$$
the correct answer actually has a $+\mathcal O(d-1)$ piece. The $p$ integral has $1/(d-1)$ divergences which, when multiplied by the missing subleading piece, leaves a finite contribution.
We can do the integrals exactly in $d$. For the $q$ integral we combine denominators à la Feynman, and do the linear shift $q\to q+(1-x)p$. We get
$$
\frac{2 \pi ^{d/2}}{(2 \pi )^d \Gamma \left(\frac{d}{2}\right)}\int_0^\infty\frac{q^{d-1}}{\left(m^2-p^2 (x-1) x+q^2\right)^2}\,\mathrm dq=\frac{2^{-d-1} (2-d) \pi ^{1-\frac{d}{2}} \csc \left(\frac{\pi  d}{2}\right) }{\Gamma \left(\frac{d}{2}\right)}\left(\frac{1}{m^2-p^2 (x-1) x}\right)^{2-\frac{d}{2}}
$$
Next we evaluate the $p$ integral:
\begin{align}
-\frac{2^{-d-1} (d-2) \pi ^{1-\frac{d}{2}} \left(2 \pi ^{d/2} \csc \left(\frac{\pi  d}{2}\right)\right)}{(2 \pi )^d \Gamma \left(\frac{d}{2}\right)^2}\int_0^\infty p^{d-1} \left(4 m^2+p^2\right) \left(\frac{1}{m^2-p^2 (x-1) x}\right)^{2-\frac{d}{2}}\,\mathrm dp=\\
=-2^{-2 d-1} d \pi ^{-d} m^{2 d-2} (-((x-1) x))^{-\frac{d}{2}-1} (8 d (x-1) x+d-8 (x-1) x) \Gamma (-d)
\end{align}
Finally, we perform the $x$ integral:
\begin{align}
\frac{2^{-2 d-1} (d-2) \pi ^{1-d} m^{2 d-2} \left(\csc \left(\frac{\pi  d}{2}\right) \Gamma \left(\frac{d}{2}+1\right) \Gamma (-d)\right)}{\Gamma \left(2-\frac{d}{2}\right) \Gamma \left(\frac{d}{2}\right)^2}\int_0^1((1-x) x)^{-\frac{d}{2}-1} (-8 d (1-x) x+d+8 (1-x) x)\,\mathrm dx=\\
\color{red}{\frac{2^{1-2 d} \pi ^{2-d} m^{2 d-2} \csc ^2\left(\frac{\pi  d}{2}\right)}{\Gamma \left(\frac{d}{2}\right)^2}}
\end{align}
For $d\to 1$ you can expand this as
$$
=\frac12+\big(\log\frac{m}{\pi}+\frac12\gamma\big)(d-1)+O(d-1)^2
$$
where I haven't bothered to include the standard $\mu^\epsilon$ scale to get a dimensionally consistent series.
We correctly reproduce the leading $1/2$ result.


text:
Q: Open an image in Paint, saving the image and closing Paint using C# As stated in the title of the question I have a doubt regarding Paint.
In C# I would like to:
1- Open an existent .jpg image in Paint
2- Save the image in the same format using Paint
3- Leave Paint open for 1 second
4- Close Paint
So far I only know how to do the first step and I have no idea about how to do the rest.
You help is greatly appreciated!
        string path = "C:/blah blah";
        String image = "imageInput.jpg";
        ProcessStartInfo startInfo = new ProcessStartInfo(image);
        startInfo.Verb = "edit";
        Process.Start(startInfo);

A: You should really look and see what Paint is doing differently than the normal C# routines.  I am guessing it is adding/changing some meta data.  If this is true you could just change the metadata with a program instead of opening this in paint.  I don't believe Paint has the auto-save that you are looking for.


text:
Q: Slick Slider setPosition for navigation I am using Slick Slider within Magnific Popup.
The slider can contain a couple of items, and has it's own thumbnail nav.
Because the popup sets the slider to display:none I've use:
$('.slider-products').slick('setPosition');

within a callback function when the popup opens and changes.
I've created a pen.
You'll see a couple of issues, firstly the thumbnail navigation doesn't load in correctly due to the setPosition not being set, but I've been unable to get this to work. If you resize the window you'll see it.
Secondly on the second (purple) and third (green) items do not start on their first items. Each slider gets it's own unique class, so they shouldn't be interfering with each other.


text:
Q: Position frequency matrix for Pandas column with strings I have a pandas Dataframe with a column of peptide sequences and I want to know how many times each each amino acid appears at each position. I have written the following code to create the position frequency matrix:
import pandas as pd
from itertools import chain

def frequency_matrix(df):
    # Empty position frequency matrix
    freq_matrix_df = pd.DataFrame(
        columns =  sorted(set(chain.from_iterable(df.peptide_alpha))),
        index=range(df.peptide_len.max()),
    ).fillna(0)

    for _, row in df.iterrows():
      for idx, aa in enumerate(row["peptide_alpha"]):
        freq_matrix_df.loc[idx, aa] += 1

    return freq_matrix_df

which for the following sample DataFrame:
mini_df = pd.DataFrame(["YTEGDALDALGLKRY",
                        "LTEIYGERLYETSY",
                        "PVEEFNELLSKY",
                        "TVDIQNPDITSSRY",
                        "ASDKETYELRY"],
                       columns=["peptide_alpha"])
mini_df["peptide_len"] = mini_df["peptide_alpha"].str.len()

peptide_alpha
peptide_len

0
YTEGDALDALGLKRY
15

1
LTEIYGERLYETSY
14

2
PVEEFNELLSKY
12

3
TVDIQNPDITSSRY
14

4
ASDKETYELRY
11

gives the following output:

A
D
E
F
G
I
K
L
N
P
Q
R
S
T
V
Y

0
1
0
0
0
0
0
0
1
0
1
0
0
0
1
0
1

1
0
0
0
0
0
0
0
0
0
0
0
0
1
2
2
0

2
0
2
3
0
0
0
0
0
0
0
0
0
0
0
0
0

3
0
0
1
0
1
2
1
0
0
0
0
0
0
0
0
0

4
0
1
1
1
0
0
0
0
0
0
1
0
0
0
0
1

5
1
0
0
0
1
0
0
0
2
0
0
0
0
1
0
0

6
0
0
2
0
0
0
0
1
0
1
0
0
0
0
0
1

7
0
2
1
0
0
0
0
1
0
0
0
1
0
0
0
0

8
1
0
0
0
0
1
0
3
0
0
0
0
0
0
0
0

9
0
0
0
0
0
0
0
1
0
0
0
1
1
1
0
1

10
0
0
1
0
1
0
1
0
0
0
0
0
1
0
0
1

11
0
0
0
0
0
0
0
1
0
0
0
0
1
1
0
1

12
0
0
0
0
0
0
1
0
0
0
0
1
1
0
0
0

13
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
2

14
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1

This works for small DataFrames but because of the for loop becomes too slow for bigger datasets. Is there a way to rewrite this in a faster/vectorized way?

A: Solution
mini_df['peptide_len'] = mini_df.peptide_len.map(lambda x: range(x))
mini_df['peptide_alpha'] = mini_df.peptide_alpha.map(list)
mini_df = mini_df.explode(["peptide_alpha", "peptide_len"])

pd.crosstab(mini_df.peptide_len, mini_df.peptide_alpha)

Performance
With the dataframe
mini_df = pd.concat([mini_df] * 10000)

On my machine, my solution solves the problem within 0.5s, whereas the solution of the OP takes 1m8.6s. Consequently, I believe that my solution can be useful for him.
Output
peptide_alpha  A  D  E  F  G  I  K  L  N  P  Q  R  S  T  V  Y
peptide_len
0              1  0  0  0  0  0  0  1  0  1  0  0  0  1  0  1
1              0  0  0  0  0  0  0  0  0  0  0  0  1  2  2  0
2              0  2  3  0  0  0  0  0  0  0  0  0  0  0  0  0
3              0  0  1  0  1  2  1  0  0  0  0  0  0  0  0  0
4              0  1  1  1  0  0  0  0  0  0  1  0  0  0  0  1
5              1  0  0  0  1  0  0  0  2  0  0  0  0  1  0  0
6              0  0  2  0  0  0  0  1  0  1  0  0  0  0  0  1
7              0  2  1  0  0  0  0  1  0  0  0  1  0  0  0  0
8              1  0  0  0  0  1  0  3  0  0  0  0  0  0  0  0
9              0  0  0  0  0  0  0  1  0  0  0  1  1  1  0  1
10             0  0  1  0  1  0  1  0  0  0  0  0  1  0  0  1
11             0  0  0  0  0  0  0  1  0  0  0  0  1  1  0  1
12             0  0  0  0  0  0  1  0  0  0  0  1  1  0  0  0
13             0  0  0  0  0  0  0  0  0  0  0  1  0  0  0  2
14             0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  1


text:
Q: Perimeter of intersecting and growing circles I'm trying to generate a script/file in MS Excel where I can calculate the perimeter variation of growing intersecting circles. In my example there is three circles placed in a random pattern.
They start at 1 mm radius and is then growing.
I have managed to calculate the perimeter at initial conditions and when only "one-to-one" interaction occurs, see fig 1 and fig 2.
But my problem is when the circles are overlapping, and "taking away" the same perimeter, as my calculations are now, this is not accounted for and the perimeter is underestimated.
In short:
I'm looking for a way to calculate the perimeter at any given time for these growing circles: (perimeter represented by solid line)

Is there a way to mathematically determine the perimeter of three "merged" circles?
Or is there any other nice software that would do such a thing?
Hope I have managed to describe my problem.


text:
Q: unused import statement for used ones in IntelliJ IDEA I am new in IntelliJ IDEA and I have the warning "unused import statement" for an statements that I use. I tried mvn clean from the terminal but it didn't helps

It seems that some libraries hav a broken path, but I don't know how to solve it

A: I will assume that you want to use those imports in your code.
The warnings, in gray, are suggesting you to remove imports of libraries that you are then NOT using in your code (in order to save resources and gain other advantages).
The errors, in red, are related to the lack of availability of the specified library in your local environment (in other words Lombok dependency is not properly installed).
The command "mvn clean" will remove local dependencies installed using Maven.
This could indeed be the cause of the error itself, you removed Lombok jar file from your local install using "mvn clean".
To know more about this topic and be sure to fix the related error I'd need to see your POM.xml file.
Nonetheless I would like to try to provide help right away.
Assuming that your POM.xml looks good in order to successfully import the missing libraries you'd need to run:
mvn clean install -U
And then run a rebuild (from IntelliJ Rebuild menu), this should take care of the red import errors.
Then, to remove the warnings, you should just use the imported libraries in your code.
Here's an example that would remove the warning related to Date, just as an example:
String pattern = "yyyy-MM-dd";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);

String date = simpleDateFormat.format(new Date());
System.out.println(date);

IntelliJ will scan your code, see that "Date" import is used and stop generating the related warning.
If, on the other hand, you are not using those import statements I would just suggest to simply remove the unused import lines from the class.
The end result will be the same, you will no longer get errors and/or warnings.
A very neat way to obtain this result in IntelliJ is the Optimize Imports function.
Here its current shortcut:
Ctrl+Alt+O
This will take care not only of removing the unused imports but also to optimize them in order to minimize resource usage and attack surface.
Please write a comment if you need more clarity or other explanations, I'd be glad to help.

A: It seems like you didn't add your library to the project.
Go to File -> Project settings -> Library (or something similar) and add it.
But if you don't need any of the imports just remove them.

A: Optimize imports in the current file

1.On the main menu, choose Code | Optimize Imports.
2.Press Ctrl+Alt+O.
3.Place the caret at the import statements, click icons actions , and choose Remove unused import.
4.Open the Reformat File Dialog (Ctrl+Shift+Alt+L) and select the Optimize imports checkbox.

A: you can change your intelliJ preferences.
Preferences->Editor->Auto Import->Optimize Imports on the Fly will automatically remove unused imports

A: Try to delete all import statements, then go to usages of imports and try to alt-enter. This way IDE imports them by itself, and would give an error in case you added libraries in a wrong way. Perhaps build project and clean project inbetween steps just to be sure

A: try the Invalidate Cache and Restart option if nothing else works


text:
Q: Uninstalling python3 from Ubuntu stops the user interface from working so, I had an error while booting Ubuntu and loading the user interface which resulted in the boot process stopping after checking file system integrity.
My error was just the same as in: https://askubuntu.com/questions/882385/dev-sda1-clean-this-message-appears-after-i-startup-my-laptop-then-it-w
So basically a message
dev/sda1: clean, 552599/6111232 files, 7119295/24414464 blocks

was the last thing to appear on the screen while booting.
This happened right after I uninstalled python3 from my system in order to re-install it, which I thought could help me solve a non-related bug involving a module that could not be imported.

A: When python3 was purged, some dependencies of atp package nvidia-driver-430, which depend on python to run, stopped working. This stopped my GUI from being loaded after booting.
In the link for another question I shared above, the problem is solved purging nvidia's drivers and re-installing them. I've tried this for the python-related error and would like to add: that solution doesn't work if your problem was caused by a misuse of python3, like mine. The exact solution for that case would be:

*

*Ctrl+Alt+FX, X=1, 2, 3... in order to access the terminal after booting;

*Purging nvidia's drivers, sudo apt-get purge nvidia*;

*Removing nvidia's python related dependencies, with sudo apt autoremove;

*Rebooting;

*Re-installing drivers: sudo apt-get install nvidia-driver-XXX;

*Solving other problems related with losing those drivers temporarily, after starting the GUI, such as not having GNOME installed (I think its purged somewhere in the process along with the drivers's dependencies) and having your dock mispositioned.


text:
Q: Formatting a single row as CSV I'm creating a script to convert a whole lot of data into CSV format. It runs on Google AppEngine using the mapreduce API, which is only relevant in that it means each row of data is formatted and output separately, in a callback function.
I want to take advantage of the logic that already exists in the csv module to convert my data into the correct format, but because the CSV writer expects a file-like object, I'm having to instantiate a StringIO for each row, write the row to the object, then return the content of the object, each time.
This seems silly, and I'm wondering if there is any way to access the internal CSV formatting logic of the csv module without the writing part.

A: The csv module wraps the _csv module, which is written in C.  You could grab the source for it and modify it to not require the file-like object, but poking around in the module, I don't see any clear way to do it without recompiling.

A: One option could be having your own "file-like" object. Actually, cvs.writer requires for the object only to have a write method, so:
class PseudoFile(object):
    def write(self, string):
        # Do whatever with your string

csv.writer(PseudoFile()).writerow(row)

You're skipping a couple steps in there, but maybe it's just what you want.


text:
Q: How do I implement textInput binding with OJET input text v5.2.0? Knockout's textInput binding used to work with Oracle JET v3.2.0 ojInputText tag.
<input id="text-input"
     type="text"
     data-bind="ojComponent: {component: 'ojInputText',
                              textInput: value}"/>

But now that every single component of Oracle JET v5.2.0 is a custom HTML component, textInput doesn't work anymore. I've tried these methods:
<oj-input-text id="text-input" textInput="{{value}}"></oj-input-text>
<oj-input-text id="text-input" data-bind="textInput: value"></oj-input-text>

Is there a way to make textInput work with oj-input-text?
I've checked the documentation as well, but nothing is mentioned.

A: This isn't possible, and you can see why when you check the library.
In ojinputtext.js, the _onKeyUpHandler function specifically listens only for the Enter key and nothing else.
 _onKeyUpHandler : function (event)
    {
       if(event.keyCode === $.ui.keyCode.ENTER){
            this._SetValue(this._GetDisplayValue(), event);
       }
    }

It's also not possible to modify this function from your viewModel, since ojinputtext is registered as a Composite Component at the end into OJET, and only then do you get access to it.
  oj.CustomElementBridge.registerMetadata('oj-input-text', 'inputBase', ojInputTextMeta);
  oj.CustomElementBridge.register('oj-input-text',
                         {'metadata': oj.CustomElementBridge.getMetadata('oj-input-text')});

You could maybe do a workaround of wrapping a Jquery function around the input text that listens to every keystroke.

A: As confirmed by @Srishti, I can't use textInput with Oracle JET. So I created a Knockout Binding Handler to imitate the behaviour, which I believe others would find useful too:
<oj-input-text data-bind="textInputOJET: value"></oj-input-text>

JS:
ko.bindingHandlers.textInputOJET = {
    init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
        $(element).focus(function(){
            $($(this).find('input')[0]).keyup(function(event){
                valueAccessor()(event.currentTarget.value);
            });
        });
    },
    update: function(element, valueAccessor, allBindings, viewModel, bindingContext) {}
}

self.value = ko.observable();
self.value.subscribe(function(newValue){
    console.log(newValue);
});

A: I think the right OJET way of doing that without custom KO bindings is with rawValue instead of value attribute, as covered in the docs/playground:
https://www.oracle.com/webfolder/technetwork/jet-520/jsdocs/oj.ojInputText.html#rawValue
https://www.oracle.com/webfolder/technetwork/jet-520/jetCookbook.html?component=textInput&demo=rawValue


text:
Q: How to edit choice list in multiple SharePoint lists Is there a way of programmatically changing a choice list in multiple SharePoint lists?
We have about 50 special SharePoint lists that are created from the same template. Is there a way of changing the choise list items in all these SharePoint lists ?
Thanks,
Thomas

A: If you are looking for a c# answer, here is some sample code.  (It could be ported to PowerShell as well).  You could loop through any of your matching lists (based on name, template, or someone other method to retrieve the list of lists).  Then for each list, you could call a method like this:
private void updateChoiceFieldForOneList(SPList currentList, string fieldName, string[] arrayValues)
{
    SPFieldChoice choiceField = (SPFieldChoice) currentList.Fields[fieldName];
    choiceField.Choices.Clear();
    foreach (string oneValue in arrayValues)
    {
        choiceField.Choices.Add(oneValue);
    }
    choiceField.Update();
}

You would call this with something like this:
updateChoiceFieldForOneList(currentWeb.GetList("/Lists/TestList"), "MyChoiceField", new string[] { "1", "2", "3" });


text:
Q: How do I open an HTML file with CSS events enabled on iPhone? I am emailing users a report in html format.  The html file has CSS events (e.g. hover and active) to highlight or change visibility of some rows.  No javascript.
When I run this in a browser the CSS works fine, but when i open the html attachment in the iOS "Mail" app the CSS events do not work.
Is there any way to open an html file on iOS with CSS enabled?

A: Use Webkit in your styles like this
    transform: rotate(90deg) scale(1) skew(1deg) translate(10px);
-webkit-transform: rotate(90deg) scale(1) skew(1deg) translate(10px);
-moz-transform: rotate(90deg) scale(1) skew(1deg) translate(10px);
-o-transform: rotate(90deg) scale(1) skew(1deg) translate(10px);
-ms-transform: rotate(90deg) scale(1) skew(1deg) translate(10px);


text:
Q: Getting dates from week number of year in android I am trying to get the dates from a given weeknumber and the year. The below piece of code is always showing the currentDates even though I enter week and year.
Calendar c = new GregorianCalendar(Locale.getDefault());
    c.set(Calendar.WEEK_OF_YEAR, 15);
    c.set(Calendar.YEAR, 2015);

    String result = "";

    int firstDayOfWeek = c.getFirstDayOfWeek();
    for (int i = firstDayOfWeek; i < firstDayOfWeek + 7; i++) {
        c.set(Calendar.DAY_OF_WEEK, i);
        result += new SimpleDateFormat("yyyy.MM.dd").format(c.getTime()) + "\n";
    }

instead of getting dates of Week number 15. I am getting current dates values always. I am not what is wrong here?
How to solve this issue?
Thanks!

A: Try this
  Calendar now = Calendar.getInstance();
  now.set(Calendar.YEAR,2015);
  now.set(Calendar.WEEK_OF_YEAR,15);

  System.out.println(new SimpleDateFormat("yyyy.MM.dd").format(now.getTime()));

OUTPUT

A: please update the my code: it's works for me.
  Calendar now = Calendar.getInstance();
      now.set(Calendar.YEAR,2015);
      now.set(Calendar.WEEK_OF_YEAR,15);

      String result = "";

        int firstDayOfWeek = now.getFirstDayOfWeek();

        Log.e("day","day:"+firstDayOfWeek);
        for (int i = firstDayOfWeek; i < firstDayOfWeek + 7; i++) {
            now.set(Calendar.DAY_OF_WEEK, i);
            result += new SimpleDateFormat("yyyy.MM.dd").format(now.getTime()) + "\n";
        }

    Log.e("result","result:"+result);


text: Q: Space between side of tkinter text widget and the text inside it I want to create a space between the side of the tkinter text widget and the text inside it. That is, the text does not stick to the side of the widget. How can this be done?


text:
Q: Flutter Web View: error de autorizacion disallowed_useragent Estoy practicando una app con flutter, tengo una web view donde el usuario entra a determinado sitio web y puede realizar su registro a traves del boton de google.
Pero se me presenta este problema, como podria otorgar permisos para un correcto inicio de sesion o registro con google para dichas webs?

Este es el codigo donde abro esa pantalla webview:
 Container(
            alignment: Alignment.topCenter,
            padding: EdgeInsets.symmetric(horizontal: 5.0),
            child: ElevatedButton(
              style: ButtonStyle(
                shape: MaterialStateProperty.all<RoundedRectangleBorder>(
                  RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(18.0),
                    side: BorderSide(
                      color: Colors.blueAccent,
                      width: 2.0,
                    ),
                  ),
                ),
              ),
              child: Text(
                'Ir al curso',
                style: TextStyle(fontSize: 15, color: Colors.white),
              ),
              onPressed: () {
                Navigator.of(context).push(MaterialPageRoute(
                  builder: (context) => webview(
                  namePage: widget.td.title,
                  url: 'https://www.youtube.com/')));
              },
            ),
          ),

A: Este error se provoca cuando Google no reconoce el navegador, primeramente asegura tener instalado en tu dispositivo el navegador Chrome.
Si esto no resuelve el problema, te sugiero definir un User-Agent de esta forma:
 userAgent: "random"

Ejemplo:
body: const WebView(
        initialUrl: 'https://-----------------------------------',
        userAgent: "random",
      ),


text:
Q: Blank Data by Fetching data from DB using Laravel 9 and Vue.js 3 and Axios Hello i using Laravel 9 and Vue.js 3, with Axio  and i am trying to fecht some data from my data base, to appear inside a select list options, however i am not getting anything (neither any error, just blank data...)
I created my model  Produto
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Produto extends Model
{
    use HasFactory;
    protected $table = "produto";
    protected $guarded = [];
}

created the correct migration
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('produto', function (Blueprint $table) {
            $table->id();
            $table->string("nome");
            $table->double("preco");
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('produto');
    }
};

Created my controller ProdutoController
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Produto;

class ProdutoController extends Controller
{
   /**
     *Retorna os dados dos Produtos
     *
     * @return void
     */
    public function getProdutos()
    {
        $data = Produto::get();
        return response()->json($data);
    }
}

Defined my route
<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ProdutoController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

Route::get('get_produtos', [ProdutoController::class, 'getProdutos']);
//Route::post('produtos', [ProdutoController::class, 'setProdutos']);

For testing i tried localhost:8000/get_produtos and it appeared my data as expected, so i think this part is correct
[{"id":1,"nome":"Telemovel","preco":124.55,"created_at":null,"updated_at":null},{"id":2,"nome":"Tablet","preco":600.99,"created_at":null,"updated_at":null},{"id":3,"nome":"Portatil","preco":501,"created_at":null,"updated_at":null},{"id":4,"nome":"Caneta","preco":2.55,"created_at":null,"updated_at":null}]

In my template i used this Select
<div :id="selectProdutoID" class="row">
            <div :id="optionId" class="col-sm-6" >
                            <select  :id="selectId"  class=' form-select form-control-md' v-model='prod' @change="onchange($event)">
                                <option v-for='data in produto' :value='data.id'>{{ data.nome }} </option>
                            </select>
                        </div>

And finally here is my script
<script>

export default{
name:"app",
components: {

},

data() {
  return{
    blankID:"blank",
    tituloID:"titulo",
    ClienteID:"nomeCliente",
    selectId:"selectID",
    dropID:"drop",
    adicionarID:"adicionarId",
    selectProdutoID:"selectProduto",
    optionId:"optionId",
    qtdID:"qtdId",
    boxId:"boxId",
    produto: [],

    onchange(e){
        console.log(e.target.value);
    }
}
},

methods:{
            getProdutos: function(){
                axios.get('get_produtos')
                    .then(function (response) {
                        this.produtos = response.data;
                    }.bind(this));
            }
        },
        created: function(){
            this.getProdutos()
        }
    }

</script>

It doesn't even get me an error, just a select with empty content , and i tried to check other solutions i found here, but nothing worked for now.  I believe the error is happening somewhere in the the template/script part, but i´ve been trying everything i found and still with no luck
Thank you in advance
EDIT:
Found out this tutorial https://www.tutsmake.com/laravel-9-vue-js-axios-get-request-tutorial/
and then changed my script methods to
methods: {
            getProdutos(){
                axios.get('/get_produtos')
                     .then((response)=>{
                       this.produtos = response.data.produtos
                     })
            }
        },
        created() {
            this.getProdutos()
        }

However data continues to not appear on my select

A: Found a solution to my problem.  For some reason if i use «this» directly Axios doesn't work, so i had to create a variable, and it worked
methods: {
            getProdutos(){
                var vm = this
                axios.get('/get_produtos')
                     .then((response)=>{
                       vm.produtos = response.data
                     })
            }
        },
        created() {
            this.getProdutos()
        }


text:
Q: Unlock the reading pane in outlook 2016 How do you write a script to change a registry key? What I am trying to do is have a script I can run to unlock the reading pane in outlook 2016.
The path of the registry key is:

Computer\HKEY_CURRENT_USER\Software\Policies\Microsoft\office\16.0\outlook\options
  disablereadingpane REG_DWORD 0x00000001 (1)

And I need to change the 1 to a 0. In the 0x00000001
Any help getting started with this would be greatly appreciated.

A: My comment was faulty it's add not edit.
reg.exe is the command line registry manipulation tool. See reg.exe /?
You may first check if the key exists and what value / data it has.
Reg Query "HKCU\Software\Policies\Microsoft\office\16.0\outlook\options"

To adda key/value/data pair
Reg add "HKCU\Software\Policies\Microsoft\office\16.0\outlook\options" /v disablereadingpane /t REG_DWORD /d 0x0

optionally you may add a /f  force option to overwrte current content.

A: I think you're looking for something like this, if you're using powershell. It's pretty self explanatory
Set-ItemProperty -Path HKCU:\Software\Policies\Microsoft\office\16.0\outlook\options -Name disablereadingpane -Value 0


text:
Q: Why does the memory behave differently after applying strcpy() and initialising an array with a string literal? If I assign an array a string literal using strcpy, I can easily access those bytes which are beyond the array bounds:
char sequence[4];
strcpy(sequence, "String");
printf("&sequence == %p\n", &sequence);
printf("&sequence[3] == %p\n", &sequence[3]);
printf("The out-of-range values are '%c' and '%c'\n", *(char*)0x000000000022FE50, *(char*)0x000000000022FE51);

&sequence == 000000000022FE4C
&sequence[3] == 000000000022FE4F
The out-of-range values are 'n' and 'g'

But if I do the same thing merely initialising the array in place, these memory bytes are empty or have some unexpected values:
char sequence[4] = "String";
printf("&sequence == %p\n", &sequence);
printf("&sequence[3] == %p\n", &sequence[3]);
printf("The out-of-range values are '%c' and '%c'\n", *(char*)0x000000000022FE50, *(char*)0x000000000022FE51);

&sequence == 000000000022FE4C
&sequence[3] == 000000000022FE4F
The out-of-range values are ' ' and 'r'

Why is there such difference between strcpy and direct storing?
Disclaimer:
I know that this programme is incorrect.  I know what undefined behavior is, I know that it is bad and should not be considered as a solution ever. The question is only about mechanisms and only seeks educational purposes. I am never about to apply this to any practical task (if anyone worries that much).

A:
If I assign an array a string literal using strcpy, I can easily access those bytes which are beyond the array bounds:

No, you cannot. This is undefined behavior. It may work. It may not. Don't do that. Whenever you "can" access out of bounds elements, you're doing something wrong.
You could avoid this with strncpy(sequence, "String", sizeof(sequence))

Why is there such difference between strcpy and direct storing?

strcpy have no knowledge of the size of the array you're passing to it, but the compiler has that knowledge during compilation. An implementation of strcpy can look like this:
char * strcpy ( char * destination, const char * source ) {
    char *ret = destination;
    while(source) {
        *destination = *source;
        destination++;
        source++;
    }
    return ret;
}

If you initialize an array, this is what the C standard says:

An array of character type may be initialized by a character string literal or UTF-8 string literal, optionally enclosed in braces. Successive bytes of the string literal (including the terminating null character if there is room or if the array is of unknown size) initialize the elements of the array.

If the string literal is too long, the remaining characters will be ignored. Do note that this will most likely lead to a string without zero termination. So this is not a valid string and printing it will invoke Undefined behavior. However, this code is ok, even if it will issue a warning:
#include <stdio.h>
int main(void)
{
    char str[8]="Hi!\0This initializer is too long";
    printf("%s\n", str);
    for(int i=0; i<sizeof(str); i++)
        putchar(str[i]);
    putchar('\n');
}

It will print:
Hi!
Hi!This


text:
Q: How do I convert this javascript date picker date to milliseconds? I need to do a conditional where I test whether the date from a date picker has passed already. I need to compare it to todays date using Date.now(); which returns milliseconds.
when I my log date picker date from my object - listOfEventsObject[i].date - it prints in this form:
 **2017-08-15** .

while date.now() outputs this: **1503904013430**

how can I convert the date picker date in order to see if the time has passed?
UPDATE It does not work to use getTime();
when I use getTime(); it removes everything from the array. I only need passed dates left out of the array.
my code:
    function getPostsSuccess (listOfEventsObject){ /*callback which passes
                                                             array to loop*/

        for (var i in listOfEventsObject) {

                if(listOfEventsObject[i].date.getTime() < Date.now()){

                       this.listOfEvents.push(listOfEventsObject[i]);

}//close if

                }//close loop

            }//close callback

A: You can use the .getTime() method of the date object to get milliseconds that can be compared to Date.now().

var before = new Date(2000, 1, 1, 0, 0, 0, 0);

var now = Date.now();

var after = new Date(2100, 1, 1, 0, 0, 0, 0);

console.log("before is before now: %s", before.getTime() < now);

console.log("after is after now: %s", after.getTime() > now);


text:
Q: Cannot disable cipher suite "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384" in IIS / Windows Server 2022 I am using this command in Windows Server 2022, latest updates:
Disable-TlsCipherSuite -Name "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384"
It completes without error.  I then tried restarting IIS (and also the server).
But this cipher suite still shows up in SSL Labs.  Is this suite part of the suite named "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384"?  Is that why it can't be turned off?
Any guidance would be greatly appreciated.


text:
Q: Printing issue using java's printf method I am trying to print a percentage sign using printf.
When I use the following:
System.out.printf("%-3d%%\n",10);
System.out.printf("%-3d%%\n",100);
System.out.printf("%-3d%%\n",0);

I end up with:
10 %
100%
0  %

How can I achieve the following
10%   - 1 space after % sign
100%  - no space
0%    - 2 spaces after % sign

Any ideas?

A: try
    System.out.printf("%-4.4s\n",10 + "%");
    System.out.printf("%-4.4s\n",100+ "%");
    System.out.printf("%-4.4s\n",0+ "%");

this can be verified with
    System.out.printf("%-4.4s|\n",10 + "%");
    System.out.printf("%-4.4s|\n",100 + "%");
    System.out.printf("%-4.4s|\n",0+ "%");

which produces
10% |
100%|
0%  |

A: try with DecimalFormat..
    DecimalFormat df=new  DecimalFormat("###'%'");
    System.out.printf("%s\n",df.format(10));
    System.out.printf("%s\n",df.format(1));
    System.out.printf("%s\n",df.format(100));


text:
Q: aspx Login page takes long time due to loading config values in session. How can I make it faster I have a configuration table in the database which is loaded into the session on the login page. The login is taking long time. This is a aspx page and makes a call to a stored procedure which has a simple select query. How can I make the login load faster?

A: *

*Test your SP how long its take.

*Test your web page without the SP, maybe there is another problem that cause it.

*Change your code. try to write different access to your SP


text:
Q: Error connecting http through URL in vagrant I am not being able to get an answer to my http request through the url that I placed in the windows HOST file. However, if you order through the IP of the machine works perfectly.
The content of my HOST file:
172.0.0.10 sogets.dev

The content of my VagrantFile
Vagrant.configure("2") do |config|
  config.vm.box = "ubuntu/trusty64"
  config.vm.network "private_network", ip: "172.0.0.10"
  config.vm.synced_folder "yii2.dev", "/var/www/yii2.dev"
end

The response to an http request via "sogest.dev" is "Connection Refused"

A: There are couple of issues:

*

*The allocated IP

172.0.0.10 is not within IP range for Private Network, see https://en.wikipedia.org/wiki/Private_network
Please make sure to set an IP within the allowed range for Private Network, otherwise your request is going to the real server and not against your VM.

*the Host file

When you allocated a private IP to your VM, then you must use this IP in your host file.
Lets say you have following in your Vagrantfile
config.vm.network "private_network", ip: "192.168.34.10"

Then you'll write in your host file
192.168.34.10 sogets.dev

A: "It appears that Google wants to use .dev only for internal puposes. Under that assumption it seems to be safe to host a "fake" dev zone on your internal DNS server"
Solution


text:
Q: How to model in UML this specific scenario I have to model some specs, and I can't understand what kind of uml diagram I should be using.
This is the scenario: There are 3 nested categories called area, grouping and topic. Under the topic, there are possible "activation codes" which will define a serie of document. Let me clarify with an example:
Area A1, Grouping G1, Topic T1.

*

*If there is activation code "X1" then documents Y1 and Y2 are present.

*If there is "X5" in conjunction of "X1" then documents Y3 and Y4 are also present.

*If there is "X2" then Y5 is present

*If there is "X5" in conjunction of "X2" then Y3 and Y4 are also present.

etc.
How these activation codes are "activated" is outside the scope of this diagram. This diagram must only represent what documents will be present in various scenarios of activation codes.
Any kind of help is appreciated. Thanks.

A: I would say that this behavior is too fine-grained to be in an UML spec. Do a basic class diagram with Topic "has many" Documents, then write the rules as plain English in an accompanying notice.
My answer might not be what you expect as I know some people like to specify the smallest details of their apps in complex UML diagrams. From my experience, it rarely makes the specs any better...

A: Solendil makes a good point.
However this could be a number of different UML diagrams. On a sequence diagram, with each activation code offering an alternative path with guard conditions as you see fit.
It could alternatively and I think probably more sensibly be a state diagram. With the state inputs becoming your activation codes and the 'states' are the documents to output. This might be better displayed in a truth table rather than a diagram though. Or used in conjunction. I like to have a few different representations for this kind of strict behavior. One so it's easy to map in my own head, but also different people find it easier to read information in different ways. Or whichever works best for whoever you are trying to communicate the info to!


text:
Q: Reveal Modal - Show only once per day I am using reveal modal to load a popup when my website loads. However the popup loads everytime the page loads. Since a visitor can visit multiple pages or on multiple instances, this limitation is turning out to be bad for our visitors experience.
The following is the js I am using to load the reveal modal once a page is loaded.
jQuery(document).ready(function($) {
/* Pop-up
================================================= */

$(function() {
    function showpanel() {
    $('.reveal-modal').reveal({
        animation: 'fade',
        animationspeed: 800
    });
    }
    setTimeout(showpanel, 4000)
   });
});

What can I add to ensure that the the reveal modal loads only once in a particular day no matter how many different pages a visitor accesses?
Would appreciate any assistance.
Thanks

A: The easiest way to achieve this is with a cookie which only lasts 24 hours.
What you'd do is check if there was a cookie and show the dialog if there isn't
if($.cookie('MyCookie') != 'DialogShown'){
  showpanel();
  setCookie();
}

Here's the code to set it
function setCookie(){
    $.cookie('MyCookie', 'DialogShown',
      {
         expires: date.getTime() + (24 * 60 * 60 * 1000) // now add 24 hours
      });
}

However be aware the user may have configured their browser to reject cookies and in the UK (and probably other countries there are regulations about websites using cookies).

A: You'll need persistent storage, as in cookies, localStorage or serverside storage.
$(function() {
    if ( localStorage.getItem('seen') != (new Date()).getDate()) {
        setTimeout(showpanel, 4000);
    }
});

function showpanel() {
    $('.reveal-modal').reveal({
        animation: 'fade',
        animationspeed: 800
    });

    localStorage.setItem('seen', (new Date()).getDate());
}

There's a polyfill for older browsers at MDN

A: For Client side solution you may use cookie to set in user's browser and set it's expiry for 1 day.
$.cookie('the_cookie', 'the_value', { expires: 1 });

For more details see:
https://github.com/carhartl/jquery-cookie
EDIT:
Include Jquery-cookie Plugin in your html page and then add following piece of code
$(function() {
    if($.cookie('alreadyShow') === null) {
        $.cookie('alreadyShow', true, {expires: 1});

        $('.reveal-modal').reveal({
           animation: 'fade',
           animationspeed: 800
       });
    }
});


text:
Q: C++ Stack implementation unexpected output #include <iostream>

using namespace std;
/*Stack
last in first out algorithm
pop, push, print*/
class Node{
private:
    int a;
public:
    Node *next;
    Node(){
        next = NULL;
    };
    Node(int b){
        int a = b;
        next = NULL;
    }
    int getValue();
};

int Node::getValue(){
    return a;
}

class Stack{
    Node *top;
public:
    Node* pop();
    void push(int);
    Stack(){
        top=NULL;
    }
    void printStack();
}aStack;

//pushing onto the stack
void Stack::push(int z){
    //if top is not null create a temp link it to top then set point top to temp
    if (top != NULL){
        Node*temp = new Node(z);
        temp->next = top;
        top = temp;
    }
    else
        //else just set the new node as top;
        top = new Node(z);
        top->next = NULL;
}

Node* Stack::pop(){
    if (top == NULL){
        cout << "Stack is empty" << endl;
    }
    else
        //top = top->next;
        return top;
        //top = top->next;
}
//prints the stack
void Stack::printStack(){
    int count = 0;
    while(top!=NULL){
        count++;
        cout << count << ": " << (*top).getValue() << endl;
        top = top->next;
    }
}

int main(){
    aStack.push(5);
    aStack.printStack();
    //cout << aStack.pop()->getValue()<< endl;
    cin.get();
}

Hey guys, I am reviewing my data structures. I am not able to figure out why i am getting output 0 after pushing the number 5 on the empty stack and printing it out. Please give me a HINT on what i am doing wrong, thanks.

A: In Node::Node you are shadowing the member variable a,
int a = b;

replace it by
a = b;

or better, use a constructor initializer list
Node(int b): a(b), next(NULL){}

A: One problem I find in your code is thay you are declaring another a variable in the class of node
Node(int b){
    //int a = b; when you define a new `a` variable, old one is ignored
    a=b;
    next = NULL;
}

All private members are defined inside the class, so all the class can see the variable a. but when you declare a new variable in a sub-scope, the a variable in the general scope is ignored inside this sub-scope


text:
Q: avoid space before \textsuperscript in linebreak I have a lot of
Ca\textsuperscript{2+}

in my text. In my editor I use automatic linebreaking to keep the text readable. Now it sometimes happens that lhe line breaks like this:
Ca
\textsuperscript{2+}

which produces a space between Ca and 2+.
Is there a way to write this code that it would ignore the linebreak or do I have to find a way to change the behaviour of my editor?

A: How about using semantic markup. I.e. you write what you mean and use macros to format it. That way if you change how you want the text formatted later you don't need to fix it all over the place.
\newcommand{Ion}[2]{#1\textsuperscript{#2}}

Now you can write
Blah blah \Ion{Ca}{2+} blah blah.

Hopefully your text editor wont break that anywhere bad.
And if you decide you later want all your ions formatted in bold you can just change the macro
\newcommand{Ion}[2]{\textbf{#1\textsuperscript{#2}}}

A: While using semantic markup seems preferable, adding a % (comment sign) after "CA" will conceal the line break and hereby get rid of the space.
\documentclass{article}

\begin{document}

\Huge

Ca
\textsuperscript{2+}

Ca%
\textsuperscript{2+}

\end{document}


text:
Q: Is the categorical variable relevant if one of the dummy variable has a t score of 0.95? If a variable has more than 0.05 t score, it is deemed not relevant and should be excluded from the model. However, what if the categorical variable has 4 dummy variable and only one of them exceeds 0.05? Do i exclude the entire categorical variable?
                            OLS Regression Results
==============================================================================
Dep. Variable:              SalePrice   R-squared:                       0.803
Model:                            OLS   Adj. R-squared:                  0.801
Method:                 Least Squares   F-statistic:                     368.4
Date:                Mon, 15 Jul 2019   Prob (F-statistic):               0.00
Time:                        12:00:26   Log-Likelihood:                -17357.
No. Observations:                1460   AIC:                         3.475e+04
Df Residuals:                    1443   BIC:                         3.484e+04
Df Model:                          16
Covariance Type:            nonrobust
============================================================================================
                               coef    std err          t      P>|t|      [0.025      0.975]
--------------------------------------------------------------------------------------------
const                    -1.366e+05   9432.229    -14.482      0.000   -1.55e+05   -1.18e+05
OverallQual               1.327e+04   1249.192     10.622      0.000    1.08e+04    1.57e+04
ExterQual                 1.168e+04   2763.188      4.228      0.000    6262.969    1.71e+04
TotalBsmtSF                 13.7198      5.182      2.648      0.008       3.554      23.885
GrLivArea                   45.4098      2.521     18.012      0.000      40.465      50.355
1stFlrSF                     9.4573      5.543      1.706      0.088      -1.416      20.330
GarageArea                  22.4791      9.748      2.306      0.021       3.358      41.600
KitchenQual               1.309e+04   2142.662      6.111      0.000    8891.243    1.73e+04
GarageCars                8875.8202   2961.291      2.997      0.003    3066.923    1.47e+04
BsmtQual                  1.097e+04   2094.395      5.235      0.000    6856.671    1.51e+04
GarageFinish_No           2689.1356   5847.186      0.460      0.646   -8780.759    1.42e+04
GarageFinish_RFn         -8223.4503   2639.360     -3.116      0.002   -1.34e+04   -3046.057
GarageFinish_Unf         -8416.9443   2928.002     -2.875      0.004   -1.42e+04   -2673.349
BsmtExposure_Gd           2.298e+04   3970.691      5.788      0.000    1.52e+04    3.08e+04
BsmtExposure_Mn           -262.8498   4160.294     -0.063      0.950   -8423.721    7898.021
BsmtExposure_No          -7690.0994   2800.731     -2.746      0.006   -1.32e+04   -2196.159
BsmtExposure_No Basement  2.598e+04   9879.662      2.630      0.009    6598.642    4.54e+04
==============================================================================
Omnibus:                      614.604   Durbin-Watson:                   1.972
Prob(Omnibus):                  0.000   Jarque-Bera (JB):            76480.899
Skew:                          -0.928   Prob(JB):                         0.00
Kurtosis:                      38.409   Cond. No.                     2.85e+04
==============================================================================

A: when you say "0.05 t score" I assume you mean "0.05 p value".  the t-value is just coef / stderr, which goes into the p-value calculation (abs(t_value) > 2 is approximately p-value < 0.05)
when you say "categorical variable has 4 dummy variable", I presume you mean it has 4 "levels" / distinct values and you're referring to BsmtExposure_Mn.  I'd leave that in as the other categories/levels are helping the model.  if you had several categories that were less predictive you could think about combining them into one "other" category
as a general point, you shouldn't just automatically exclude variables because their p-value is > 0.05 (or whatever your cutoff/"alpha value" is).  they can be useful for understanding what's going on within the model, and explaining results to other people


text:
Q: Netlify CMS image path I'm having an issue with file paths on the Netlify CMS on the live site, everything worked fine whilst on localhost.
U have the following in my config.yml:
backend:
  name: git-gateway
  branch: main
  repo: [my-repo]
media_folder: "src/img"
public_folder: "/img"
collections:
  - name: "guides"
    label: "Guides"
    folder: "/src/guides"
    create: true
    delete: true
    fields:
    // Some fields removed for brevity
      - { label: "Body", name: "body", widget: "markdown" }

I can create a new post (guide) absolutely fine, I have several other collections which all also work fine, the issue is with the images. I can upload images and they're added to my img folder, but the path is incorrect, as an example, if I choose an image from the media library and then toggle the markdown editor view, I get:
![Alt test](/src/img/logo--dark.png)

which then throws a deploy error, with the issue:
ENOENT: no such file or directory, stat '/src/img/logo--dark.png' (via Error)

Which is easy enough to understand, as the correct path should be:
![Alt test](./src/img/logo--dark.png)

My site structure is straightforward (Eleventy is doing the magic in the background):
public
-img
...
-guides
-- guide-1.html
...
src
- img
...
- guides
-- guide-1.md

I'm missing the period before the filepath in the markdown editor and changing the media-folder filepath isn't solving the issue. So the question is, when a user uploads an image in the CMS how do I get the editor to create the correct filepath?


text:
Q: View All Rows of Print out in Ipython Notebook I have searched StackOverflow and Google but can't find a satisfactory explanation.
I'm hoping someone can help me display all rows of a printout in an IPython notebook.
I have the following code:
g = df.columns.to_series().groupby(df.dtypes).groups
feature_name_dict = {k.name: v for k, v in g.items()}
print(feature_name_dict)

I've also tried:
g = df.columns.to_series().groupby(df.dtypes).groups
feature_name_dict = {k.name: v for k, v in g.items()}
with pd.option_context('display.max_rows', None, 'display.max_columns', None):
    print(feature_name_dict)

The results I get are:
{'int32': Index(['1_m_v1', '2_m_v1', '3_m_v1', '4_m_v1', '5_m_v1', '6_m_v1', '7_m_v1',
       '8_m_v1', '9_m_v1', '10_m_v1',
       ...
       '1994_y_v2', 'F_v3', 'M_v3', 'F_v4', 'M_v4', 'H_v5', 'W_v5', 'X_v5',
       'C_v9', 'X_v9'],
      dtype='object', length=159), 'int64': Index(['dev'], dtype='object'), 'float64': Index(['v6', 'v7', 'v8', 'v12', 'v13'], dtype='object')}

How can I get a full printout?
EDIT:
If moderator actually looked at question s/he would see that my code attempts what is addressed in the referenced question for "possible duplicate" and it doesn't work

A: in place of print(feature_name_dict) use     print(str(feature_name_dict)). That should work.


text: Q: Sencha touch packaging for windows phone 8 I created a sencha touch app using sencha cmd and I was trying to test it on windows phone 8 emulator. I have read that we should integrate sencha touch with phonegap to build it to windows phone 8. So can anyone help me with the process of how to integrate those two or wrap the sencha code with phonegap ?? any help would be greatly appreciated. thanks.


text:
Q: Displaying and iterating a list within a string? So I'm writing a program which part of it involves sending out an email.
Within the email body (which is a string), I want to display a list. However, I want to know how/or what the best way to do this because right now, it only displays the first element of the list (naturally). As you can see, the list I'm trying to put in at the bottom is:
formatted_times

Here's the code below:
FROM = gmail_user
    TO = ['mcgoga12@wfu.edu']
    SUBJECT = "StudyBug - Study Rooms for %s" % newdate
    TEXT = """
This is an automated email from StudyBug.

We wanted to let you know that the following studyrooms were booked for %s:

%s

Thank You,

StudyBug

-----------------------------------------------------------------------------------------------

-----------------------------------------------------------------------------------------------

Check out the project page!: https://github.com/g12mcgov/StudyBug

""" % (newdate, formatted_times)

A: Just join the list on newlines (or commas, or whatever you like) as you format it:
"""…booked for %s:

%s

Thank You, …""" % (newdate, "\n".join(formatted_times))


text:
Q: WinForms DataGridView Checkbox I am trying to figure out how to set a cell in a dataGridView to ReadOnly.
The checkbox is being added by the boolean property. Therefore, I looking for tips how to accomplished the task of setting a cell to readonly based on the column with the boolean property.
Below is a snippet of my code.
[DisplayName("Lock")]
public bool RevenueLock { get; set; }

revenue = new DomesticCostRevenue()
{
RevenueLock = Convert.ToBoolean(values[10]),
Revenue = Convert.ToDouble(values[11])
};
domestic.Add(revenue);
}
CostRevenueGridView.DataSource = domestic;

This is what I've done but no success so far.
foreach (DataGridViewRow row in CostRevenueGridView.Rows)
{
if ((bool)row.Cells["RevenueLock"].Value == true)
{
row.Cells["Revenue"].ReadOnly = true;

//MessageBox.Show("Lock");
}
}

A: You can set the whole column or the whole row or a specific cell read only:

*

*Column: this.dataGridView1.Columns[1].ReadOnly = true;

*Row: this.dataGridView1.Rows[0].ReadOnly = true;

*Cell: this.dataGridView1.Rows[0].Cells[1].ReadOnly = true;
Test
Put the below code in a button click or somewhere else to show a form to you. In first row, the second cell will be read only, because the first cell value is true:
var f = new Form();
f.Controls.Add(new DataGridView
{
    Name = "g",
    Dock = DockStyle.Fill
});
f.Load += (se, ev) =>
{
    var g = ((Form)se).Controls["g"] as DataGridView;
    g.AutoGenerateColumns = true;
    g.AllowUserToAddRows = false;
    g.DataSource = new List<C1>
    {
        new C1{P1=true, P2="x"},
        new C1{P1=false, P2="y"},
    };
    foreach (DataGridViewRow row in g.Rows)
    {
        if ((bool)row.Cells["P1"].Value == true)
            row.Cells["P2"].ReadOnly = true;
    }
};
f.ShowDialog();

And here is the code for class C1:
public class C1
{
    public bool P1 { get; set; }
    public string P2 { get; set; }
}

Also the problem doesn't exist with DataTable:
f.Load += (se, ev) =>
{
    var g = ((Form)se).Controls["g"] as DataGridView;
    g.AutoGenerateColumns = true;
    g.AllowUserToAddRows = false;
    var dt = new DataTable();
    dt.Columns.Add("P1", typeof(bool));
    dt.Columns.Add("P2", typeof(string));
    dt.Rows.Add(true, "x");
    dt.Rows.Add(false, "y");
    g.DataSource = dt;
    foreach (DataGridViewRow row in g.Rows)
    {
        if ((bool)row.Cells["P1"].Value == true)
            row.Cells["P2"].ReadOnly = true;
    }
};

A: I recreated your issue by creating a DataTable, populating with two columns matching yours, and then using the foreach loop you posted. My results were the same as yours. The individual cells that were ReadOnly were still editable.
I'm not sure why this is, but since Reza got it to work with a List<T>, I assume it has something to do with a DataTable.
Try subscribing to the RowsAdded event, and moving your check into there. Column names may not work with this code... if not, use the column indexes instead.
private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
    for (int index = e.RowIndex; index <= e.RowIndex + e.RowCount - 1; index++)
    {
        var currentRow = dataGridView1.Rows[index];

        if (Convert.ToBoolean(currentRow.Cells[0].Value))
            currentRow.Cells[1].ReadOnly = true;
    }
}

A: Thank for the help.  I finally was able to solve my problem.  The below snippet is my solution.
    private void CostRevenueGridView_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
    {
        foreach (DataGridViewRow row in CostRevenueGridView.Rows)
        {
            foreach (DataGridViewCell cell in row.Cells)
            {
                if (cell.ColumnIndex == 12)
                {
                    if (Convert.ToBoolean(CostRevenueGridView.Rows[row.Index].Cells[cell.ColumnIndex].Value))
                    {
                        row.Cells[11].ReadOnly = true;
                    }
                }

            }
        }
    }


text:
Q: Rails Internationalization translate a word and append to a model field My translation works great, but when I try to append a field of my model I get and error:
This is the code:
<%=t :beneficios @offer.benefits %>

this is the error:
app/views/offers/show.html.erb:18: syntax error, unexpected tIVAR, expecting ')'
...er.append=(t :beneficios @offer.benefits );@output_buffer.sa...

The problem is when I try to append the model field. But I can't find a solution on google and I don't think this is an option:
<%=t :beneficios %><%= @offer.benefits %>

Thanks in advance for your help.

A: You forgot a coma after :beneficios :)
<%= t :beneficios, @offer.benefits %>


text:
Q: Setup an app to use single Universal Push Notification Client SSL Certificate for Development and Production Recently Apple introduced a new type of APNS certificates - Universal Push Notification Client SSL Certificate.
It seemed for me that it should allow to have one certificate to use on both Development and Production (Sandbox and Production). This was really wanted feature because my backend uses the Azure Notification Hub to send pushes and contains only one available space for a certificate (Sandbox or Production).
I tried to follow official docs provided by Apple  (Creating a Universal Push Notification Client SSL Certificate) but with no luck - the new certificate applies only for Distribution . And even on theirs screenshots I see that this certificate applies only for Distribution mode and not for the Development and this is what confuses me
- Creating a Universal Push Notification Client SSL Certificate
This is why I will appreciate any guidance or advice which will explain how it should work, and did I understand the purpose of those certificates properly?

A: That's how it should appear - "Configurable" for development and "Enabled" for distribution. But it'll work for development as well.

A: I had the same problem looking for how to "Generate a universal APNs client SSL certificate". After a while, I managed to make it work. In the Apple developer console:

*

*create a Key (not a certificate)

*write the name of your key a select "APNs" service.

*Download your .p8 key.

Then you have to use this .p8 file in your call.


text:
Q: Is the following limit true or not? (function convergence) Let $x\in(0,1)$, let $p>1.$ I was wondering if $\lim_{n\to\infty} n^{\frac{2}{p}}x^{\frac{n}{p}}=0$ is true or not? I plotted some values and it seems to be true but I am struggling to prove this. Intuitively, one thing I can think of is that $x^{\frac{n}{p}}$ decays much quicker than $n^{\frac{2}{p}}$.

A: Your intuition

that $x^{\frac{n}{p}}$ decays much quicker than $n^{\frac{2}{p}}$.

is basically correct. In general, exponential values of the form $y^z$ where $y \gt 1$, with $z \to \infty$, always eventually grow faster than any polynomials $p(z)$.
Since $x\in(0,1)$, then
$$y = \frac{1}{x} \gt 1 \tag{1}\label{eq1A}$$
As such, you can rewrite your limit as follows
$$\begin{equation}\begin{aligned}
\lim_{n\to\infty} n^{\frac{2}{p}}x^{\frac{n}{p}} & = \lim_{n\to\infty}\frac{n^{\frac{2}{p}}}{y^{\frac{n}{p}}} \\
& = \lim_{n\to\infty}\left(\frac{n^{2}}{y^{n}}\right)^{\frac{1}{p}} \\
& = \left(\lim_{n\to\infty}\frac{n^2}{y^{n}}\right)^{\frac{1}{p}}
\end{aligned}\end{equation}\tag{2}\label{eq2A}$$
Since you have the limits are $\infty$ in both the numerator & denominator, you can use L'Hôpital's rule. Using it twice gives
$$\lim_{n\to\infty}\frac{n^2}{y^{n}} = \lim_{n\to\infty}\frac{2}{(\ln(y))^2 y^{n}} = 0 \tag{3}\label{eq3A}$$
This shows the limit in \eqref{eq2A} is also $0$.

A: \begin{align*}
\lim_{n \rightarrow \infty} n^{\frac{2}{p}}x^{\frac{n}{p}} &= \lim_{n \rightarrow \infty}  \mathrm{e}^{\frac{2}{p}\ln n}\mathrm{e}^{\frac{n}{p}\ln x}  \\
    &= \lim_{n \rightarrow \infty} \mathrm{e}^{\frac{2 \ln n + n \ln x}{p}}
\end{align*}
Since $0<x<1$, $\ln x < 0$, so $n \ln x$ is a function linear in $n$ with negative slope.  $2 \ln n$ is logarithmic in $n$.  As you observe, the linear function dominates, so
\begin{align*}
\lim_{n \rightarrow \infty} \mathrm{e}^{\frac{2 \ln n + n \ln x}{p}} &= \lim_{n \rightarrow \infty} \mathrm{e}^{\frac{n \ln x}{p}}  \\
    &= \lim_{n \rightarrow \infty} x^{\frac{n }{p}}  \\
    &= 0  \text{.}
\end{align*}


text:
Q: When to call Python's super().__init__()? (I am unable to find a reference anywhere on this matter after some Googling.)
The scenario can be clearly demonstrated with this short code sample:
class X:
    def __init__(self, stuff):
        self.__stuff = stuff

class Y(X):
    def __init__(self, stuff):
        # Is it safe to execute statements before calling super.__init__()?
        new_stuff = self.call_another_method(stuff)
        super(Y, self).__init__(new_stuff)

Using CPython 3.x, the above code sample works -- assuming call_another_method() exists.  It this coding style generally safe, but frowned upon or considered unPythonic?  I am unable to find advice on this matter.
Why do I care?
My background comes from more traditional object oriented programming languages such as C++, C#, and Java where "super" must be called strictly as the first statement in a subclass constructor -- ignoring the zero-argument, implicit case.
If it matters, I am a young Pythoneer: 3+, please.

A: Yes, it is perfectly safe to call other things before super(). Python doesn't set an order, and there are plenty of use-cases for this.
Note that super().__init__() call is just another expression in Python, it is not a syntax construct. You can use super() outside methods too, for example, provided you pass in the right arguments.
In your case, you can omit the type and instance arguments, Python 3 will retrieve these for you when super() is called without arguments, because you are using it in a function defined inside a class:
class Y(X):
    def __init__(self, stuff):
        new_stuff = self.call_another_method(stuff)
        # super(Y, self) is implicit here:
        super().__init__(new_stuff)


text:
Q: Unique ip connections in a syslog file I am analyzing a syslog files that have been created as a result of a DDOS attack and would like to a create a list of unique ip connections.Any assistance is greatly appreciated.

A: Assuming that the IP/Hostname is in field 4:
cat /var/log/messages | cut -d\  -f 4 -|sort|uniq

Example log message:
May 29 18:27:30 10.101.11.31 Myprog[5291]: 20856: Mar 31 06:14:38 EDT: %LINEPROTO-5-UPDOWN: Line protocol on Interface FastEthernet1/0/29, changed state to up

You may also want to try a tool like LogZilla which will make this much easier for analyzing these things.


text:
Q: php excel to mysql problem i am trying to build a csv to mysql and i did everything right,
butthe first row of the titles keep entering too, i want it to start from the second row in the csv file,
can you please help me:
    $row = 1;
if (($handle = fopen($file, "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);

    $userid = mysql_real_escape_string($Sid);
    $amount = mysql_real_escape_string($data[0]);
    $cardHolderName = mysql_real_escape_string($data[1]);
    $cardHolderAddress = mysql_real_escape_string($data[2]);
    $cardHolderZipcode = mysql_real_escape_string($data[3]);
    $cardHolderCity = mysql_real_escape_string($data[4]);
    $cardHolderState = mysql_real_escape_string($data[5]);
    $cardHolderCountryCode = mysql_real_escape_string($data[6]);
    $cardHolderPhone = mysql_real_escape_string($data[7]);
    $cardHolderEmail = mysql_real_escape_string($data[8]);
    $cardNumber = mysql_real_escape_string($data[9]);
    $cardSecurityCode = mysql_real_escape_string($data[10]);
    $cardExpireMonth = mysql_real_escape_string($data[11]);
    $cardExpireYear = mysql_real_escape_string($data[12]);

    $PurchaseDate = mysql_real_escape_string($data[13]);
    $StoreId = mysql_real_escape_string($data[14]);

    $ItemCode = mysql_real_escape_string($data[15]);
    $ItemName = mysql_real_escape_string($data[16]);
    $ItemQuantity = mysql_real_escape_string($data[17]);
    $itemShippingType = mysql_real_escape_string($data[18]);

A: You need to get the first row of data (title row) and "throw it away". Your code example is starting processing without skipping the first row.
if (($handle = fopen($file, "r")) !== FALSE) {
    $data = fgetcsv($handle, 1000, ",");
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    ...

A: I'm not sure what you're doing with your $row variable, but you could do something like this:
$row = 1;
if (($handle = fopen($file, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    if($row == 1)
    {
       $row++;
       continue;
    }
 ...


text:
Q: Pandas pd.to_datetime() removing duplicate values I've been trying to sort a date column, but I needed to convert the string date to date value format. However I'm losing duplicate dates, but I need the duplicates.
Here's my code:
import pandas as pd

df_in = pd.read_csv(input.csv)
df_in['date'] = pd.to_datetime(df_in['date'],format='%Y%m%d').dt.date
df_in.to_excel("output.xlsx")

Am I missing something in my method call?
below is a comparison of the input (left side) and output (right side) files:


text:
Q: can I sell a software that uses a GPL library and another BSD licensed library? This is the first time I have dealt with licensing issues so I am sorry if I am making any stupid assumptions. My issue is that I have written a program in Python that uses PyQT for the GUI and also uses another library licensed under BSD.
PyQT comes with GPL v2 and GPL v3 as well as a commercial license. From what I have read until now (including the GPL license), I understand that you can sell a software that is licensed under GPL. However, there is an issue if you're not the original author and you are reusing source code that is licensed under GPL. So here are my questions:

*

*In my case since I am using PyQT I believe that I should license my program under GPL as well? Also if this is the case I can sell my software provided that I release the source code as well right?

*If PyQT is released under GPL which as far as I understand gives you freedom to sell your software if you use the library why do they also provide a commercial license? Is it only for the case where you do not want to release the source code?

*Since I am also using a library that is licensed under BSD it is OK to license my software only under GPL and mention that my program uses this library in the License.txt and the About section of my program?

A: To answer the third question first, the fact that your program uses a library licensed with license X does not necessarily mean that your program must also use license X.
For permissive licenses, like BSD, you are completely free to choose a different license for your own code.
When the library uses a strong copyleft license, like GPL, then you can avoid a lot of legal questions and uncertainty by using the same license for your code.
The reason for this is because copyleft licenses require you to distribute the entire product that makes use of the copyleft licensed source under the copyleft license conditions. So, when you distribute your program, the GPL conditions of having to provide source code apply to both your code, the PyQT library and the additional BSD-licensed library that you use.

Neither the BSD nor the GPL license prevent you from asking money for your program, but they also don't forbid anyone to buy the program from you and redistribute it further without asking money for it.
The reason that PyQT is available both with the GPL and a commercial license is to make it possible to write commercial applications based on PyQT without having to release your source code.

A: *

*GPL nor BSD prevents you from selling your product

*GPL requires you to release everything under GPL, and make all source code available

*You can't change the license of the BSD licensed library to GPL

Conclusion: you can't release it as is.

As Bart hinted, you can get a commercial license for pyQT which would allow you to release it without putting everything under GPL. I'm not sure if that would clash with the BSD license but I doubt it.


text:
Q: Understanding React refs - why is my reference null here? I have a use-case where a React ref makes sense.
I've tried a few different ways of implementing them, and in this case integrating them with hammerjs.
I'm mostly going off of this question:
adding hammerjs to a react js component properly
My return method in my render is as such:
  return (
    <div className={"App card-row card-color " + this.props.className} ref={
      (el) => this._slider = el
  }>
          {this.state.bubblemsg ? (
    <NotifBubble message={this.state.bubblemsg} merchant={this.props.merchant.merchant}/>
  ) : (
   null
  )}
      <ScrollMenu
        data={this.state.list}
        inertiaScrolling={true}
        transition={.1}
        inertiaScrollingSlowdown={.000001}
      />
    </div>
  );

Which I would think would attach my div element as a reference.
In my componentDidMount() method, I am then attaching it to hammer:
componentDidMount() {
  this.hammer = Hammer(this._slider)
  this.hammer.on('swipeleft', console.log("swipe left"));
  this.hammer.on('swiperight', console.log("swipe right"));
}

However, I am getting the error:
TypeError: Cannot read property 'addEventListener' of undefined

And this is directly related to Hammer, and thus the reference I assume.
So what am I doing wrong with my references? I don't totally understand how they're supposed to work and the React tutorial explanation wasn't super clear, so a thorough explanation would be useful.

A: I think the problem is that in the listening of the hammer you have to pass a function to be called, try inserting an arrow function to log
componentDidMount() {
  this.hammer = Hammer(this._slider)
  this.hammer.on('swipeleft', () => console.log("swipe left"));
  this.hammer.on('swiperight', () => console.log("swipe right"));
}


text:
Q: Read will loop end of file I'm writing a C code that will read content of file and output it on the terminal.
This is my code so far:
rdfd = open(address, O_RDONLY);
read(rdfd, reader, 1);
while(rdfd != 0){ //will end if EOF is reached
    for(x=0; x<1; x++) printf("%c", reader[x]); //for printing at the terminal
    read(rdfd,reader,1);
}

Now, for an example, I have an index.html file with the ff content:

HELLO WORLD

The program will print something like this:

HELLO WORLD

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> (...)

The > will just go on infinitely. I don't know why. Was there something wrong with the while condition?

A: rdfd is the File Descriptor of the file you are reading from. Testing it for zero (while(rdfd != 0) actually doesn't do anything useful. If you want to test whether the file was opened correctly (you should) test if for < 0.
If you want to know when the end of the file is reached, check the return value from the read call, i.e:
int bytesRead = read(rdfd, reader, 1);

while (bytesRead > 0)
{ ...
  bytesRead = read(rdfd,reader,1);
}


text:
Q: How can I specific the operating system tag in my setup.py I want to distribute my python package, so I use setup.py and bdist_wheel. I am able to specific package name and version, but the filename generated is like package_name-0.0.2-py3-none-any.whl. I haven't figured out how to specify the none and any in the file_name with setpy.py. I need this to distribute different package versions for diffferent operating systems and CUDA versions.
My code did work in this way:
    setuptools.setup(
    '''
        platforms=['linux_x86_64'],
    '''
    )

which argument should I specify to replace the none and any?


text:
Q: Component Symbol identification; Rectangle with large T-shape I've been searching for days and still have not come up with an answer.
What is this symbol?:

The component in question was found on this mosfet amplifier schematic from the 1980s.

A: This looks like preset potentiometer wired as rheostat.
Here you can find the following definitions:

A: Long story short:
It's a variable resistor. Mainly used as a preset resistor (e.g. to equalize an DC offset)
See Rapidtables as an example and search for "Trimmer Resistor" after maybe 1/3 of the page.


text:
Q: How to use SendKeys(webdriver) command in Rich Text editor that is located in iframe I'm facing the following problem.I can not type text in iframe in which there is a text editor:Here is the html:

<!DOCTYPE html>

Here is what I have done so far,but the test passed successfully and no text is writen in the text editor.May be the solution is with Javascript executor but I'm not familiar with it.
WaitTool.waitForElementPresent(Browser.instance, By.tagName("iframe"), 10);
WebElement iframe = Browser.instance.findElement(By.tagName("iframe"));
Browser.instance.switchTo().frame(iframe);
WebElement description=Browser.instance.findElement(By.xpath("//body[@class='cke_editable cke_editable_themed cke_contents_ltr']"));
description.click();
description.sendKeys("someText");
Browser.instance.switchTo().defaultContent();

Thanks in Advance!

A: There are multiple ways of doing it. Here's an article you might want to have a look.
Test WYSIWYG editors using Selenium WebDriver

*

*Send keys directly

This approach is the one you have tried and didn't work. Please try make sure your locators to  and  are correct. Otherwise I'd suggest using JavaScriptExecutor for more stable solutions.

*

*Set innerHTML

WaitTool.waitForElementPresent(Browser.instance, By.className("cke_wysiwyg_frame"), 10);
WebElement iframe = Browser.instance.findElement(By.className("cke_wysiwyg_frame"));
Browser.instance.switchTo().frame(iframe);

WebElement description = Browser.instance.findElement(By.cssSelector("body"));
(JavascriptExecutor)Browser.instance.executeScript("arguments[0].innerHTML = '
Set text using innerHTML
'", description);

*

*Use CKEditor's native API

// no need to switch iframe
(JavascriptExecutor)Browser.instance.executeScript("CKEDITOR.instances.ckeditor.setData('
Native API text
 Editor')");


text:
Q: How can I hide the entire repeater when its empty from html tag How can I hide the entire Repeater when the repeater is empty (have no data)
without using code behind?

A: you can add to the repeater's attributes this code, keep in mind you have to change 'RepeaterName'to the current repeater:
Visible='<%# RepeaterName.Items.Count != 0 %>

Example of how the start tag of a repeater will be:
<asp:Repeater ID="RepeaterName" runat="server" Visible='<%# RepeaterName.Items.Count != 0 %>'>

** Sorry if this is a duplicate, I have been trying to find the best answer for a long time, and I just found it.


text:
Q: Validation in a getter method Normally when I use properties in my classes and have both getter and setter methods, I do all the validation checks inside the setter.
On the other hand, what do I do if I want to restrict the end user from changing the value of the property but still need to perform validations? I just put the checks into the getter although I'm not sure if it really belongs there.
class Foo:
    def __init__(self, value):
        self.__value = value

    @property
    def value(self):
        if not isinstance(value, int):
            raise ValueError(f'Expecting an integer, got {type(value)}.')
        else:
            return self.__value

This works fine, but the issue is the a) no validation is done until the property is accessed and b) validation is performed every time a property is accessed, which can get expensive.
So I made the below version instead. It solves the above issues but it looks and feels wrong. Is there a better way to do this:
class Foo:
    def __init__(self, val):
        self.__val = val

    @property
    def __val(self):
        return self.__tmp

    @__val.setter
    def __val(self, value):
        if not isinstance(value, int):
            raise ValueError()
        else:
            self.__tmp = value

    @property
    def value(self):
        return self.__val

I guess, I could do the validation in __init__ as well, but this is also ugly.
EDIT:
>>> a = Foo('bar')

Traceback (most recent call last):
  File "C:\python\block_model_variable_imputer\venv_fixed\lib\site-packages\IPython\core\interactiveshell.py", line 3437, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-8-637c10c15d73>", line 1, in <module>
    a = Foo('bar')
  File "<ipython-input-7-f7d16143eb85>", line 3, in __init__
    self.__val = val
  File "<ipython-input-7-f7d16143eb85>", line 12, in __val
    raise ValueError()
ValueError

A: Personally, I'd go for
class Foo:
    def __init__(self, value):
        if not isinstance(value, int):
            raise TypeError(f'Expecting an integer, got {type(value)}.')
        else:
            self.__value = value

    @property
    def value(self):
        return self.__value

Note that I used TypeError rather than ValueError, as that's the more appropriate exception type here ;)
This solves both of

a) no validation is done until the property is accessed and b) validation is performed every time a property is accessed, which can get expensive.

and also doesn't introduce an additional helper variable like in your second snippet. Having setters and getters (for __val) exclusively for internal usage seems bad practice to me …
If the goal of your second snippet is to move the checking logic out of __init__ for readability, you could do something like
class Foo:
    def __init__(self, value):
        self.__value = self._check_value_input(value)

    def _check_value_input(value):
        if not isinstance(value, int):
            raise TypeError(f'Expecting an integer, got {type(value)}.')
        else:
            return value

    @property
    def value(self):
        return self.__value

This also has the benefit that you can reuse _check_value_input if at some point you do need to check the input at some other pace, e.g. if you do decide to re-add the setter for value.


text:
Q: Is there any interactive tool on web to understand common code bases? I am modifying the code for glibc 2.5. Now since glibc is large and complex, I need to have a really good tool, to see interaction of different parts of the code. I am using Understand for this purpose, but Understood is only valid for 15 days. Afterwards you have to buy it.
So my question is, on web, are there sites where you can interactively understand common code bases such as glibc, gcc, linux kernel etc. I mean where you could search for some function, and then click on a function call to see its definition and such other useful features. I have used Koders.com, but it will only display the code, and is not interactive.

A: OpenGrok is good. You have to host it yourself though, it's not on the web.


text:
Q: Storing connection info while deploying geoprocessing tool on Server I have a geoprocessing tool written in python.
It will be deployed on ArcGIS for Server 10.1 as a Geoprocessing Service and it's processing workflow includes some manipulations with data in SDE geodatabase.
Right now I've decided to save .sde file of connection (with login and password saved in it) and deploy it together with my script to ArcGIS for Server.
Another similar option is to deploy a .lyr file. In any of these cases deployment on another server requires additionally editing these files in ArcGIS for Desktop.
Can you advice any other methods for sharing data access to SDE GDB without exposing sensitive information (password)?

A: All the password information is stored Server side, so its just a matter if people can get to your Server or not.
I'd say there are 3 ways you can connect/use SDE.
1) A GP Service which uses CreateArcSDEConnection tool. You can build up a connection to SDE at Service execution time. Somewhere inside the script you'll have in plain text the username/password. This way would be least secure. It would also be the worst in terms of performance.
2) A .sde connection file saved with your project. Your tool(s) use featureclasses from SDE via a path something like c:\myData\project1\connection to mySDE.sde\sde.features.points
The connection file saves the credentials using either DB or OS authentication. If DB, then a username/password are saved inside the .SDE file. If OS, then whatever account running AGS needs access to your database. I'd say this way is "more secure" than the previous example. You can decide what way is more secure in terms of authentication.
3) Using layers from the map as input to your GP Service. The credentials are saved as part of the layer. (layers are created and persist when you publish). There isn't an actual .SDE connection file in this example, so you could argue its even "more secure" than the previous. This is the "best" way for performance reasons.
Really your Server is only as secure as you make it. The only real way someone can get this sort of information is to actually get onto your server or pull the pieces back to their machine which make up the service (and the arcgisinput directories are not web exposed unless you've made them). Even if they can get onto your server, passwords that are saved inside the .SDE connection file are encrypted, so they cant "see" them (same with layers). My point is, unless you've written the SDE connection password somewhere in your script in plain text, I couldnt envision a way someone would ever be able to get it.