text:
Q: Compute multivariate complex Gaussian integral I don't know how to work out the homework of Leib&Loss P121, Ex4(b), in which we need to compute the following
$$
\int_{\mathbb{R}^n}\exp(-x^tAx)dx=\pi^{n/2}/\sqrt{\det A}
$$
where $A=A^t$ is a symmetric (thank Paul, see the comments) complex matrix with positive definite real part.
It hints to use something like continuous extension, but I don't know how to do this?

UPDATE
Since it is easy to show in case $A$ is real, I try to show that
$$
F(t)=\int_{\mathbb{R}^n}\exp(-x^t(A+tBi)x)dx-\pi^{n/2}/\sqrt{\det (A+tBi)}
,
$$
is independent to $t$, the DCT make us differentiate under the integral, but I can't show that $F'(t)=0$.

A: A corrected form of the question asks to show that $\int_{\mathbb R^n} e^{-x^tAx}\;dx\;=\; \pi^{n/2}/\sqrt{\det A}$ for symmetric $n$-by-$n$ $A$ with positive-definite real part. First, for $A$ real (positive-definite), there is a (unique) positive-definite square root $S$ of $A$, and the change of variables $x=S^{-1}y$ gives the result, as the questioner had noted.
The trick here, as in many similar situations asking for extension to complex parameters of a computation that succeeds simply by change of variables in the purely real case, is invocation of the Identity Principle from complex analysis. That is, if $f,g$ are holomorphic on a non-empty open $\Omega$ and $f(z)=g(z)$ for $z$ in some subset with an accumulation point, then $f=g$ throughout $\Omega$. This can be iterated to apply to several complex variables, in various manners. In the case at hand, this gives an extension from symmetric real matrices to symmetric complex matrices (with the constraint of positive-definiteness on the real part, for convergence of everything).
To be sure, the complex span (in the space of $n$-by-$n$ matrices) of real symmetric matrices is complex symmetric matrices, not $n$-by-$n$ complex matrices with arbitrary imaginary part.
EDIT: To discuss meromorphy in each of the entries, observe that if $A$ is symmetric with positive-definite real part, then so is $A+z\cdot (e_{ij}+e_{ji})$ for sufficiently small complex $z$, where $e_{ij}$ is the matrix with $ij$-th entry $1$ and otherwise $0$. Without attempting to describe the precise domain, this allows various proofs of holomorphy of both sides of the asserted equality. To prove connectedness of whatever that domain (for fixed $i>j$) is, it suffices to observe that it is convex: if $A$ and $B$ are symmetric complex with positive-definite real part, then the same is true of $tA+(1-t)B$ for real $t$ in the range $0\le t\le 1$.

A: Take
\begin{align}
A:=
\begin{pmatrix}
1 & -2i \\
i & 1
\end{pmatrix}
\end{align}
Then $\sqrt{\det(A)} = \pm i$, and your formula predicts that the value of the integral is $\pm i\pi$. However, $\mathbf{x}^{T}A\mathbf{x} = x^2 + y^2 - ixy$ and
\begin{align}
\int_{\mathbb{R}^2} \exp(-x^2 - y^2 + ixy) \, \mathrm{d}x \mathrm{d}y = \frac{2\pi}{\sqrt{5}}.
\end{align}

A: In the case that A is complex, $\sqrt{detA}$ has two values. The problem should involve which one to choose. There's ambiguity to say this $\int_{\mathbb{R}^2} e^{-x^{t}Ax}dx=\pi^{n/2}\sqrt{detA}$.
One way to consider this problem is to  diagonalize  $A$  (possible because A Hermitian) and change coordinate.
The integral is then $\int_{\mathbb{R}^2}e^{-(a_1+i b_1){x_1}^{2}-(a_2+ib_2){x_2}^{2}}dx_1dx_2$ with $a_1,a_2>0$.
So this problem is tranformed to a one dimension complex Gaussian. Then one can consider a complex contour which are two sectors closed by real axis and a complex ray in compex plane. We want the integral over the real axis and the integral over the complex ray to be the same. This requirement forces the angle between the complex ray and the real axis to be less or equal to $\frac{\pi}{4}$. This yields which value of $\sqrt{det A}$ one should choose.

A: The formula given is false if $\sqrt{\cdot}$ is interpreted as meaning the principal branch. There is the following counterexample: let $n \geq 5$ and let $A = e^{\frac{2\pi i}{n} } I_{n \times n}$ where $I_{n \times n}$ is the $n\times n $ identity matrix ($n \geq 5$ ensures the real part of $A$ is positive definite). Then the integral is equal to $- (2\pi )^\frac{n}{2}$ however the formula gives $(2\pi )^\frac{n}{2}$, an error by a sign.
On the other hand the formula is true if you say the left hand side is $\pm$ the right hand side. You can show this by squaring both sides and showing that both sides are holomorphic/analytic in $A$, agree for real pos. def. matrices, and the set of matrices which have positive definite real part is path connected (analytic continuation). The fact that the matrix is symmetric rather than Hermitian is important for analyticity (because a Hermitian matrix has a nonzero antiholomorphic derivative with respect to $\overline{A_{ij}}$).
The problem with making a similar argument without squaring is that for the right hand side to be analytic, you need to exclude matrices $A$ that have a negative determinant $\det{A} < 0$ (if the negative real line is your branch cut). However the set of matrices with positive definite real part and non-negative determinant is not a connected set, so you cannot analytically continue.
Admittedly I do find it strange that $\int_{\mathbb{R}^n} e^{-\frac{1}{2} x^{\mathrm{T}}A x } dx$ is holomorphic with  no branch cuts, yet on some open set it is equal to an analytic function with branch cuts.


text:
Q: Paypal SDK Integration Error I am trying to add the Paypal SDK to my app but I get 4 errors
Undefined symbols for architecture i386:
  "std::terminate()", referenced from:
  ___clang_call_terminate in libPayPalMobile.a(CardIOGPURenderer.o)
  "___cxa_begin_catch", referenced from:
  ___clang_call_terminate in libPayPalMobile.a(CardIOGPURenderer.o)
  "___gxx_personality_v0", referenced from:
  Dwarf Exception Unwind Info (__eh_frame) in libPayPalMobile.a(CardIOAnalytics.o)
  Dwarf Exception Unwind Info (__eh_frame) in libPayPalMobile.a(CardIOGPURenderer.o)
  Dwarf Exception Unwind Info (__eh_frame) in libPayPalMobile.a(CardIOAnalytics.o)
  Dwarf Exception Unwind Info (__eh_frame) in libPayPalMobile.a(CardIOGPURenderer.o)
ld: symbol(s) not found for architecture i386
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Can anyone help me solve this?

A: Try this :

*

*Go to Targets -> Build Settings -> Linking -> Other Linker Flags

*Add -lc++ & -ObjC to it

This worked for me solve errors same as above.
Hope this will help.

A: Go to:
Targets -> Build Settings -> Linking -> Other Linker Flags Add -ObjC -l"PayPalMobile" -l"Pods-PayPal-iOS-SDK" -l"c++" -framework "AVFoundation" -framework "AudioToolbox" -framework "CoreLocation" -framework "CoreMedia" -framework "MessageUI" -framework "MobileCoreServices" -framework "SystemConfiguration"

redpajama_set_name: RedPajamaStackExchange


text:
Q: Rate of Convergence for derivatives Let $\{f_n\}$ be a sequence of differntible functions $f_n:\mathbb{R} \to \mathbb{R}$.
And suppose that $\{f_n\}$ converges uniformly with rate $\varphi$ to a function $f$. That is:
$$\sup_x||f_n(x) - f(x)|| \leq \varphi(n), \lim\limits_{n\to \infty}\varphi(n) = 0.$$
Suppose further that $f_n'$ converges uniformly to $f'$. Is there anything which can be said about the rate of convergence for the derivatives?
Thanks.


text:
Q: Local python repository, but no server My question is very similar to this one:
python repo without hosting a server
but the accepted answer to that one is not the solution for me as it replaces the web server with a git server.
Reading this
https://packaging.python.org/guides/hosting-your-own-index/
I see that it is very easy to create a python repository
I just have to create a correct directory structure, and run a web server which makes that directory structure available.
I want to skip the server and have a completely local repository.
I don't want to get permission to run a server on the required computer  because I will not get it.
I don't want external service.
I just want the local repository be available without the server in between.
Is there a way to specify the repository url for pip as for example "file:///d:/example-repository" or something like this?
I know that it is possible to manually install with pip a selected package file, but this is not what I want.
I want a whole repository, but offline.
Why I would want to have a totally offline repository and how would the packages go into it is a completely different topic, independent of this question?
Edited to add: apparently, it's not entirely clear what I mean by this.
Consider the following situation:
I develop multiple python libraries to do some stuff commonly occuring in my projects.
For example controlling some of our custom made devices over usb.
I create python packages from these libraries.
I don't upload them anywhere. They are meant to be used locally and they are anyway useless without the equipment.
Later I want to create multiple independent projects using those libraries.
Each project gets its own virtual environment. And for each I install only the packages that it needs. Including my own libraries. Likely different projects will end up using different releases of my libraries. When I update a library I don't want to propagate it to all the projects using it already, because of the risk of breaking something there.
So how I handle this?
For public packages it's easy - just install by PIP.
I can automate this by specifying requirements of projects and make pip install what I need.
But then my private packages.
I can install them from PIP too, by manually pointing pip to the package files created by me when doing the release of library.
But this is manual work.
One solution is to create my own server which will serve my libraries, and add its url to pip.
This is actually a very reasonable thing to do.
But in my case, I would like to skip the server part.
After some reading I find out that to set up my server I just need a http(s) server and a correctly prepared filesystem substructure.
Which means that the http server is unaware that it is actually serving a python repository.
Pip is doing all the work of understanding the filesystem structure.
So I thought to skip the http server and make pip read the local filesystem directly without the interface of a http server.
(It is already doing most of the work anyway)
Similarly how for example the APT (package manager for some gnu/linux distributions) can be configured to install packages from a CD-ROM instead of an internet.
So that's why I'm posting this question to find out if there is a good way of achieving this.

A: You have a good list of "don't want" capabilities.  However, you're not clear on what you do want.  In common usage, "repository" is a data base -- of code, in your case -- that stores the data for a service -- in your case, the various actions of version control on the code.
If you want the capabilities of a service, especially if you're using a downloaded package to provide those capabilities, then you need to provide the configuration for that package.  For the two packages my devOps have discussed with me, the package is set up as a common service: one configured as a server.
As far as I know, you need to configure a local server -- that being the software abstraction that provides the service.


text:
Q: Как пофиксить ошибку activity_main.xml вот такая ошибка вылезает, что делать?
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.nikita.mozhaev.jm, PID: 22493
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.nikita.mozhaev.jm/com.nikita.mozhaev.jm.MainActivity}: android.view.InflateException: Binary XML file line #2 in com.nikita.mozhaev.jm:layout/activity_main: Binary XML file line #2 in com.nikita.mozhaev.jm:layout/activity_main: Error inflating class DrawerLayout
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3654)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3806)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2267)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:237)
        at android.app.ActivityThread.main(ActivityThread.java:8167)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:496)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1100)
     Caused by: android.view.InflateException: Binary XML file line #2 in com.nikita.mozhaev.jm:layout/activity_main: Binary XML file line #2 in com.nikita.mozhaev.jm:layout/activity_main: Error inflating class DrawerLayout
     Caused by: android.view.InflateException: Binary XML file line #2 in com.nikita.mozhaev.jm:layout/activity_main: Error inflating class DrawerLayout
     Caused by: java.lang.ClassNotFoundException: android.view.DrawerLayout
        at java.lang.Class.classForName(Native Method)
        at java.lang.Class.forName(Class.java:454)
        at android.view.LayoutInflater.createView(LayoutInflater.java:815)
        at android.view.LayoutInflater.createView(LayoutInflater.java:776)
        at android.view.LayoutInflater.onCreateView(LayoutInflater.java:913)
        at com.android.internal.policy.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:68)
        at android.view.LayoutInflater.onCreateView(LayoutInflater.java:930)
        at android.view.LayoutInflater.onCreateView(LayoutInflater.java:950)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:1004)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:961)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:659)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:534)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:481)
        at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:696)
        at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:170)
        at com.nikita.mozhaev.jm.MainActivity.onCreate(MainActivity.java:44)
        at android.app.Activity.performCreate(Activity.java:7963)
        at android.app.Activity.performCreate(Activity.java:7952)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1307)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3629)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3806)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2267)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:237)
        at android.app.ActivityThread.main(ActivityThread.java:8167)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:496)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1100)
    Caused by: java.lang.ClassNotFoundException: Didn't find class "android.view.DrawerLayout" on path: DexPathList[[zip file "/data/app/com.nikita.mozhaev.jm-sT9AsTEmPxXw5fPnbjy7hg==/base.apk"],nativeLibraryDirectories=[/data/app/com.nikita.mozhaev.jm-sT9AsTEmPxXw5fPnbjy7hg==/lib/arm64, /system/lib64, /product/lib64]]
        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:196)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
            ... 31 more

Вот мой код activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <include
        layout="@layout/app_bar_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_main"
        app:menu="@menu/activity_main_drawer" />

</DrawerLayout>


text:
Q: Is it good practice to keep Cursors in Try catch block? Most of the time when I write a cursor in SQL Server, I keep it in a try/catch block.  In the catch block I deallocate and close the activities of the cursor.
What is your opinion?  Is this a good practice?

A: Think it through and I think you will agree that try/catch for a cursor is bad practice.
If you encounter an error when declaring or opening a cursor then the CLOSE in the catch block won't work, it needs a successfully opened cursor. So you shouldn't include these parts in a using.
Move on a little to the loop and FETCH. I can't see an error happening in a simple loop statement, and if it happens with the FETCH then @@FETCH_STATUS gets set to -1 instead of an error being raised. So there is no point in including those parts.
Now we are onto the operation you are completing with the cursor. If an error happens here you either want to fix it and continue, log it and continue step on to the next row, or explicitly break the loop within the error handling of the operation. Your solution would jump you out of the operation where a catch block might have done some good.
After you finish the loop, either because of a break, a fetch error or the end of the records you can just close and deallocate without a catch block, there's no need to repeat yourself.
So you are writing useless code, moving away from the causes of an error and potential resolutions, and at worst replacing an otherwise reported error with one about CLOSE being called on an unopened cursor.


text:
Q: 16 bytes-long integer types I'm compiling a C++ program using GCC on 64bits - machine/OS/ (with -m64 option passed to g++). As expected, sizeof(long double) == 16 – I'm wondering whether there is 16 bytes-long standard type for integers?
P.S. __int128_t is an artificial extension that emulates standard type as I understood. Other than that I didn't find anything.

A: Nope, only guaranteed sizes are for char, unsigned char & signed char, and they are 1:
5.3.3 Sizeof [expr.sizeof]

1 The sizeof operator yields the number of bytes in the object
  representation of its operand. The operand is either an expression,
  which is not evaluated, or a parenthesized type-id. The sizeof
  operator shall not be applied to an expression that has function or
  incomplete type, or to an enumeration type before all its enumerators
  have been declared, or to the parenthesized name of such types, or to
  an lvalue that designates a bit-field. sizeof(char), sizeof(signed
  char) and sizeof(unsigned char) are 1. The result of sizeof applied to
  any other fundamental type (3.9.1) is implementation-defined. [ Note:
  in particular, sizeof(bool) and sizeof(wchar_t) are
  implementation-defined.74) —end note ] [ Note: See 1.7 for the
  definition of byte and 3.9 for the definition of object
  representation. —end note ]

(emphasis mine)

A: The c++ standard does not standardize the size of each type (accept char) but the difference in size in relation to each other.
A char has to be 1 byte.
A short has to be >= to a char.
An int has to be >= to a short.
A long has to be >= to an int.
and a long long has to be >= to a long.

same goes for float types.
I believe most compilers now support up to 8-byte integers
however I know for a fact some, if not most don't have 16-byte integers.
I also think that there are some object classes/structs that people have developed to emulate a 16-byte integer that would work on most compilers.


text:
Q: Virtual infiniband on kvm/qemu or another open source platform? Is there any way to set up a virtual infiniband network within kvm/qemu?  If not, is there a viable open source alternative which would allow virtual infiniband networking?
(Note that I'm not looking to give VMs access to a physical IB network, I'm looking to have an entirely virtual IB network with no IB hardware)

A: One of the following two drivers is probably what you are looking for: softRoCE (rdma_rxe) or softiWARP (http://www.gitorious.org/softiwarp). The softRoCE driver went upstream in Linux kernel version v4.8.

A: Currently, to the best of my knowledge, QEMU/KVM can only emulate the basic (but enought to run a VM) set of bios/video/usb/disk/net combo.
I know you said you don't want physical hardware, but your best chance at giving a VM some IB capabilities is using PCI passthrough.


text:
Q: My web fonts look pixelated, especially the vertical parts of 'l's 'i's and 't's
All WordPress sites render strangely and Google searches look weird as well.
For WordPress sites, it loads fine, but then looks like the picture moments later.
Additional information:

*

*Mozilla Firefox had the same issue on the same page.

*Enabling Microsoft TrueFont did nothing.

*Restarting chrome did nothing (except the last time).

*If you use an extension (font changer) to force all fonts into 'Times New Roman,' the problem vanishes.

*Chrome LCD Text Antialiasing does not fix the problem.

*Forcing other sites to use 'Noto Sans' (pre-relaunch) replicated the problem.

*Whatever font Google used was also messed up. After relaunching and installing 'Noto Sans,' google was fixed. Google's font does not appear to be 'Noto Sans,' however, which leads me to believe it fixed itself somehow.

*The problem appears in incognito mode.

*Clearing the cache does not fix the problem.

A: I installed the font in question, which I discovered to be 'Noto Sans,' to my computer. Following a relaunch of chrome, it seemed to fix itself.
EDIT: This did not fix the problem, I had to manually install an extension to replace the text on pages with a custom font before the problem vanished.


text:
Q: How to Drag UIBezierPath in UiView I successfully create the UIBezierPath now I want to drag that path in UIView on drag event(UIPanGestureRecognizer) and get the current location's  points contended by that path.
Is it possible that we can only drag UIBezierPath from one place to another? in UIView.

A: If you allow me to toot my own horn, I blogged about this topic a while ago in a post titled CGPath Hit Testing. The demo app that I talk about in the article has the capability you are looking for.


text:
Q: Creating submodule in gfortran This is code:
Program Submodules_0

Use Const_Var
Use Baz_Var

Implicit none

Call Pro_Baz

End Program Submodules_0

Module Const_Var

Implicit none

Integer::i
Integer,parameter::Br_NaNi=3
Real,parameter::S_baz=3.15E+06
Real,parameter,dimension(Br_NaNi)::V_baz=[110.0E+03,20.0E+03,0.40E+03]
Real,dimension(Br_NaNi)::I_baz,Z_baz,Y_baz

End module Const_Var

Module Baz_Var

Use Const_Var

Implicit none

Interface

Module subroutine Pro_Baz

End subroutine Pro_Baz

End interface

End module Baz_Var

Submodule(Baz_Var) Baz_Var_Main

Contains

Subroutine Pro_Baz

Implicit none

Do concurrent(i=1:Br_NaNi)

   I_baz(i)=(S_baz)/((sqrt(3.0))*V_baz(i))
   Z_baz(i)=(V_baz(i)**2)/(S_baz)
   Y_baz(i)=1/(Z_baz(i))

End Do

Return
End Subroutine Pro_Baz

End submodule Baz_Var_Main

I want to create submodules which contains subroutine Pro_Baz and when I start this program I got a this message:
Error: Unclassifiable statement
The message was on this line: Module subroutine Pro_Baz
What is wrong with this program?

A: Compiler support for submodules was introduced in gfortran in version 6.0.
Within an interface block, an interface body starting module subroutine ... is specific to the submodule facility.  A complaint about an unclassifiable statement for this interface body is, then, an indication of a lack of submodule understanding.  The compiler doesn't wait to complain on reaching a submodule statement.
The version of gcc/gfortran bundled with Code::Blocks 16.01 appears to be 4.9.2.
You will need to install, and configure the IDE to use, a more recent version of the compiler.  This is whether you are using the Windows version with a bundled default compiler, or a version on any OS with a separate compiler installation.


text:
Q: How can I extract a wrapped C++ type from a Python type using boost::python? I've wrapped a C++ class using Py++ and everything is working great in Python. I can instantiate the c++ class, call methods, etc.
I'm now trying to embed some Python into a C++ application. This is also working fine for the most-part. I can call functions on a Python module, get return values, etc.
The python code I'm calling returns one of the classes that I wrapped:
import _myextension as myext
def run_script(arg):
    my_cpp_class = myext.MyClass()
    return my_cpp_class

I'm calling this function from C++ like this:
// ... excluding error checking, ref counting, etc. for brevity ...
PyObject *pModule, *pFunc, *pArgs, *pReturnValue;

Py_Initialize();
pModule = PyImport_Import(PyString_FromString("cpp_interface"));
pFunc = PyObject_GetAttrString(pModule, "run_script");
pArgs = PyTuple_New(1); PyTuple_SetItem(pArgs, 0, PyString_FromString("an arg"));

pReturnValue = PyObject_CallObject(pFunc, pArgs);

bp::extract< MyClass& > extractor(pReturnValue); // PROBLEM IS HERE
if (extractor.check()) {                         // This check is always false
    MyClass& cls = extractor();
}

The problem is the extractor never actually extracts/converts the PyObject* to MyClass (i.e. extractor.check() is always false).
According to the docs this is the correct way to extract a wrapped C++ class.
I've tried returning basic data types (ints/floats/dicts) from the Python function and all of them are extracted properly.
Is there something I'm missing? Is there another way to get the data and cast to MyClass?

A: I found the error. I wasn't linking my bindings in my main executable because the bindings were compiled in a separate project that created the python extension only.
I assumed that by loading the extension using pModule = PyImport_Import(PyString_FromString("cpp_interface")); the bindings would be loaded as well, but this is not the case.
To fix the problem, I simply added the files that contain my boost::python bindings (for me, just wrapper.cpp) to my main project and re-built.


text:
Q: Need explicit formula for certain "$q$-numbers" involving gcd's The question is motivated by yet another possible approach to a combinatorial problem formulated previously in "Special" meanders. I'm not giving details of the connection as I believe the question is sufficiently motivated by itself.
I've got a vector space with basis $\left\{e_n\mid n\geqslant0\right\}$ and scalar product
$$
\left\langle e_m,e_n\right\rangle=q^{\gcd(m,n)}
$$
(with the convention $\gcd(0,n)=n$ for all $n\geqslant0$).
What I need is a maximally explicit expression for an orthogonal basis $\left\{o_n\mid n\geqslant0\right\}$ with respect to this scalar product. I do not mind if the $o_n$ are not of unit norm (and this is clearly a minor point anyway).
Here are the first few values (calculated with MAPLE). Up to arbitrary rescalings,
\begin{align*}
o_{{0}}&=e_{{0}}\\
o_{{1}}&=e_{{1}}-qe_{{0}}\\
o_{{2}}&=e_{{2}}- \left( q+1 \right) e_{{1}}+qe_{{0}}\\
o_{{3}}&=e_{{3}}-qe_{{2}}-e_{{1}}+qe_{{0}}\\
o_{{4}}&=\left( q+1 \right) e_{{4}}-{q}^{2}e_{{3}}- \left( {q}^{2}+q+1
 \right) e_{{2}}+{q}^{2}e_{{1}}+{q}^{2}e_{{0}}\\
o_{{5}}&=\left( {q}^{2}+q+1 \right) e_{{5}}- \left( {q}^{2}+1 \right)
qe_{{4}}- \left( {q}^{2}+1 \right) qe_{{3}}+ \left( {q}^{3}-{q}^{2}-1
 \right) e_{{1}}+ \left( {q}^{2}+1 \right) qe_{{0}}\\
o_{{6}}&=\left( {q}^{3}+{q}^{2}+2\,q+1 \right) e_{{6}}- \left( {q}^{3}
+q-1 \right) qe_{{5}}- \left( {q}^{3}+q-1 \right) qe_{{4}}\\&- \left( {q}
^{2}+1 \right)  \left( {q}^{2}+q+1 \right) e_{{3}}- \left( {q}^{3}+{q}
^{2}+2\,q+1 \right) e_{{2}}+ \left( 2\,{q}^{4}+{q}^{3}+3\,{q}^{2}+1
 \right) e_{{1}}+ \left( {q}^{3}+q-1 \right) qe_{{0}}\\
o_{{7}}&=\left( {q}^{2}+1 \right) e_{{7}}- \left( {q}^{2}-q+1 \right)
qe_{{6}}- \left( {q}^{2}-q+1 \right) qe_{{5}}- \left( {q}^{2}-q+1
 \right) qe_{{4}}\\&+ \left( {q}^{2}-q+1 \right) qe_{{2}}+ \left( {q}^{3}
-2\,{q}^{2}+q-1 \right) e_{{1}}+ \left( {q}^{2}-q+1 \right) qe_{{0}}
\end{align*}
The inverse transformation (again up to rescalings) does not look any more enlightening (except that everything is positive):
\begin{align*}
e_{{0}}&=o_{{0}}\\
e_{{1}}&=o_{{1}}+qo_{{0}}\\
e_{{2}}&=o_{{2}}+ \left( q+1 \right) o_{{1}}+{q}^{2}o_{{0}}\\
e_{{3}}&=o_{{3}}+qo_{{2}}+ \left( {q}^{2}+q+1 \right) o_{{1}}+{q}^{3}o_
{{0}}\\
e_{{4}}&=o_{{4}}+{\frac {{q}^{2}}{q+1}}o_{{3}}+ \left( {q}^{2}+1
 \right) o_{{2}}+ \left( q+1 \right)  \left( {q}^{2}+1 \right) o_{{1}}
+{q}^{4}o_{{0}}\\
e_{{5}}&=o_{{5}}+{\frac { \left( {q}^{2}+1 \right) q}{{q}^{2}+q+
1}}o_{{4}}+{\frac {q \left( {q}^{2}+1 \right)}{q+1}} o_{{3}}+q \left( {q}^{2}
+1 \right) o_{{2}}+ \left( {q}^{4}+{q}^{3}+{q}^{2}+q+1 \right) o_{{1}}
+{q}^{5}o_{{0}}\\
e_{{6}}&=o_{{6}}+{\frac { \left( {q}^{3}+q-1 \right) q}{{q}^{3}+
{q}^{2}+2\,q+1}}o_{{5}}+{\frac { \left( {q}^{3}+q-1 \right) q}{{q}^{2}
+q+1}}o_{{4}}+{\frac { \left( {q}^{2}+q+1 \right)  \left( {q}^{2}-q+1
 \right)}{q+1}} o_{{3}}\\
&+ \left( {q}^{2}+q+1 \right)  \left( {q}^{2}-q+
1 \right) o_{{2}}+ \left( q+1 \right)  \left( {q}^{2}+q+1 \right)
 \left( {q}^{2}-q+1 \right) o_{{1}}+{q}^{6}o_{{0}}\\
e_{{7}}&=o_{{7}}+{\frac { \left( {q}^{2}-q+1 \right) q}{{q}^{2}+
1}}o_{{6}}+{\frac { \left( {q}^{2}+q+1 \right)  \left( {q}^{2}-q+1 \right) q}{{q}^{3}+{q}^{2}+2\,q+1}}o_{{5}}+ \left( {q}^{2}-q+1 \right) qo_{{4}}\\
&+{\frac {q \left( {q}^{2}+q+1 \right)  \left( {q}^{2}-q+1 \right)}{q+1}}o_{{3}}
+q \left( {q}^{2}+q+1 \right)  \left( {q}^{2}-q+1 \right) o_{{2}}
+ \left( {q}^{6}+{q}^{5}+{q}^{4}+{q}^{3}+{q}^{2}+q+1 \right) o_{{1}}+{q}^{7}o_{{0}}\\
e_{{8}}&=o_{{8}}+{\frac { \left( {q}^{2}+1 \right) {q}^{4}}{
 \left( {q}^{2}+q+1 \right)  \left( {q}^{3}+q+1 \right) }}o_{{7}}+{\frac {{q}
^{4}}{{q}^{2}+q+1}}o_{{6}}+{\frac { \left( {q}^{2}+1 \right) {q}^{4}}{{q}^{3}+{q}^{2}+2\,q+1}}o_{{5}}\\
&+{\frac { {q}^{6}+{q}^{4}+{q}^{2}+q+1 }{{q}^{2}+q+1}}o_{{4}}
+{\frac {{q}^{2} \left( {q}^{2}+q+1 \right)  \left( {q}^{2}-q+1 \right)}{q+1}}o_{{3}}+ \left( {q}^{2}+1\right)  \left( {q}^{4}+1 \right) o_{{2}}+ \left( q+1 \right)
 \left( {q}^{2}+1 \right)  \left( {q}^{4}+1 \right) o_{{1}}+{q}^{8}o_{
{0}}
\end{align*}
There are some patterns, but I cannot even guess any statement that I could try to prove about these coefficients. Also the above was computed under the assumption that the transformation matrix is triangular, i. e. that $o_n$ only depends on $e_k$ with $k\leqslant n$. It is quite possible that there is a nicer basis which violates this assumption, but again I cannot think of any natural alternative form of the transformation matrix.
What I know is an explicit orthogonal basis for a similar scalar product "without $q$": if I would have just $\left\langle e_m,e_n\right\rangle=\gcd(m,n)$, then an orthogonal basis would be given by $e_n=\sum_{d|n}o_d$, so $o_n=\sum_{d|n}\mu\left(\frac nd\right)e_d$. Strangely enough, I obtain this from the above by substituting $q=0$, and again I have no idea why.
As @alpoge points out in a comment, if one removes $e_0$, then this actually works "with $q$" too.
PS As suggested by @Wolfgang in a comment, I've looked at polynomials resulting from the substitutions $q=\pm1$, $e_n=x^n$. Here:
$q=1$:
\begin{align*}
&1\\
&x-1\\
& \left( x-1 \right) ^{2}\\
& \left( x+1 \right)  \left( x-1 \right) ^{2}\\
& \left( x+1 \right)  \left( 2\,x+1 \right)  \left( x-1 \right) ^{2}\\
& \left( x+1 \right)  \left( 3\,{x}^{2}+x+2 \right)  \left( x-1 \right) ^{2}\\
& \left( x+1 \right)  \left( 5\,{x}^{3}+4\,{x}^{2}+8\,x+1 \right)
 \left( x-1 \right) ^{2}\\
& \left( x+1 \right)  \left( {x}^{2}+x+1 \right)  \left( 2\,{x}^{2}-x+1
 \right)  \left( x-1 \right) ^{2}\\
& \left( x+1 \right)  \left( 9\,{x}^{5}+7\,{x}^{4}+14\,{x}^{3}+10\,{x}^
{2}+6\,x+2 \right)  \left( x-1 \right) ^{2}\\
& \left( x+1 \right)  \left( 11\,{x}^{6}+8\,{x}^{5}+16\,{x}^{4}+10\,{x}
^{3}+15\,{x}^{2}+9\,x+3 \right)  \left( x-1 \right) ^{2}\\
& \left( x+1 \right)  \left( 7\,{x}^{5}+6\,{x}^{4}+5\,{x}^{3}+4\,{x}^{2
}+10\,x+1 \right)  \left( {x}^{2}+1 \right)  \left( x-1 \right) ^{2}\\
& \left( x+1 \right)  \left( 16\,{x}^{8}+11\,{x}^{7}+22\,{x}^{6}+12\,{x
}^{5}+18\,{x}^{4}+3\,{x}^{3}+9\,{x}^{2}-6\,x+5 \right)  \left( x-1 \right) ^{2}\\
& \left( x+1 \right)  \left( 21\,{x}^{9}+19\,{x}^{8}+38\,{x}^{7}+34\,{x
}^{6}+51\,{x}^{5}+45\,{x}^{4}+39\,{x}^{3}+33\,{x}^{2}+6\,x+2 \right)
 \left( x-1 \right) ^{2}
\end{align*}
$q=-1$:
\begin{align*}
0&:1\\
1&:1+x\\
2&:\left( x-1 \right)  \left( 1+x \right)\\
3&:\left( x-1 \right)  \left( 1+x \right) ^{2}\\
4&:- \left( x-1 \right)  \left( 1+x \right) ^{2}\\
5&:\left( x-1 \right)  \left( {x}^{2}+x+2 \right)  \left( 1+x\right) ^{2}\\
6&:-\left( x-1 \right)  \left( {x}^{3}+2\,{x}^{2}+2\,x+3 \right) \left( 1+x \right) ^{2}\\
7&:\left( x-1 \right)  \left( {x}^{2}+x+1 \right)  \left( 2\,{x}^{2}-
x+3 \right)  \left( 1+x \right) ^{2}\\
8&:-\left( x-1 \right)  \left( {x}^{4}+2\,{x}^{2}+2 \right)  \left( 1
+x \right) ^{3}\\
9&:\left( x-1 \right)  \left( {x}^{5}+{x}^{4}+{x}^{3}+3\,{x}^{2}+3
 \right)  \left( 1+x \right) ^{3}\\
10&:- \left( x-1 \right)  \left( {x}^{2}+1 \right)  \left( {x}^{5}+2\,
{x}^{4}+{x}^{3}+2\,{x}^{2}+2\,x+3 \right)  \left( 1+x \right) ^{2}\\
11&:\left( x-1 \right)  \left( 4\,{x}^{8}+{x}^{7}+8\,{x}^{6}+2\,{x}^{
5}+12\,{x}^{4}+3\,{x}^{3}+11\,{x}^{2}+4\,x+5 \right)  \left( 1+x
 \right) ^{2}
\end{align*}


text:
Q: False Positives in Google Analytics I run a very niche website.
There is absolutely no way it gets organic traffic; its url is not .com, it's also not easy to type or remember, it's more like sub.sub.domain.xyz/some/path/. domain.xyz shows a blank page.
The website contains data that I share with my colleagues and only 3 people know about it, all of them live in the US but do a lot of travel (of course, those 3 people may have shared it to others as well).
I track their behavior by a custom set of scripts that parse the raw HTTP server logs. I also make use of AWStats, which is essentially the same thing. And, finally, Google Analytics.
The typical activity on my site is something like 2-3 visits/week. Usually I can pinpoint which person is using it because I know where they live (they are from different cities among the world).
Recently, Google Analytics showed me a (relatively speaking) huge spike in traffic from the UK that lasted for two days. Funny thing is that, when looking at my HTTP log, I see no IP's that I could geolocate to the UK. Actually, the only two IPs I see logged around those days are one from a colleague in the US and my own one.
Does Google Analytics reports data that is not completely true? Particularly, false positives?
Or else, what could be happening here?

A: The spike might be the result of spam traffic. Make sure to filter your site for your hostname only.


text:
Q: Backing Gmail into Outlook 2007 I've always used gMail the usual way, through their web interface, and used Outlook for my other account. Lately I find myself often working offline (I moved, and haven't gotten my ADSL line yet, and it will be some time before it comes), so I'd like to have an offline copy of my gMail account. In Outlook.
I've looked, and for that there are two options, through POP and IMAP. If I figured correctly, I need to use IMAP settings in Outlook, along with SMTP, and it will download all my mail in Outlook, and later if I delete one in gMail, or one in Outlook it will reflect on the other. Am I right ?
What else do I need to be careful of, if I wish to have an offline copy in Outlook (same directories: Inbox, Send, Drafts, Archive ... and labels <-- can they also be transferred ?) so to have it syncronized between gMail and Outlook ? Change in one reflects in the other.

A: Using IMAP to synchronise the server and your local email client is not suitable as a backup, unless you actually make a backup of those local copies. So, though the title of the question probably does not mean you mainly want to use Outlook as a backup: see How to back up Gmail to my computer? if applicable.
When using IMAP otherwise, be very sure to understand how the Gmail Trash works, and how to use its SMTP server. When in doubt, see for example some more details at the almost duplicate How should I configure Mail.App and Google Mail? (Only a few details in that question are specific to the Mac.)

A: IMAP is a permament connection to the server, and only stores the headers of your e-mail for local reading by default. Although you can choose to download all. It will however by default try and keep both in sync at all times.
POP3 allows you to download a complete copy locally, and as long as you disabled the setting to delete e-mail from the server once downloaded, you will have a copy on both.
However when using G-Mail it normally keeps a copy in your account either way.

A: Read everything Google has on GMail IMAP protocols. I believe Outlook 2007 has the option to download all mails as well as just headers, like it does for Exchange, but I don't have it in front of me right now. This lets you read everything offline.


text:
Q: Change text color in Chrome browser header in android I have used meta tag in the header to set the theme-color in an html page. it works perfectly fine, but the text color is black, i want it to be white. Do we have a solution for this?
<meta name="theme-color" content="#db5945">
This changes header background color. Please help me with text color, if you have any idea.


text:
Q: Reusing a component over multiple modules in angular Hi guys I am fairly new to the angular space and am trying to use a component that I created in AppModule in two other modules to reduce redundant code. I tried exporting the component from AppModule and import in the other modules but that did not seem to work.
Doing that gave me the errors:
error NG6002: Appears in the NgModule.imports of AdminModule, but could not be resolved to an NgModule class.

error NG6004: Present in the NgModule.exports of AppModule but neither declared nor imported.

I am unable to solve the error. Can any of you give any suggestions as to how I can achieve my goal?

A: My suggestion is the following:

*

*If you have a folder with "shared" components, create a shared module for all of them. Include your components array in the declarations and exports of the shared module. Include this shared module in every component you wish to use it.

*If you only want to use this component as "shared", just create a module for it, add it to exports and again include this module wherever you want to use the component.
To answer your issue, it's coming from the fact that you're not importing the module that's exporting your required component.


text:
Q: $1$, $z$, and $z^{2019}$ are vertices of an equilateral triangle
Find all complex numbers $z$, such that the points, in the complex plane, which correspond to $1$, $z$, and $z^{2019}$ form an equilateral triangle.

Thanks in advance.
So far I got $$\frac{z^{2019}-1}{z-1}-\cos(\pi/3)-i\sin(\pi/3)=0$$ and $$\frac{z^{2019}-1}{z-1}-\cos(\pi/3)+i\sin(\pi/3)=0$$ and my task will be completed if I knew how many different roots these two polynomials have?

A: Let $z$ be any root of the polynomial
$$ \begin{align}f(X)&=\frac{(X^{2019}-1)^3+(X-1)^3}{(X^{2019}-1)+(X-1)}\\
&=(X^{2019}-1)^2-(X^{2019}-1)(X-1)+(X-1)^2\\
&=X^{4038}-X^{2020}-X^{2019}+X^2-X+1.\end{align}$$
Then  $a=1$, $b=z$, $c=z^{2019}$ form an equilateral triangle.
Indeed, if $z=1$, we have a degenerate equilateral triangle, which we may or may not accept as one of the possible solutoins.
In all other cases, let $w=\frac{a-c}{b-a}$ and observe that
$$ 0=(a-c)^2+(a-c)(b-a)+(b-a)^2=(w^2+w+1)(b-a)^2,$$
i.e., $w$ is a primitive third root of unity. It follows that $|a-c|=|b-a|$, but also
$$ c-b=-(a-c)-(b-a)=(-w-1)(b-a)=\overline w(b-a),$$
i.e., also $|c-b|=|b-a|$.
Hence for each of the roots of $f$ (with $z=1$ counted or not), we obtain an equilateral triangle, and there are no other solutions.
Note that $$f'(X)=4038X^{4037}-2020X^{2019}-2019X^{2019}+2X-1$$
and by a straightforward but laborious calculation, we find that
$$ \gcd(f(X),f'(X))=X-1,$$
i.e., $z=1$ is the only root of $f$ that has higher (namely, double) multiplicity. The remaining $4036$ simple roots of $f$ are proper solutions to the problem.


text:
Q: Moving items from list to list? I have two DataGridViews labeled: choiceDGV and universalDGV that are bound to binding sources labeled: choiceLineBindingSource and universalLineBindingSource.
SortableBindingList<ChoiceLine> theChoiceList = new SortableBindingList<ChoiceLine>();
SortableBindingList<UniversalLine> theUniversalList = new SortableBindingList<UniversalLine>();

I then add to each list using a foreach loops that iterates this:
theChoiceList.Add(new ChoiceLine(item1, item2, item3, item4, item5, item6, item7,
                                 item8, item9, item10, item11, item12, item13));

theUniversalList.Add(new UniversalList(stuff1, stuff2, stuff3, stuff4, stuff5, stuff6, stuff7,
                                       stuff8, stuff9, stuff10, stuff11, stuff12, stuff13));

Now I call: choiceSort(); annd universalSort();. They look like this:
private void choiceSort()
{
    var sortedChoice = theChoiceList.OrderBy(l => l.Speed);
    choiceLineBindingSource.DataSource = sortedChoice;
}

private void universalSort()
{
    var sortedUniversal = theUniversalList.OrderBy(l => l.Type);
    universalLineBindingSource.DataSource = sortedUniversal;
}

EDIT:
Here is the code for the moving of the items.
private void toUniversalButton_Click(object sender, EventArgs e)
{
    foreach (DataGridViewRow row in choiceDGV.SelectedRows)
    {
        object[] items = new object[row.Cells.Count];
        for (int i = 0; i < row.cells.Count; i++)
            items[i] = row.Cells[i].Value;

        theUniversalList.Add(new UniversalList(item1, item2, item3, item4, item5, item6, item7
                                               item8, item9, item10, item11, item12, item13));
        universalSort();

        choiceDGV.Rows.Remove(row);
    }
}

My Problem:
I also have multiple buttons that move the item from one DGV to another. So on the click, the selected item(s) from choiceDGV will be removed and added to unversalDGV. However, when I go to move the item(s) back using the other button that removes the item(s) from universalDGV and adds to choiceDGV I get duplicate items.
If this process is continued and I move the item(s) back-and-fourth 4 times, I will get that particular item(s) 4 times instead of just the one that I wanted.
So pretty much I get duplicates. Does anyone know what is going on and how I can fix it so I only get one item when I move back-and-fourth?
EDIT -- More info on the problem
I just moved every item from one list to the other so that one of the DGV's was completely visibly empty. Now when I click the button to move an item(s) from the other DGV to the visibly empty DGV it repopulates what the DGV had (before it was cleared) plus (+) the item(s) that were selected when the move button was clicked...

A: You never seem to remove the original item from theChoiceList, you need to do this at the same time you remove it from choiceDGV (choiceDGV.Rows.Remove(row)) otherwise each time you re-sort it will do it based on theChoiceList which still contains the original item plus the new one.


text:
Q: Use CMAKE_PREFIX_PATH for multi-configuration builds I am using find_package to find Qt and adding "C:\Qt\5.15.0\mingw81_64\lib\cmake" to my CMAKE_PREFIX_PATH environment variable and it has worked fine when just using 64-bit up until now. However, I want the ability to switch between 32-bit and 64-bit builds. I therefore also added the equivalent above path for 32-bit, however this resulted in linking errors (presumably CMake wasn't sure which one to pick and picked the wrong one for one of the configurations).
What is the conventional way to fix this situation? At the moment I'm using a suffix path and searching in that dependent on the compiler architecture, however ideally I'd like to leave that stuff out of the CMake project itself and simply require users of the project to add whatever Qt location themselves, while still being able to have "more than one" Qt location.
Is this solvable? Or is it malpractice to have two Qt paths in your CMAKE_PREFIX_PATH variable?

A: What is the conventional way to fix this situation?
Only add to your CMAKE_PREFIX_PATH the Qt path corresponding to the architecture you want.
[...] however ideally I'd like to leave that stuff out of the CMake project itself and simply require users of the project to add whatever Qt location themselves, while still being able to have "more than one" Qt location.
You may request the users to pass the Qt path as a parameter (when calling CMake through the command line)
cmake -DQT_PATH={PATH TO QT} ...

Or read an environment variable (which the user would have to set)
if(DEFINED ENV{QT_ENVIRON})
    set(QT_PATH $ENV{QT_ENVIRON})
else()
    set(QT_PATH ...)
endif()


text:
Q: Python creating list of lists where first item is of length one and the second item is of length n? I'm having an issue creating a list of lists in python. Suppose I have the following list:
fruitlist = [('Vendor A', 'Apples'),
('Vendor B', 'Apples'),
('Vendor C', 'Bananas'),
('Vendor A', 'Grapes'),
('Vendor A', 'Bananas'),
('Vendor B', 'Oranges')]

What I want to do is create list like this : [[Vendor A, (Apples, Grapes, Bananas)], [Vendor B, (Apples, Oranges)], [Vendor C, (Bananas)]]
So basically Vendor, and then their offerings. This is the code I currently have, it basically goes through and pulls out just a list of vendors, then loops through and snags each offering, however, the output is not quite I want.
vendors = list(set([x[0] for x in fruitlist]))
# this creates a list of just vendors:
output = [[] for x in range (len(vendors))]
#This creates a list with 3 empty lists inside (one for each vendor) where my output will be housed
    for x in range(0,len(vendors)):
        for y in range(0,len(fruitlist)):
            if fruitlist[y][0] == vendors[x]:
                output[x].append(fruitlist[y][1])

The output looks something like this:
[['Apples', 'Oranges'], ['Apples', 'Grapes', 'Bananas'], ['Bananas']]

So the output is now broken down by vendor, and each vendor's offering is now in its own list, but now I have to figure out how to insert the vendor names in there, and I simply can't. If I include the vendor name in the append portion of the for loop,
output[x].append((fruitlist[y][0],fruitlist[y][1]))

it repeats the vendor name for each fruit. If I use the insert method, it seems to create a brand new item, and increase the length of the list. I've tried a few things, I've tried googling around but I can't figure out the right phrasing. If anyone could point me to the right direction, I'd really appreciate it.
Also can anyone explain why when I look up vendors:
 ['Vendor B', 'Vendor A', 'Vendor C']

It puts "B" ahead of "A"? In my original list A was first, does the set function randomly assign the order?

A: Sets are merely collections of elements, there is no order like with lists.
The way I would write this would be to create a dictionary and then, when we convert it to a list, we can sort it to match the input order.
fruitlist = [('Vendor A', 'Apples'),
('Vendor B', 'Apples'),
('Vendor C', 'Bananas'),
('Vendor A', 'Grapes'),
('Vendor A', 'Bananas'),
('Vendor B', 'Oranges')]
vendors = {}
for vendor, fruit in fruitlist:
    vendors.setdefault(vendor, []).append(fruit)
ordered_fruitlist_vendors = [t[0] for t in fruitlist]
vendors_list = [[k, tuple(v)] for k,v in vendors.items()]
vendors_list.sort(key=lambda t: ordered_fruitlist_vendors.index(t[0]))

which gives vendors_list as:
[['Vendor A', ('Apples', 'Grapes', 'Bananas')], ['Vendor B', ('Apples', 'Oranges')], ['Vendor C', ('Bananas',)]]

However I doubt that the conversion of a neat dictionary to this clunky list of 2-element lists with tuples is necessary. Surely you want to be able to retrieve the fruits from a vendor in O(1) time with vendors['Vendor A'] rather than having to iterate over this list which will be O(n)? Anyway both methods are options now!

Explanation of setdefault.
The setdefault method of a dictionary takes two parameters - a key and a value. If the key is already present in the dictionary, the current value is returned, otherwise the key is created with the value passed into the function and that value is returned.
For example:
>>> d = {1:2}
>>> d.setdefault(1,3)
2
>>> d
{1: 2}
>>> d.setdefault(3,4)
4
>>> d
{1: 2, 3: 4}

So a neat trick that uses this method is to set a key to an empty list ([]). Then if we don't already have that key (in our case that vendor has not been seen yet), then an empty list is returned. Otherwise we get a reference to the list which contains all that vendor's fruits that we have seen so far. The beauty is that we can just add our new fruit to whatever is returned and either a new entry for that vendor will be created and the new fruit is appended or if that vendor already exists, we will just append to the previously created list.
This means that we only have to iterate over the fruitlist once so the solution is efficient.

One more example of the method in action with lists:
>>> d = {}
>>> d.setdefault(1, []).append(2)
>>> d
{1: [2]}
>>> d.setdefault(1, []).append(3)
>>> d.setdefault(1, []).append(4)
>>> d
{1: [2, 3, 4]}
>>> d.setdefault(2, []).append(3)
>>> d.setdefault(2, []).append(3)
>>> d.setdefault(2, []).append(3)
>>> d
{1: [2, 3, 4], 2: [3, 3, 3]}

A: (look ma, no dictionaries)
The data
In [15]: fruitlist = [('Vendor A', 'Apples'),
    ...:              ('Vendor B', 'Apples'),
    ...:              ('Vendor C', 'Bananas'),
    ...:              ('Vendor A', 'Grapes'),
    ...:              ('Vendor A', 'Bananas'),
    ...:              ('Vendor B', 'Oranges')]

The output list, initially empty
In [16]: output = []

We are going to use an uncommon capability of a Python's for loop, that is the else clause.  The body of the else clause is executed if the for body ended normally, that is without a break
In [17]: for vendor, fruit in fruitlist:
    ...:     for sublist in output:
    ...:         if sublist[0] == vendor:
    ...:             sublist[1].append(fruit)
    ...:             break
    ...:     else:
    ...:         output.append([vendor, [fruit]])

Eventually we check our result
In [18]: output
Out[18]:
[['Vendor A', ['Apples', 'Grapes', 'Bananas']],
 ['Vendor B', ['Apples', 'Oranges']],
 ['Vendor C', ['Bananas']]]

I have to say that the original question mentioned sublist where the second element is a tuple, while I have a list, but tuples are immutable...

A: You can use a simple for loop and a dictionary no need to overcomplicate it
fruits = [
    ('Vendor A', 'Apples'),
    ('Vendor B', 'Apples'),
    ('Vendor C', 'Bananas'),
    ('Vendor A', 'Grapes'),
    ('Vendor A', 'Bananas'),
    ('Vendor B', 'Oranges')
]

dicta = {}

for vendor, item in fruits:
    if vendor not in dicta:
        dicta[vendor] = [item]
    else:
        dicta[vendor].append(item)

print(dicta)

(xenial)vash@localhost:~/python/stack_overflow$ python3.7 fruits.py
{'Vendor A': ['Apples', 'Grapes', 'Bananas'], 'Vendor B': ['Apples', 'Oranges'], 'Vendor C': ['Bananas']}


text:
Q: Dynamic memory allocation with aligned storage I'm a bit confused about the alignement requirements when std::aligned_storage is used and dynamic allocation is needed. Example:
  using storage = typename std::aligned_storage<sizeof(T), std::alignment_of<T>::value>::type;
  storage* pool;
  pool = ::new storage[num_obj];

Is it legal? The new operator doesn't return alignment memory, so is the result correct?

A: The C++11 standard requires that allocation functions such as ::operator new return memory that is aligned to alignof(std::max_align_t) [basic.stc.dynamic/2]:

The pointer returned shall be suitably aligned so that it can be converted to a pointer of any complete object type with a fundamental alignment requirement […]

Thus, as long as the type of the object you're creating via your new expression is not an overaligned type (one that requires an alignment more strict than alignof(std::max_align_t)), everything's fine. For overaligned types, you would indeed have to allocate storage of sufficient size to manually align the pointer, e.g., using std::align, and then construct your object at a suitable address, e.g., via placement new…
Starting with C++17, new automatically takes care of this. To allocate storage that requires alignment more strict than __STDCPP_DEFAULT_NEW_ALIGNMENT__ (the alignment that allocation functions are at least required to supply), a new-expression will call an allocation function that is explicitly given the alignment of the storage to be allocated as an argument [expr.new]/14 …


text:
Q: R: function parameters inheritance So i have the following code:
library(semPLS)
data(ECSImobi)

#exponent vector for transformation of the dataset
#model of type plsm
#data
#returns a list of models with length of exponent vector
#list items are of class sempls
CalcModels <- function(exponent,model,data){

  #initialize result as list
  result <- vector("list")

  #estimate models with different distances
  for(i in seq_along(exponent)){
    result[[i]] <- sempls(model=model, data = data^exponent[i])
  }

  return(result)

}

#calculate ecsi models with exponent 0.1, 0.2, ..., 2.0
ecsiModels <- CalcModels(c(1:20/10),ECSImobi,mobi)

The sempls() function has numerous other parameters. Is there any way I can give them to the CalcModels function, so I can call the CalcModels function with the additional parameter wscheme="pw" of the sempls function. I could write them all in the parameters of both functions, but I think there must be a smarter way that I'm missing.
So I want something like that:
library(semPLS)
data(ECSImobi)

#exponent vector for transformation of the dataset
#model of type plsm
#data
#returns a list of models with length of exponent vector
#list items are of class sempls
CalcModels <- function(exponent,model,data,wscheme){

  #initialize result as list
  result <- vector("list")

  #estimate models with different distances
  for(i in seq_along(exponent)){
    result[[i]] <- sempls(model=model, data = data^exponent[i],wscheme=wscheme)
  }

  return(result)

}

#calculate ecsi models with exponent 0.1, 0.2, ..., 2.0
ecsiModels <- CalcModels(c(1:20/10),ECSImobi,mobi,"pw")

but instead of writing each parameter in both functions do some kind of inheritance of the parameters without overwriting the function.

A: Would you like to use ellipsis (see here for more details)? This is a very useful technique to pass arguments to another function. All you would need to do is to add ... to the definition of function:
CalcModels <- function(exponent,model,data,...){

  #initialize result as list
  result <- vector("list")

  #estimate models with different distances
  for(i in seq_along(exponent)){
    result[[i]] <- sempls(model=model, data = data^exponent[i],...)
  }

  return(result)

}

Ellipsis can pass any number of parameters.


text:
Q: keyerror the name "import/Placeholder" refers to an operation not in the graph So I was trying to run the Tensorflow retraining for the Inception V3 model, and no matter what I tried, running the label_image command didn't work.
I tried resetting the values as such:
input_height = 299
input_width = 299
input_mean = 0
input_std = 299
input_layer = "input"
output_layer = "final_result"

and like so:
input_height = 299
input_width = 299
input_mean = 0
input_std = 299
input_layer = "Mul"
output_layer = "final_result"

the command
python label_image.py --graph=output_graph.pb --labels=output_labels.txt --output_layer=final_result --input_layer=Placeholder --image=fox.png

yields the error in the title.
changing the command to:
python label_image.py --graph=output_graph.pb     --labels=output_labels.txt --output_layer=final_result --input_layer=input --image=fox.png

gives the same error but with 'import/input'
Command as it is now:
python label_image.py --graph=output_graph.pb --labels=output_labels.txt --output_layer=final_result --image=fox.png

Error:
Traceback (most recent call last):
  File "label_image.py", line 128, in <module>
    input_operation = graph.get_operation_by_name(input_name)
  File "C:\Users\Phil\AppData\Local\Programs\Python\Python37\lib\site-packages\t
ensorflow\python\framework\ops.py", line 3606, in get_operation_by_name
    return self.as_graph_element(name, allow_tensor=False, allow_operation=True)

  File "C:\Users\Phil\AppData\Local\Programs\Python\Python37\lib\site-packages\t
ensorflow\python\framework\ops.py", line 3478, in as_graph_element
    return self._as_graph_element_locked(obj, allow_tensor, allow_operation)
  File "C:\Users\Phil\AppData\Local\Programs\Python\Python37\lib\site-packages\t
ensorflow\python\framework\ops.py", line 3538, in _as_graph_element_locked
    "graph." % repr(name))
KeyError: "The name 'import/input' refers to an Operation not in the graph."


text:
Q: Can't use Sequelize.Op.Not as intended on Sequelize I have the following code:
async getMentorSchedule(mentorId) {
    try{
        var schedule = await MentorSchedule.findAll({
            where: {
                personId: mentorId,
                id: {
                    [Sequelize.Op.not]: Sequelize.col('mentoring.mentor_schedule_id')
                }
            },
            include: [
                {
                    model: Mentoring,
                }
            ],
        })

        return {
            status: 200,
            message: 'Agenda carregada com sucesso',
            content: schedule
        }
    } catch (error) {
        console.log(error.message)
        return {
            status: 500,
            message: error.message,
            content: []
        }
    }
}

I want to get all MentorSchedule rows which id isn't in Mentoring table as a Foreign Key. The following code doesn't returns any rows, just a empty list. Why is this happening?

A: Well, i've achieved to make it work. The following code:
    async getMentorSchedule(mentorId) {
    try{
        var schedule = await MentorSchedule.findAll({
            where: [
                Sequelize.where(Sequelize.col('mentor_schedule.person_id'), mentorId),
                Sequelize.where(Sequelize.col('mentoring.id'), null),
            ],
            include: [
                {
                    model: Mentoring,
                    required: false,
                }
            ],
        })

        return {
            status: 200,
            message: 'Agenda carregada com sucesso',
            content: schedule
        }
    } catch (error) {
        console.log(error.message)
        return {
            status: 500,
            message: error.message,
            content: []
        }
    }
}

Basically, it searchs for null entries on relationship (this.hasOne(models.Mentoring)) in MentorSchedule. So, it returns all MentorSchedule rows which id isn't in Mentoring table as a Foreign Key.


text:
Q: Jackson serialization with ObjectMapper in java I want to serialize the different types of lists by using object mapper, but I do not know how to
  pass the different types of list objects into object Mapper at a time. The following is my code:
AccountingService accService      = ServiceFactory.getAccountingService();
List<TaxCategory> taxCategoryList = accService.getAllTaxCategories();
ProductService productService     = ServiceFactory.getProductService();
List<SimpleUom> simpleUomList     = productService.getSimpleUomsList();

ObjectMapper objMapper;
objMapper.writeValueAsString(?)--

Would You please suggest what I have to pass instead of ? in above code. This is because of i have to get the jackson serialized string that includes above lists as a single string in jsp and parse that string to get individual lists to be used at client side.

A: Simply try:
ObjectMapper objMapper = new ObjectMapper();
String jsonString = objMapper.writeValueAsString(simpleUomList);

Edit according to the comment:
You need to create a class wrapping your two lists and then write it:
public class MyLists {
    private List<TaxCategory> taxCategoryList;
    private List<SimpleUom> simpleUomList;
    // + constructor, getters and setters
}

ObjectMapper objMapper = new ObjectMapper();
MyLists myLists = new MyLists(taxCategoryList, simpleUomList);
String jsonString = objMapper.writeValueAsString(myLists);


text:
Q: Querying Firebase A/B testing using API I'm writing a script that will generate extended A/B testing results. Is it possible to query Firebase A/B testing using API to get an experiment variant list, start date, end date, etc?

A: There currently is no API to get/manage the list of experiments for Firebase A/B testing. All management of experiments must be done through the Firebase console at the moment.
You might want to file a feature request, and keep an eye out on the Firebase blog and release notes for changes.


text:
Q: Why is this program not optimized away? Consider the following, simple program (adapted from this question):
#include <cstdlib>

int main(int argc, char** argv) {
    int mul1[10] = { 4, 1, 8, 6, 3, 2, 5, 8, 6, 7 }; // sum = 50
    int mul2[10] = { 4, 1, 8, 6, 7, 9, 5, 1, 2, 3 }; // sum = 46

    int x1 = std::atoi(argv[1]);
    int x2 = std::atoi(argv[2]);

    int result = 0;

    // For each element in mul1/mul2, accumulate the product with x1/x2 in result
    for (int i = 0; i < 10; ++i) {
        result += x1 * mul1[i] + x2 * mul2[i];
    }

    return result;
}

I believe it is functionally equivalent to the following one:
#include <cstdlib>

int main(int argc, char** argv) {
    int x1 = std::atoi(argv[1]);
    int x2 = std::atoi(argv[2]);

    return x1 * 50 + x2 * 46;
}

And yet clang 3.7.1, gcc 5.3 and icc 13.0.1 seem to be unable to make such optimization, even with -Ofast. (Note by the way how the generated assembly is vastly different between compilers!). However, when removing mul2 and x2 from the equation, clang is able to perform a similar optimization, even with -O2.
What prevents both compilers from optimizing the first program into the second?

A: The complete expression is too complicated even for clang. If you split it then everything gets optimized again:
int result1 = 0;
int result2 = 0;

for (int i = 0; i < 10; ++i) {
    result1 += x1 * mul1[i];
    result2 += x2 * mul2[i];
}

std::cout << (result1 + result2);

A: I'm not a compiler programmer so this can only be a guess. IMHO, the answer is part in @dlask's answer and part in the remark that clang does the optimisation when you remove x2 and mul2 from the expression.
The compiler may optimize away all that it can do. But I also think that optimizing compilers are already huge and complicated programs, in which bugs can have high consequences because they are at the base of almost everything else (Python most current interpreter is written in ... C)
So there must be a balance between the efficiency of the optimizer and its complexity, and I think that this example program is beyond it for gcc, and just around for clang. Nothing prevents them to do that optimization except that it is just too complicated for current version of those compilers.


text:
Q: Python: Find largest array index along a specific dimension which is greater than a threshold Lets say I have a 4-D numpy array (ex: np.rand((x,y,z,t))) of data with dimensions corresponding to X,Y,Z, and time.
For each X and Y point, and at each time step, I want to find the largest index in Z for which the data is larger than some threshold n.
So my end result should be an X-by-Y-by-t array. Instances where there are no values in the Z-column greater than the threshold should be represented by a 0.
I can loop through element-by-element and construct a new array as I go, however I am operating on a very large array and it takes too long.

A: Unfortunately, following the example of Python builtins, numpy doesn't make it easy to get the last index, although the first is trivial.  Still, something like
def slow(arr, axis, threshold):
    return (arr > threshold).cumsum(axis=axis).argmax(axis=axis)

def fast(arr, axis, threshold):
    compare = (arr > threshold)
    reordered = compare.swapaxes(axis, -1)
    flipped = reordered[..., ::-1]
    first_above = flipped.argmax(axis=-1)
    last_above = flipped.shape[-1] - first_above - 1
    are_any_above = compare.any(axis=axis)
    # patch the no-matching-element found values
    patched = np.where(are_any_above, last_above, 0)
    return patched

gives me
In [14]: arr = np.random.random((100,100,30,50))

In [15]: %timeit a = slow(arr, axis=2, threshold=0.75)
1 loop, best of 3: 248 ms per loop

In [16]: %timeit b = fast(arr, axis=2, threshold=0.75)
10 loops, best of 3: 50.9 ms per loop

In [17]: (slow(arr, axis=2, threshold=0.75) == fast(arr, axis=2, threshold=0.75)).all()
Out[17]: True

(There's probably a slicker way to do the flipping but it's the end of day here and my brain is shutting down. :-)

A: Here's a faster approach -
def faster(a,n,invalid_specifier):
    mask = a>n
    idx = a.shape[2] - (mask[:,:,::-1]).argmax(2) - 1
    idx[~mask[:,:,-1] & (idx == a.shape[2]-1)] = invalid_specifier
    return idx

Runtime test -
# Using @DSM's benchmarking setup

In [553]: a = np.random.random((100,100,30,50))
     ...: n = 0.75
     ...:

In [554]: out1 = faster(a,n,invalid_specifier=0)
     ...: out2 = fast(a, axis=2, threshold=n) # @DSM's soln
     ...:

In [555]: np.allclose(out1,out2)
Out[555]: True

In [556]: %timeit fast(a, axis=2, threshold=n)  # @DSM's soln
10 loops, best of 3: 64.6 ms per loop

In [557]: %timeit faster(a,n,invalid_specifier=0)
10 loops, best of 3: 43.7 ms per loop


text:
Q: 3.5mm PCIe Headset sound card I.e.same as laptop - not seperate mic socket I recently built a few new PC's for our home and buying budget motherboards I was surprised I couldn't find any with headset output either for front panel or rear panel connections (its been 5 years or so since I built the last batch of family/gaming PC's).
So I decided I would simply build the PC's and find a PCIe headset soundcard later and fit to rear panel. Now its 'later' and 'simply' seems not an option as all the sound cards I can find seem to be 5.1 and 7.1 with separate microphone.
I am not interested in a splitter lead or any USB dongle suggestions/options.
Does the PCIe card I am after have a particular name so I can search directly and can anyone link me to a suitable product?


text:
Q: graphical query language algorithms My intention is to write a graphical query language where users can drag and drop criteria into a GUI query designer, then the designer will generate appropriate SQL query code and return the appropriate result set. Do you know where I can learn more about SQL code generation or if similar tools like this exist?

A: You may want to look at Microsoft Access's query designer to see how it works; it's relatively simple to use and you can compare how changes in the graphical representation affect the SQL statement and vice-versa.  It should give you a pretty good view of how joins are translated into SQL.
(I cringe to suggest Microsoft Access for anything, but in this case, it might be useful to you).


text:
Q: How to set up PyAMF Django gateway so it uses AMF3? How to set up PyAMF Django gateway so it uses AMF3 instead of the default AMF0?

A: By default PyAMF supports both AMF0 (NetConnection remoting) and AMF3 (Flex messaging) of which RemoteObject is one flavour.
The docs give a simple example of how to approach a PyAMF gateway with both.
Also, you can set pyamf.DEFAULT_ENCODING = pyamf.AMF3 :-)


text:
Q: npm installation of jsreport is failing I am not sure what is to blame here. Is it npm having a problem or a specific package that is corrupted or something?
I am trying to install JSReport on an Azure Ubuntu VM and have followed the simple instructions here (http://jsreport.net/downloads/). However, when I run the sudo npm install jsreport --production I get this error from npm:
npm http GET https://registry.npmjs.org/sntp
npm http 304 https://registry.npmjs.org/boom
npm http 304 https://registry.npmjs.org/sntp
npm http 304 https://registry.npmjs.org/hoek
npm http 304 https://registry.npmjs.org/cryptiles
npm WARN engine boom@2.10.1: wanted: {"node":">=0.10.40"} (current: {"node":"v0.10.25","npm":"1.3.10"})
npm WARN engine hoek@2.16.3: wanted: {"node":">=0.10.40"} (current: {"node":"v0.10.25","npm":"1.3.10"})
npm WARN engine cryptiles@2.0.5: wanted: {"node":">=0.10.40"} (current: {"node":"v0.10.25","npm":"1.3.10"})
npm http GET https://registry.npmjs.org/weak-map/1.0.0
npm http 304 https://registry.npmjs.org/weak-map/1.0.0
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR!     /home/<username>/npm-debug.log
npm ERR! not ok code 0

And of course... when I look for /home/<username>/npm-debug.log there is no file at all. I have tried deleting the node_modules twice now and retrying without any luck. Any ideas?

A: You need to upgrade your version of node. It seems you currently have v0.10.25 installed, but some packages need/want at least v0.10.40. As far as the node v0.10 branch goes, v0.10.43 is the latest as of this writing. The latest node LTS release is v4.4.0 and latest stable node release is v5.9.0.

A: Extending correct @mscdex answer with updated jsreport ubuntu installation guide: https://github.com/jsreport/docs/blob/master/installation/ubuntu.md

Official ubuntu apt-get distribution contains outdated node.js. I
  prefer to use nvm to manage my node.js installation.
wget -qO- https://raw.githubusercontent.com/creationix/nvm/v0.31.0/install.sh | bash

If you are using terminal like putty, you cannot pipe the installation
  to the bash, so you need to save it to file and run it. Afterwards you
  need to reopen the terminal.
wget -qO- https://raw.githubusercontent.com/creationix/nvm/v0.31.0/install.sh > install.sh
chmod +x install.sh
./install.sh

Now install node.js
nvm install 5

To be able to sudo run the npm or node you need to also run the
  following command
n=$(which node);n=${n%/bin/node}; chmod -R 755 $n/bin/*; sudo cp -r $n/{bin,lib,share} /usr/local

Afterwards you should be able to run
sudo npm install jsreport --production


text:
Q: how to check condition in xml? i have 2 links login1 and login2 when i click login1 that should avoid filter node which has login filter in xml, that means it should not read <filter-name>LoginFilter</filter-name> i have googled got some examples how to modify xml using java but is there a way which can check condition without changing xml file
here is my xml file:
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app id="WebApp_ID" version="2.4"
        xmlns="http://java.sun.com/xml/ns/j2ee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" >

        <display-name>OIOSAML-J</display-name>
        <env-entry>
            <env-entry-name>oiosaml-j.home</env-entry-name>
            <env-entry-type>java.lang.String</env-entry-type>
            <env-entry-value>c:\oiosaml-config</env-entry-value>
        </env-entry>

        <listener>
            <listener-class>dk.itst.oiosaml.sp.service.session.SessionDestroyListener</listener-class>
        </listener>

        <servlet>
            <servlet-name>SAMLDispatcherServlet</servlet-name>
            <servlet-class>
                dk.itst.oiosaml.sp.service.DispatcherServlet
            </servlet-class>
            <load-on-startup>1</load-on-startup>
        </servlet>

        <servlet-mapping>
            <servlet-name>SAMLDispatcherServlet</servlet-name>
            <url-pattern>/saml/*</url-pattern>
        </servlet-mapping>
    <filter>
    <filter-name>PrimeFaces FileUpload Filter</filter-name>
    <filter-class>org.primefaces.webapp.filter.FileUploadFilter</filter-class>
  </filter>
        <filter>
            <filter-name>LoginFilter</filter-name>
            <filter-class>dk.itst.oiosaml.sp.service.SPFilter</filter-class>
        </filter>
        <filter-mapping>
            <filter-name>LoginFilter</filter-name>
            <url-pattern>/sp/*</url-pattern>
        </filter-mapping>
<filter-mapping>
    <filter-name>PrimeFaces FileUpload Filter</filter-name>
    <servlet-name>Faces Servlet</servlet-name>
  </filter-mapping>
        <welcome-file-list>
            <welcome-file>index.jsp</welcome-file>
        </welcome-file-list>
    </web-app>

here is my view code:

   <h:body>

Login1
|
login2

    </h:body>

A: The LoginFilter will be triggered on every request going to any target under /sp/.
If you want a webpage does not trigger this Filter you must make sure that the page is not on a path that will trigger the filter. May be have a structure like this.
/
/sp/
/public/

and put the login page in public


text:
Q: SDL_RenderGeometry could not be located in the dyamic link library I am trying to use SDL_RenderGeometry in visual studio, but an error keeps on popping up. It says
The procedure entry point SDL_RenderGeometry could not be located in dynamic link library

I have tried to re-install SDL, and even downgraded to version 2.20.
I'm not sure what else I should provide since that is the only error message.


text:
Q: What is the best way to make a Windows service ask the user for input? I'm trying to write a program to ask me to input some information periodically, so I've written a service in C to run in the background, I can watch it reporting its okay by refreshing its log file. Now I'm stuck on how to get it to open up cmd and ask for the information.
I'd like to save this information to a log file. (I'm planning on monitoring my sleeping habits)
I tried using system("getinput.exe") and that seems to do nothing, I know using system() is bad but it was a first step.
CreateProcess() I simply cannot get to work, the example on MSDN http://msdn.microsoft.com/en-us/library/ms682512.aspx doesn't work for me, i just get CreateProcess failed (2) whenever i try createprocess.exe dir for example.
Surely there must be a way?
EDIT: Thanks for the replies I will try to take a different approach then. Where would I start with writing a background application that can occasionally ask for user input in C?


text:
Q: function only works when clicked twice i'm quite new when it comes to programming, so i do have some basic issues. one of them, that i can't really solve is the following:
i wrote a javascript code to change a div's content on a button click. it works fine, but only on the second click.
the buttons html:

Home

the javascript:
var buttonId = "";
var contentText = "";

function navClick(clicked_id)
{
    buttonId = clicked_id;
    changeContent();
}

function changeContent(){
    fetch("./pages/"+buttonId+".txt")
    .then(function(response){
        return response.text()
        })
        .then(function(data){
            contentText = data;
        })
        document.getElementById("content").innerHTML = contentText;
}

A: It looks like an async mishap. Try it like this:
var buttonId = "";
var contentText = "";

function navClick(clicked_id)
{
    buttonId = clicked_id;
    changeContent();
}

function changeContent(){
    fetch("./pages/"+buttonId+".txt")
    .then(function(response){
        return response.text()
    })
    .then(function(data){
        contentText = data;
        document.getElementById("content").innerHTML = contentText;
    })
}

The innerHMTML needs to be updated inside the then, otherwise it will probably run before the fetch completes. My best guess.


text:
Q: Which user settings are used by python's virtual environment? Note: The following behaviour is observed on MAC OS Monterey 12.3.1
When I ran a command to start the mlflow server inside a newly created python venv:

mlflow server --backend-store-uri postgresql://mlflow_user:mlflow@localhost/mlflow  --artifacts-destination S3://<bucket_name>/mlflow/ --serve-artifacts  -h 0.0.0.0 -p 8000

It gave me Access denied error:

botocore.exceptions.ClientError: An error occurred (AccessDenied) when calling the ListObjectsV2 operation: Access Denied

Now, when I tried it using sudo, i.e.,

sudo mlflow server --backend-store-uri postgresql://mlflow_user:mlflow@localhost/mlflow  --artifacts-destination S3://<bucket_name>/mlflow/ --serve-artifacts  -h 0.0.0.0 -p 8000

I could access the bucket's artifacts.
My Question:
When I didn't used sudo, which user settings were used by the python's venv


text:
Q: highlight the word in the string, if it contains the keyword how write the script, which menchion the whole word, if it contain the keyword? example: keyword "fun", string - the bird is funny, result - the bird is * funny*. i do the following
     $str = "my bird is funny";
     $keyword = "fun";
     $str = preg_replace("/($keyword)/i","$1",$str);

but it menshions only keyword.  my bird is funny

A: Try this:
preg_replace("/\w*?$keyword\w*/i", "$0", $str)

\w*? matches any word characters before the keyword (as least as possible) and \w* any word characters after the keyword.
And I recommend you to use preg_quote to escape the keyword:
preg_replace("/\w*?".preg_quote($keyword)."\w*/i", "$0", $str)

For Unicode support, use the u flag and \p{L} instead of \w:
preg_replace("/\p{L}*?".preg_quote($keyword)."\p{L}*/ui", "$0", $str)

A: You can do the following:
 $str = preg_replace("/\b([a-z]*${keyword}[a-z]*)\b/i","$1",$str);

Example:
$str = "Its fun to be funny and unfunny";
$keyword = 'fun';
$str = preg_replace("/\b([a-z]*${keyword}[a-z]*)\b/i","$1",$str);
echo "$str"; // prints 'Its fun to be funny and unfunny'

A: <?php
$str = "my bird is funny";

$keyword = "fun";
$look = explode(' ',$str);

foreach($look as $find){
    if(strpos($find, $keyword) !== false) {
        if(!isset($highlight)){
            $highlight[] = $find;
        } else {
            if(!in_array($find,$highlight)){
                $highlight[] = $find;
            }
        }
    }
}

if(isset($highlight)){
    foreach($highlight as $replace){
        $str = str_replace($replace,''.$replace.'',$str);
    }
}

echo $str;
?>

A: Here by am added multi search in a string for your reference
$keyword = ".in#.com#dot.com#1#2#3#4#5#6#7#8#9#one#two#three#four#five#Six#seven#eight#nine#ten#dot.in#dot in#";

$keyword = implode('|',explode('#',preg_quote($keyword)));

$str = "PHP is dot .com the amazon.in 123455454546 dot in scripting language of choice.";

$str = preg_replace("/($keyword)/i","$0",$str);
echo $str;

A: Basically, since this is HTML, what you have to do is iterate over text nodes and split those containing the search string into up to three nodes (before match, after match and the highlighted match). If "after match" node exist, it must be processed too. Here is a PHP7 example using PHP DOM extension. The following function accepts preg_quoted UTF-8 search string (or regex-conpatible expression like apple|orange). It will enclose every match in a given tag with a given class.
function highlightTextInHTML($regex_compatible_text, $html, $replacement_tag = 'span', $replacement_class = 'highlight') {
    $d = new DOMDocument('1.0','utf-8');
    $d->loadHTML('<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>' . $html);
    $xpath = new DOMXPath($d);

    $process_node = function(&$node) use($regex_compatible_text, $replacement_tag, $replacement_class, &$d, &$process_node) {
        $i = preg_match("~(?<before>.*?)(?<search>($regex_compatible_text)+)(?<after>.*)~ui", $node->textContent, $m);
        if($i) {
            $x = $d->createElement($replacement_tag);
            $x->setAttribute('class', $replacement_class);
            $x->textContent = $m['search'];
            $parent_node = $node->parentNode;
            $before = null;
            $after = null;
            if(!empty($m['after'])) {
                $after = $d->createTextNode($m['after']);
                $parent_node->replaceChild($after, $node);
                $parent_node->insertBefore($x, $after);
            } else {
                $parent_node->replaceChild($x, $node);
            }
            if(!empty($m['before'])) {
                $before = $d->createTextNode($m['before']);
                $parent_node->insertBefore($before, $x);
            }
            if($after) {
                $process_node($after);
            }
        }
    };

    $node_list = $xpath->query('//text()');
    foreach ($node_list as $node) {
        $process_node($node);
    }
    return preg_replace('~(^.*)|(.*$)~mis', '', $d->saveHTML());
}

A: Search and highlight the word in your string, text, body and paragraph:
<?php $body_text='This is simple code for highligh the word in a given body or text';  //this is the body of your page
$searh_letter = 'this';  //this is the string you want to search for
$result_body = do_Highlight($body_text,$searh_letter);    // this is the result with highlight of your search word
echo $result_body;            //for displaying the result
function do_Highlight($body_text,$searh_letter){     //function for highlight the word in body of your page or paragraph or string
     $length= strlen($body_text);    //this is length of your body
     $pos = strpos($body_text, $searh_letter);   // this will find the first occurance of your search text and give the position so that you can split text and highlight it
     $lword = strlen($searh_letter);    // this is the length of your search string so that you can add it to $pos and start with rest of your string
     $split_search = $pos+$lword;
     $string0 = substr($body_text, 0, $pos);
     $string1 = substr($body_text,$pos,$lword);
     $string2 = substr($body_text,$split_search,$length);
     $body = $string0."".$string1."  ".$string2;
     return $body;
    } ?>


text:
Q: monitor process uptime on Windows We want to monitor some processes on windows machine. If process is down for 30 minutes, an alarm will be raised. Is it possible/or necessary to monitor a process downtime precisely, say, a process is down EXACTLY for 30 minutes, then an alarm will be raised? Normally, we can check it every 1 minute, but technically, most of the time, you could miss somes seconds.

A: If you're looking for something much lighter and simpler then Nagios, see AlertGrid. It is very esay to use, the only downside is that it requires a bit of integration: AlertGrid only LISTENS for heartbeat signals, so you have to provide them manually (the API is extremely simple).
The other cool thing is that if the process you want to monitor runs YOUR code - you can send heartbeat events directly "from inside", and these events can carry your own custom parameters. Then, in the AlertGrid - you can easily manage custom rules around these parameters. So if the executable you monitor is, for instance, an order processing application you can send parameter called 'number_of_orders_processed' and create rule "if number_of_orders_processed > 100, send SMS message / make phone call to... " and it will work immediately.
I am in the AlertGrid dev team, if you have any questions - feel free to ask.

A: Look into Nagios and NSClient++ if you can monitor your Windows host from a Linux host.  If this would be an option there is room to do this and many many other things in regards to monitoring your processes and more.


text:
Q: How to comparison between register with arrays and numbers typedef struct {
int codigo;
char Nombre[MAX_NAME];
char Especie[MAX_ESP];
char tipo;
int voto;
bool controles[MAX_CONTROLES];
int num_controles;
}TAnimal;

TAnimal zoo[500];

if (zoo[i].controles == 1){

controles is boolean, so my error is
ISO C++ forbids comparison between pointer and integer [-fpermissive]

So, how can i compare that?

A: controles[] is not bool, it is an array of bool.
bool controles[MAX_CONTROLES];

When you use it like this
if (zoo[i].controles == 1){

Using the base address of the array, makes it to decay to a pointer, Hence the error
ISO C++ forbids comparison between pointer and integer [-fpermissive]

Depending on your requirement, I would guess that you are trying to compare with one of the elements in that array controles[]. And to access that element you need to provide the index of that element in place of x in the below line
if (zoo[i].controles[ x ] == 1){


text:
Q: Why there are many instructions with zero destination that not affectting the hardware in RISC-V ISA? The first register is hardware zero in RISC-V ISA. It is used in many cases such as calling zero to another register, and jumping but not storing the address, etc.
However, there are many possibilities that don't change the hardware when the destination register is zero and we don't need those possible instructions because they are not used for any porpuse. I feel it is wasting the bits for other functional instructions. What am I missing in this issue? Why it is so?
As I know, the bits in ISA are expensive so ISA developers try to keep them as simple and compressed as possible to cover many different functionalities. However, it makes me feel the reverse because of many instructions that use the destination with the first register that is hardwired to zero.
I don't know if they are reserved for future usage or if the first register (x0) can be used without hardwiring zero.

A: One question the original designers were concerned with answering is: what will cost less hardware for a small embedded system?  Having useless instructions like add x0, x0, x0 or even add x0, a0, a1?  Or doing something useful with those otherwise useless encoding?  And the answer is the former, to the question of what will take less hardware.
Another is: what will allow the most common (and also useful) instructions to execute as quickly as possible.  Decoding and add x0, x0, x0, or, add x0, a0, a1, so that it will do something different (from no-op) can slow down the useful add instructions as follows: while some of that decoding can happen in parallel (with added hardware), ultimately, the two paths, decoding add x0, a0, a1 and decoding a normal add a0, a0, a1 have to merge and that generally happens with muxes.  The more muxes that are introduced, the longer the cycle has to be, so doing that has the effect of slowing down the whole processor.

The designers of RISC V went to lengths to remove one mux from the decode phase as compared to MIPS, by keeping the target register field in a fixed position for both R- and I-Type instructions.


text:
Q: Busca sem refresh por select Boa noite... gostaria de saber como faço uma busca atraves de um select e de checkbox, como no site do webmotors...
Procurei na internet mas não achei nada parecido... Alguem conhece algo assim?


text:
Q: Can't connect MariaDB from Docker using Python I am trying to connect mariadb that runs as a docker-compose service. I have antoher service named "app" and includes a new python file in it just to connect db.
It successfully connects to phpmyadmin but when I try to connect with python it fails for some reason:
error message:
mysql.connector.errors.InterfaceError: 2003: Can't connect to MySQL server on 'mariadb:3306' (-3 Try again)

docker-compose.yml
version: "3"
services:
  app:
    build:
        context: .
        dockerfile: ./Dockerfile
    volumes:
      - ./app:/app
    command: >
        sh -c "python3 services/db_connection.py"
    depends_on:
        - mariadb
  prestashop:
    image: prestashop/prestashop
    networks:
      myprestashop:
    ports:
      - 8181:80
    links:
      - mariadb:mariadb
    depends_on:
      - mariadb
    volumes:
      - /srv/Configs/PrestaShop/src:/var/www/html
      - /srv/Configs/PrestaShop/src/modules:/var/www/html/modules
      - /srv/Configs/PrestaShop/src/themes:/var/www/html/themes
      - /srv/Configs/PrestaShop/src/override:/var/www/html/override
    environment:
      - PS_DEV_MODE=1
      - DB_SERVER=mariadb
      - DB_USER=root
      - DB_PASSWD=mycustompassword
      - DB_NAME=prestashop
      - PS_INSTALL_AUTO=0

  mariadb:
    image: mariadb
    networks:
      myprestashop:
    volumes:
      - /srv/Databases/PrestaShop:/var/lib/mysql
    environment:
      - MYSQL_ROOT_PASSWORD=mycustompassword
      - MYSQL_DATABASE=prestashop

  phpmyadmin:
    image: phpmyadmin/phpmyadmin
    networks:
      myprestashop:
    links:
      - mariadb:mariadb
    ports:
      - 1235:80
    depends_on:
      - mariadb
    environment:
      - PMA_HOST=mariadb
      - PMA_USER=root
      - PMA_PASSWORD=mycustompassword

networks:
  myprestashop:

db_connection.py
import mysql.connector as database

connection = database.connect(
    user='root',
    password='mycustompassword',
    host='mariadb',
    database='prestashop')

if connection:
    print ("Connected Successfully")
else:
    print ("Connection Not Established")

Thanks for any help

A: You forgot to add myprestashop network to your app service. If a service does not have any explicitly defined network it uses a default one (it's a name like myproject_default). So the reason of the error is that the app service is in one network and everything else in another (myprestashop).


text:
Q: Pseudo-code algorithm to calculate all permutations of N values chosen from N unequal vectors without repetition This question is for a program I am trying to write which involves connecting chains of physical parts together. I believe I have distilled it down into the simplest form of the question.  I would also appreciate if someone knows any additional words that describe this problem, as about 30 min of searching for related questions hasn't even turned up a name for this problem.
You have N vectors.  If you choose one value from each vector and do not allow any repeats, you will have one permutation of the type I am trying to find.  What is a pseudo-code algorithm to find all of them without brute forcing?
Example:
You have the vectors
v1=[1 2]   v2=[1 2 3]   v3=[1 2 3 4]

(Edit note: The nesting of the vectors is unintentional and cannot be leveraged in the algorithm.)
You pick values from each of the vectors and don't allow repeats.
Value 1 is from v1 ---> 2
Value 2 is from v2 ---> 1
Value 3 is from v3 ---> 4

Resulting permutation is [2 1 4].

This is one allowable permutation.  Here is an example of a permutation that is not allowed because it repeats.
Value 1 is from v1 ---> 2
Value 2 is from v2 ---> 1
Value 3 is from v3 ---> 2

Resulting permutation is [2 1 2], which is invalid due to repeats.

What is an algorithm to find all valid permutations?
Bonus points if you can calculate how many permutations there are before calculating them.
I'll be sure to post back if I can come up with an answer before anyone else can.

A: The example you give has nested vectors, meaning that the entries in v_i are a subset of those in v_{i+1}. If this is indeed the general case for your application, then the number of solutions is simply:
n_1 * (n_2 - 1) * ... * (n_k - (k-1))

where n_i is the length of v_i and there are k nested vectors.
As far as algorithms are concerned, if you want to generate all possible solutions, then I cannot see a better way than to choose from each successive vector after eliminating already selected entries.
If you aren't nested, a good way to visualize this problem is as a Marriage Problem in the following sense. Make k vertices corresponding to the given k vectors
v_1  v_2 ...  v_k

and another m vertices corresponding to the distinct entries of the combined vectors
a_1 a_2 ... a_m

Then connect a_i to v_j if and only if a_i appears in v_j. The goal is to find a maximum matching between the vs and the as that touches all of the v's. That is, choose k edges so that each v_i is an endpoint of exactly one edge.
Any of the standard algorithms, e.g. using augmented paths, will work to find one solution or generate them all.

A: I think you can solve this problem incrementally. Let s1, s2, s3,..,sk be the solutions involving v1, v2, .., vn. Now with vn+1 for every current solution si and element j (j in vn+1), see if j is already in si, if not then add it to your new collection (corresponding to n+1).

*

*Initialize S={ {j} for j in v1 }

*For n=2..m:

*

*newS = {}

*for j in vn

*

*for s in S

*

*if j not in s add sU{j} to newS
S = newS

*return S