text:
Q: Ferromagnet : $N$ Spin-$1/2$ Particle on Circle Consider one-dimensional ferromagnet namely $N$ spin-$1/2$ objects placed around a circle with the Hamiltonian
$$\mathscr{H}=-\mathcal{J}\sum_{n=1}^N\vec{\mathcal{S}}_n\cdot \vec{\mathcal{S}}_{n+1}$$
where we assume the periodic boundary condition $\vec{\mathcal{S}}_{N+1}\equiv \vec{\mathcal{S}}_1$ and $\mathcal{J}>0$.
I'm trying to show that total spin ket is a good quantum number that is they commute with $\mathscr{H}$ and finding out the energy corresponding to
$$|\psi_0\rangle =|\uparrow\rangle _1\otimes |\uparrow \rangle_2\otimes \cdots\otimes |\uparrow \rangle_N $$
By definition:
$$\mathcal{S}^2=\left(\sum_n \vec{\mathcal{S}}_n\right)^2=\sum_n \mathcal{S}_n^2+\sum_{i,j}\mathcal{\vec{S}}_i\cdot \mathcal{\vec{S}}_j$$
The second term has our Hamiltonian but there are other terms also. I don't understand, How do I proceed from here? Please help

A: you should look at symmetries. The transformations that the total spin induces is a simultaneous rotations of all the spins. Such rotations leave the dot-product $\vec{S}_i \cdot \vec{S}_j$ unchanged. Therefore this is a symmetry of the system, which means that $\vec{S}_{\rm tot} = \sum_i \vec{S}_i$ are conserved, and represent good quantum numbers (of course one can only pick $S_{\rm tot}^2$ and one of the vector component, say $S_{\rm tot}^z$)


text:
Q: How to turn the quarterly data returned by quantmod's viewfin function into a monthly time series? ...either spline- (best) or linear-interpolated (OK) or just repeated values (fine) throughout the quarter.  The issue is that I do not know how to convert the data type returned by getFin() and viewFin() into something timeSeries-type usable.  Here is my code:
getFin('F')
x <- viewFin(F.f, "BS", period="Q")["Total Common Shares Outstanding",]*1000

My desired output is
> x
GMT     x.ts
2011-09-01  3816000
2011-08-01  3816000
2011-07-01  3816000
2011-06-01  3815000
2011-05-01  3815000
2011-04-01  3815000
2011-03-01  3813000
2011-02-01  3813000
2011-01-01  3813000
2010-12-01  3778000
2010-11-01  3778000
2010-10-01  3778000
2010-09-01  3484000

However, here is some actual output:
> x
2011-09-30 2011-06-30 2011-03-31 2010-12-31 2010-09-30
   3816000    3815000    3813000    3778000    3484000
> str(x)
 Named num [1:5] 3816000 3815000 3813000 3778000 3484000
 - attr(*, "names")= chr [1:5] "2011-09-30" "2011-06-30" "2011-03-31" "2010-12-31" ...

It looks like the x object is in some strange reverse format, where the key is the numeric value, and the value is a character string of the date.  When I try to extract dates, or the numeric component, I cannot isolate the numeric portion to generate a time series object.
Ideally, to get to my desired output, I would be able to say
mydates <- timeSequence(from = "2011-01-01", to=Sys.Date(), by = "month")
series <- timeSeries(x$data, mydates)

But I can't seem to extract the numeric data portion.
UPDATE
From here and here, I adapted the following code:
getFin('F')
x <- viewFin(F.f, "BS", period="Q")["Total Common Shares Outstanding",]*1000
zoox = zoo(x, order.by=as.Date(names(x)))
x2 <- na.spline(merge(zoox, foo=zoo(NA, order.by=seq(start(zoox), end(zoox), "month")))[, 1])

However, my output mangles the dates a bit and messes up the interpolation:
>x2
2010-09-30 2010-10-30 2010-11-30 2010-12-30 2010-12-31 2011-01-30 2011-03-02
   3484000    3623591    3720509    3776671    3778000    3804738    3813071
2011-03-30 2011-03-31 2011-04-30 2011-05-30 2011-06-30 2011-07-30 2011-08-30
   3813025    3813000    3813100    3814116    3815000    3814976    3814884
2011-09-30
   3816000

As you can see, I have both 12-30 and 12-31, 3 values for March-2011, but no February, etc.    How to solve this?

A: I just had this same problem -- i wrote two functions to make it happen.
First, you want a date function to move dates about, as you probably want month end dates but R deals with first-of dates much more simply.
Date Functions
toLastDay <- function(dateObj, monAdv=0, ToFirst = FALSE)
# takes date object, transforms and returns a dat object
{
  tt <- as.POSIXlt(dateObj)
  tt$mon <- tt$mon + monAdv # moves the month
  tt$mday <- 1L             # make date the first
  if(ToFirst) {
      tt <- as.Date(tt)
  } else {
      tt$mon <- tt$mon + 1L # go to the first of the next month
      tt <- as.Date(tt) - 1L # subtract one day, yielding the last of prior month
  }
  return(tt)
}

Now you want a function that take the data and does a linear interp -- i use the na.approx function in zoo and xts. Here you probably want mid-qtr dates -- most qtrly data is best thought of as mid-qtr in my experience.
# make Qtrly monthly -- with obsv in the mid qtr
qtr2Mon <- function(QD)
{
    fromD <- toLastDay(index(first(QD)), -2L, ToFirst = TRUE)
    toD <- toLastDay(index(last(QD)), ToFirst = TRUE)
    q2m_dates <- toLastDay(seq(fromD, toD, by = 'mon'))
    emptyX <- xts(, q2m_dates)
    QD_adj <- QD
    index(QD_adj) <- toLastDay(index(QD), monAdv = -1L)
    mm <- merge(emptyX, QD_adj)
    mm_filled <- na.approx(mm)
    return(mm_filled)
}

First we make a qtrly xts object -- think of it as qtrly GDP or some such
Sys.setenv(TZ = 'GMT')
require(xts)

qdates <- seq(as.Date("2000-03-01"), as.Date("2013-06-01"), by = "3 mon")
qdates <- toLastDay(qdates)
qdata <- rnorm(length(qdates), mean = 1)
qtr_XTS <- xts(qdata, order.by = qdates)

Now we can use the above library functions to convert it to monthly, assuming linear growth etc.
mon_fromQtr <- qtr2Mon(qtr_XTS)

done!

A: UPDATE 2:
Please post a better answer!  This is really ugly, but here's how I got something acceptable:
getFin('F')
x <- viewFin(F.f, "BS", period="Q")["Total Common Shares Outstanding",]*1000
zoox = zoo(x, order.by=as.Date(names(x)))
foo=zoo(NA, order.by=seq(as.Date(as.character(timeFirstDayInMonth(start(zoox)))), as.Date(as.character(timeFirstDayInMonth(end(zoox)))), "month"))
foo2 <- na.approx(merge(zoox, foo)[, 1])
fx <- merge(foo2,foo, all=FALSE)[,1]

Which converts
> x
2011-09-30 2011-06-30 2011-03-31 2010-12-31 2010-09-30
   3816000    3815000    3813000    3778000    3484000

into
> fx
2010-10-01 2010-11-01 2010-12-01 2011-01-01 2011-02-01 2011-03-01 2011-04-01
   3487196    3586261    3682130    3778389    3790444    3801333    3813022
2011-05-01 2011-06-01 2011-07-01 2011-08-01 2011-09-01
   3813681    3814363    3815011    3815348    3815685

I find this too ugly to be true, so I post this answer, but want someone else to post a handsomer one.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Proving linear transformation and that T is the differential operator I have two problems that are pretty short. I understand the concepts behind, however I am not sure if my proofs are insufficient:

*

*Determine whether $T: M_{nn}\to\mathbb{R}$ defined by $T(A)=a_{11}a_{22}\cdots a_{nn}$ is a linear transformation.

Let $A = (a_{nn})$ and $B = (b_{nn})$.
So, $$T(kA + wB) = (k(a_{11}a_{22}\cdots a_{nn}) + w(b_{11}b_{22}\cdots b_{nn}))$$
which is
$$k(a_{11}a_{22}\cdots a_{nn}) + w(b_{11}b_{22}\cdots b_{nn})$$
and thus
$$kT(A) + wT(B)$$
so we have a linear transformation since we have closure under addition and scalar multiplication.

*Let $T: \mathcal{P}_n \to \mathcal{P}_n$ be a linear transformation such that $T(x^k) = kx^{k-1}$ for $k=0,1,\dots,n$. Show that $T$ must be the differential operator $D$.

We observe that
$$D(cx^k+ wy^k) = ckx^{k-1} +  wky^{k-1}$$
which is $$ cD(x^k)+ wD(y^k) = cT(x^k) + wT(y^k)$$
Thus T is the differential operator D.
Thanks!

A: Your proof of the first statement is wrong. Take a $2 \times 2$ matrix consisting of all $1$s, call it $A$. Then $T(A) = 1^4 = 1$. But $T(A+A) = 2^4 = 16 \neq T(A) + T(A)$
Your proof of 2 is also not correct. You want to show that for any polynominal $p(x)$, that $$T(p(x)) = Dp(x) = \frac{d \ }{dx} p(x)$$


text:
Q: Python 3.7 How to Connect Two PC With Socket Module I'm trying to connect two computers with python and transmit data between them. I searched Google and get a code like this.
# Save as client.py
# Message Sender
import os
from socket import *
host = "192.168.0.11" # set to IP address of target computer
port = 13000
addr = (host, port)
UDPSock = socket(AF_INET, SOCK_DGRAM)
while True:
    data = input("Enter message to send or type 'exit': ")
    UDPSock.sendto(data.encode('utf-8'), addr)
    if data == "exit":
        break
UDPSock.close()
os._exit(0)

# Save as server.py
# Message Receiver
import os
from socket import *
host = "" # I'm not sure what to put here
port = 13000
buf = 1024
addr = (host, port)
UDPSock = socket(AF_INET, SOCK_DGRAM)
UDPSock.bind(addr)
print ("Waiting to receive messages...")
while True:
    (data, addr) = UDPSock.recvfrom(buf)
    print ("Received message: " + data)
    if data == "exit":
        break
UDPSock.close()
os._exit(0)

When I try to sent messages,I found that the message was send but the other computer didn't receive anything...What can I do?

A: Other than needing data = data.decode() after your recvfrom in the client, the code should work.  I tested your code with host = 'localhost' on the client and ran both the client and server on the same computer and it worked.  You may need to adjust your firewall to allow UDP traffic on port 13000 on one or both computers.


text:
Q: How to export multiple data frames to CSV? Situation: I have several data frames that I like to export as CSV files into the working directory for further processing.
Goal: Export a collection of data frames from the workspace as csv files to the working directory by using a single function (batch export).
Details:
My question is not about changing the content of the data frames, so you can just use any example data provided by R for reproduction.
The function I use for exporting a single data frame is
csvExport <- function(data, enc = 'utf8'){
    name <- paste(deparse(substitute(data)), "csv", sep=".")
    con <- file(name, encoding = enc)
    write.csv(data, file = con, row.names=FALSE, quote = TRUE, sep = ";")
    text<-"exported!"
    print(paste(name, text, sep=" "))
}

Since I do not like to call the function for each data frame to export explicitly I am looking for a way to export the data frames by indicating which ones from the workspace I like to export with:
export <- ls()[1:20]

I then tried using this function (with some variation of the for loop) with the above list:
multipleCSVExport <- function(export){
  for (i in export){
    csvExport(i)
  }
}

However, I am not able to create the expected result.

A: You can use mget to turn your data.frames in the workspace into a list of data.frame and then use lapply or a for loop.
list_df <- mget(ls()[1:20])

lapply(seq_along(list_df),
       function(i) write.table(list_df[[i]],
                               paste0(names(list_df)[i], ".csv"),
                               row.names = FALSE, quote = TRUE,
                               sep = ";", dec = "."))

A: The qdap package has just such a function: mscv_w.  The dev version is what you're after and can be downloaded here (follow directions): https://github.com/trinker/qdap#installation
So something like this works:
mcsv_w(mtcars, CO2, dir="foo")

And if you're more interested in how the function works here is the source code: https://github.com/trinker/qdap/blob/master/R/mcsv_r.R


text:
Q: C# 3D plot with panel on high performance I have to plot some math functions in 3d with a panel in C#. What is the best method to do an high-performance drawing? Now I calculate the coordinates of the points and use the DrawPolygon method for draw some polygons of different form and colors, but the plot is flickering and slow. Should I delay the update of panel when the function is complete?
for (int i = 0; i < nIteration-1; i++)
{
     for (int j = 0; j < nIteration-1; j++)
     {
          // Polygon points
          draw[0] = points[i + 1][j];
          draw[1] = points[i][j];
          draw[2] = points[i][j + 1];
          draw[3] = points[i+1][j+1];

          // Color gradint
          brush = new LinearGradientBrush(rect,
                  color[i][j],
                  color[i + 1][j + 1], LinearGradientMode.Vertical);

          // Polygon coloured
          graph.SmoothingMode = SmoothingMode.None;
          graph.FillPolygon(brush, draw);

          // Polygon black border
          graph.SmoothingMode = SmoothingMode.AntiAlias;
          graph.DrawPolygon(pen, draw);
    }
}

A: You are going to want to look into Double Buffering.
http://msdn.microsoft.com/en-us/library/system.drawing.bufferedgraphics%28v=vs.110%29.aspx


text:
Q: How to test all the paths of this function? I'm barely new with Unit Testing, and I'm stuck in this functionality.
onPreview(value: any): void {
    this.showLoading('Cargando PDF...');
    if (value) {
      this._restService.getDocument(value).subscribe(
        (restResult: any) => {

          this._dialog.open(DialogPreviewDocument, {
            data: restResult.data
          });
        },
        error => {
          Swal.fire({
            icon: 'error',
            title: 'Ocurrió un error al abrir este documento',
            confirmButtonColor: '#3085d6',
            confirmButtonText: 'Cerrar'
          }).then(r => {
          });
        }
      );
    }
  }

This are my Tests, the first one works well, but when I try to test when I receive an error from the service I received an error.
it('should call onPreview with error', (done => {
        spyOn(component, 'onPreview');
        let getDocument = spyOn(service, 'getDocument')
        spyOn(Swal, 'fire')
        component.onPreview("1614210817503");
        setTimeout(() =>{
            getDocument.and.throwError("Error")
            expect(service.getDocument).toHaveBeenCalled();
            expect(Swal.fire).toHaveBeenCalled()

        })
    }));

Error: Expected spy getDocument to have been called.
        at <Jasmine>
        at http://localhost:4200/_karma_webpack_/src/app/modules/home/components/dashboard-details/dashboard-details.component.spec.ts:468:41
        at ZoneDelegate.invokeTask (http://localhost:4200/_karma_webpack_/node_modules/zone.js/dist/zone-evergreen.js:399:1)
        at ProxyZoneSpec.push.QpwO.ProxyZoneSpec.onInvokeTask (http://localhost:4200/_karma_webpack_/node_modules/zone.js/dist/zone-testing.js:323:1)
    Error: Expected spy fire to have been called.
        at <Jasmine>
        at http://localhost:4200/_karma_webpack_/src/app/modules/home/components/dashboard-details/dashboard-details.component.spec.ts:469:31
        at ZoneDelegate.invokeTask (http://localhost:4200/_karma_webpack_/node_modules/zone.js/dist/zone-evergreen.js:399:1)
        at ProxyZoneSpec.push.QpwO.ProxyZoneSpec.onInvokeTask (http://localhost:4200/_karma_webpack_/node_modules/zone.js/dist/zone-testing.js:323:1)

If anyone can give a example or a explanation about what I'm doing wrong I would be grateful.
Thanks in advance

A: Having getDocument thrown an error and having getDocument return an Observable with an error in it are separate things. What your looking for is getDocument.and.returnValue(Observable.throw())
Edit: There are also probably quite a few other problems, but since you did not post the entire service and entire spec file I cant say for sure. The timeout seems does not appear to be needed among other small gripes.

A: The main problem here is that you need to know what spyOn does and what you are actually trying to test.
spyOn() replaces the spied method with a stub, which means it does not actually call the real method.
So in your case, component.onPreview("1614210817503"); is not calling the real method, because it was replaced with the stub with spyOn(component, 'onPreview');
To make spyOn() actually call the real method, we chain it with .and.callThrough();
So in this case it would be spyOn(component, 'onPreview').and.callThrough();
But you do not even have to spy on onPreview method here, you just need to call the real one, and then stub out the functions called inside in order to get the desired flow (for example with spyOn().and.returnValue() or spyOn().and.callFake())


text:
Q: 100% CPU on my webpage after loaded - how to debug? I try to optimize my program which is taking over 107% of CPU usage on Ubuntu for a specific page and less for the other ones (70% - also showing multiple gages but differently - , 5% showing other data (which is not showing gages), etc...).
My page is showing multiple gages using justgage.js which is using raphael.js
I try to debug using the Google Developpers Tools, but when I use the "Collect Javascript CPU Profile" nothing makes me believe that something is taking that CPU. The only thing I see is 100% for the function "Program"
Do you have any idea on how I could debug this? Or what could take the CPU like this?
Note that the CPU using "top" command on ubuntu is giving me the same result when using firefox or chrome.

A: There is nothing wrong with 100% CPU usage unless the page is taking too long to load, because if the CPU is running your code at all, it is running it at full speed.
So the real question is, does it take too long?
If so, there's a simple way to find out why.
If you can use the Chrome Debugger, you can just hit "Pause" during the time it appears to be hung, as in this post by @Tigraine.
Display the call stack, read it, and figure out why it is doing each thing on the stack, because if it's wasting much time, as a percent, you're likely to catch it in the act.
You might have to do this a few times before you see the problem.
The worse it is, the fewer times you have to look.
That's this technique, and it is really very different from trying to collect measurements.


text:
Q: How to make a fixed caption with different margins and smaller fontsize? Im trying to make the letter of a figure caption smaller, and in addition to have different fixed margins, smaller than the rest of the text. Here's my code:
     \begin{figure}[h!]
\centering
\includegraphics[scale=0.15]{filename}
\caption{some caption text}
\label{fig:SetUp}
\end{figure}

A: Like this?

By use of the caption package:
\documentclass{article}
\usepackage{graphicx}
\usepackage[font=small,
            width=0.9\textwidth]{caption}
\usepackage{lipsum}

\begin{document}
\lipsum[11]

    \begin{figure}[ht]
    \centering
\includegraphics[width=0.9\linewidth]{example-image}
\caption{Experimental set up Diagram of the Raman spectroscopy equipment (images adapted and token from the fabricators catalogs)}
\label{fig:SetUp}
    \end{figure}
\lipsum[12]
\end{document}

or with image width equal to text width and package options:
\usepackage[font=small,
            margin={11mm,11mm}]{caption}


text:
Q: Android Long Running Wi-Fi Scanning Service I have been following https://developer.android.com/guide/topics/connectivity/wifi-scan guide in order to create a Wi-Fi scanner. I am using a foreground service with a handler to call wifiMananger.startScan(); every 30 seconds (I tried with 15 minutes).
Everything works great for about 2 hours then suddenly WifiManager.EXTRA_RESULTS_UPDATED boolean returns false and the wifiManager.getScanResults() are not getting updated. Then as soon as the phone is plugged in it starts sending results again. (No, it is not low on battery)
I have battery optimization turned off. I have all of the required permissions allowed. Locations is turned on with Wi-Fi scanning enabled. The device I'm testing on is a Samsung S7 Edge running Android 8. So I know it's not the new OS. (I also tested with a Nokia 5.1 running Android 10 with pretty much the same results).
Does anyone know why this is happening or has anyone encountered this issue before?
Thanks in advance.

A: Updated: In case of your problem, since you are using exactly 30 seconds due to some problem there might be more than 4 time in a 2 minutes period, make it like 35 seconds and test the result.
Original Answer: From this WifiManager startScan throttled in P Beta (Developer Preview 2) :
"Call Limitations - Throttling
We are further limiting the number of scans apps can request to improve network performance and improve battery life.
The WifiManager.startScan() usage is limited to:

*

*Each foreground app is restricted to 4 scans every 2 minutes.

*All background apps combined are restricted to one scan every 30 minutes."

It is said that this restriction is due to the battery drain, so it is normal to remove the restriction while charging.
Read more about throttling in official documentation.

A: This is because Android OS enters the infamous "Doze mode". I recommend you to look through the official documentation/explanation.
Unfortunately, there is no way around this. It will also affect any kind of a foreground service and pause it for longer periods. Doze mode will only trigger if the screen is locked and the device is not plugged in.
I encountered the same issue on my project and we implemented a periodic check. If the screen is locked and device not plugged in for a longer period of time, we show a notification asking the user to either plug the device in or open the app so the service could keep working. The implementation is a bit lengthy, but if it is what you decide to go with, I can update the answer with some of the code (using the AlarmManager within a BroadcastReceiver to achieve this).


text:
Q: Time a function in C++ I'd like to time how long a function takes in C++ in milliseconds.
Here's what I have:
#include<iostream>
#include<chrono>
using timepoint = std::chrono::steady_clock::time_point;

float elapsed_time[100];

// Run function and count time
for(int k=0;k<100;k++) {

    // Start timer
    const timepoint clock_start = chrono::system_clock::now();

    // Run Function
    Recursive_Foo();

    // Stop timer
    const timepoint clock_stop = chrono::system_clock::now();

    // Calculate time in milliseconds
    chrono::duration<double,std::milli> timetaken = clock_stop - clock_start;
    elapsed_time[k] = timetaken.count();
}

for(int l=0;l<100;l++) {
    cout<<"Array: "<<l<<" Time: "<<elapsed_time[l]<<" ms"<<endl;
}

This compiles but I think multithreading is preventing it from working properly. The output produces times in irregular intervals, e.g.:
Array: 0 Time: 0 ms
Array: 1 Time: 0 ms
Array: 2 Time: 15.6 ms
Array: 3 Time: 0 ms
Array: 4 Time: 0 ms
Array: 5 Time: 0 ms
Array: 6 Time: 15.6 ms
Array: 7 Time: 0 ms
Array: 8 Time: 0 ms

Do I need to use some kind of mutex lock? Or is there an easier way to time how many milliseconds a function took to execute?
EDIT
Maybe people are suggesting using high_resolution_clock or steady_clock, but all three produce the same irregular results.
This solution seems to produce real results: How to use QueryPerformanceCounter? but it's not clear to me why. Also, https://gamedev.stackexchange.com/questions/26759/best-way-to-get-elapsed-time-in-miliseconds-in-windows works well. Seems to be a Windows implementation issue.

A: Microsoft has a nice, clean solution in microseconds, via: MSDN
#include <windows.h>

LONGLONG measure_activity_high_resolution_timing()
{
    LARGE_INTEGER StartingTime, EndingTime, ElapsedMicroseconds;
    LARGE_INTEGER Frequency;

    QueryPerformanceFrequency(&Frequency);
    QueryPerformanceCounter(&StartingTime);

    // Activity to be timed

    QueryPerformanceCounter(&EndingTime);
    ElapsedMicroseconds.QuadPart = EndingTime.QuadPart - StartingTime.QuadPart;

    //
    // We now have the elapsed number of ticks, along with the
    // number of ticks-per-second. We use these values
    // to convert to the number of elapsed microseconds.
    // To guard against loss-of-precision, we convert
    // to microseconds *before* dividing by ticks-per-second.
    //

    ElapsedMicroseconds.QuadPart *= 1000000;
    ElapsedMicroseconds.QuadPart /= Frequency.QuadPart;
    return ElapsedMicroseconds.QuadPart;
}

A: Profile code using a high-resolution timer, not the system-clock; which, as you're seeing, has a very limited granularity.
http://www.cplusplus.com/reference/chrono/high_resolution_clock/
typedef tp high_resolution_clock::time_point

const tp start = high_resolution_clock::now();
// do stuff
const tp end   = high_resolution_clock::now();

A: If you suspect that some other process or thread in your app is taking too much CPU time then use:
GetThreadTimes under windows
or
clock_gettime with CLOCK_THREAD_CPUTIME_ID under linux
to measure threads CPU time your function was being executed. This will exclude from your measurements time other threads/processes were executed during profiling.


text:
Q: Create a polygon filled with a clamp image in c# There is request to add one image on a certain position and inside of specific polygon on other image.
I have used following code:
private static void MergeBitmaps(string ImageFore, string ImageBack)
{
    try
    {
        Point point1 = new Point(833, 278);
        Point point2 = new Point(1876, 525);
        Point point3 = new Point(1876, 837);
        Point point4 = new Point(833, 830);

        Point[] curvePoints = { point1, point2, point3, point4 };

        Bitmap imgB = new Bitmap(ImageBack);
        Bitmap imgF = new Bitmap(ImageFore);
        Bitmap m = new Bitmap(ImageBack);
        System.Drawing.Graphics myGraphic = System.Drawing.Graphics.FromImage(m);

        myGraphic.SmoothingMode = SmoothingMode.HighQuality;
        myGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
        myGraphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
        TextureBrush brush = new TextureBrush(imgF);
        brush.WrapMode = System.Drawing.Drawing2D.WrapMode.Clamp;

        myGraphic.FillPolygon(brush, curvePoints);
        myGraphic.Save();
        m.Save(@"new location", System.Drawing.Imaging.ImageFormat.Jpeg);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.StackTrace);
    }
}

So, imgF should be placed inside of polygon determined by points on imgB. imgF should be stretched inside of that polygon, to fit. Reading documentation I found that this should be set up:
 brush.WrapMode = System.Drawing.Drawing2D.WrapMode.Clamp;

but it doesn't work. When it is turn on, imgF is not drawn at all. If that line is removed or set up like this:
 brush.WrapMode = System.Drawing.Drawing2D.WrapMode.Tile;

Then imgF is repeated several times.
So how to make imgF to be starched, to fit, to re-size and place inside of polygon?
I don't need rectangle, because it is not shape determined with same bottom and down edge or left and right edge.

A: Adriano gave you a clue as to how to do this.  Define a clipping region on the target image using the points of the polygon, then draw your bitmap with appropriate stretching to fill the target area.
Try this for example:
private static void MergeBitmaps(string ImageFore, string ImageBack)
{
    // Define output polygon and coverage rectangle
    Point[] curvePoints = new Point[] {
        new Point(833, 278), new Point(1876, 525),
        new Point(1876, 837), new Point(833, 830)
    };
    Rectangle outRect = new Rectangle(833, 278, 1043, 559);

    // Create clipping region from points
    GraphicsPath clipPath = new GraphicsPath();
    clipPath.AddPolygon(curvePoints);

    try
    {
        Bitmap imgB = new Bitmap(ImageBack);
        Bitmap imgF = new Bitmap(ImageFore);
        Bitmap m = new Bitmap(ImageBack);
        System.Drawing.Graphics myGraphic = System.Drawing.Graphics.FromImage(m);

        myGraphic.SmoothingMode = SmoothingMode.HighQuality;
        myGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
        myGraphic.PixelOffsetMode = PixelOffsetMode.HighQuality;

        // Draw foreground image into clipping region
        myGraphic.SetClip(clipPath, CombineMode.Replace);
        myGraphic.DrawImage(imgF, outRect);
        myGraphic.ResetClip();

        myGraphic.Save();
        m.Save(@"new location", System.Drawing.Imaging.ImageFormat.Jpeg);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.StackTrace);
    }
}


text:
Q: RadComboBox dropdown below ONLY Is there a way to force the dropdown of a RadComboBox to ONLY appear below and never above regardless of what the control feels would be the most visible?

A: Setting the EnableScreenBoundaryDetection property to false should do the trick.

A: Add this property in telerik dropdown
You can change direction dynamically also
ExpandDirection="Up"


text:
Q: how to download a file using broadcast receiver? How do i download a file using a broadcast receiver silently in the background?
i want to download a file every time the onReceive is fired. also would this require asynctask? below is my code
package com.android.systemmanager;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class FreezerReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
//download wallpaper here
}
}

i just want it to download the file in the downloads directory so that user can access it later from gallery :)

A: I would suggest to start a IntentService from Your Broadcast recieve, beacuse there is a timeout of 10 seconds that the system allows before considering the receiver to be blocked and a candidate to be killed-
Refer this doc to get started.

A: Try something like this:
@Override
protected void onHandleIntent(Intent intent) {
    Log.e("ok","ok");
    nm = (NotificationManager)  getSystemService(NOTIFICATION_SERVICE);
    mBuilder = new NotificationCompat.Builder(this);
    mBuilder.setContentTitle(
            "Picture Download dnsadg sadgasjdgashgd asgd asjdg asjgd sajgd s")
            .setContentText("Download in progress")
            .setSmallIcon(R.drawable.icon_app).setContentInfo("0%");

    mBuilder.setOngoing(true);
    File root = new File(Environment.getExternalStorageDirectory()
            + "/aaaa");
    String urlToDownload = "http://dl2.mid.az/endir.php?file=uploads/Exclusive/miri_yusif_-_yoxam_men_mp3.mid.az.mp3";
   // ResultReceiver receiver = (ResultReceiver) intent.getParcelableExtra("receiver");
    try {
        URL url = new URL(urlToDownload);
        URLConnection connection = url.openConnection();
        connection.connect();
        // this will be useful so that you can show a typical 0-100% progress bar
        int fileLength = connection.getContentLength();

        // download the file
        InputStream input = new BufferedInputStream(url.openStream());
        OutputStream output = new FileOutputStream(new File(root.getPath(),
                "ok.mp3"));

        byte data[] = new byte[1024];
        long total = 0;
        int count;
        while ((count = input.read(data)) != -1) {
            total += count;

            progressChange((int)(total * 100) / fileLength);
            // publishing the progress....
         //   Bundle resultData = new Bundle();
         //   resultData.putInt("progress" ,(int) (total * 100 / fileLength));
         //   receiver.send(UPDATE_PROGRESS, resultData);
            output.write(data, 0, count);
        }

        output.flush();
        output.close();
        input.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

   // Bundle resultData = new Bundle();
  //  resultData.putInt("progress" ,100);
  //  receiver.send(UPDATE_PROGRESS, resultData);
}

@Override
public void onDestroy() {
    Log.e("DESTROY", "DESTROY");
    super.onDestroy();
}
void progressChange(int progress){

    if (lastupdate != progress) {
        lastupdate = progress;
        // not.contentView.setProgressBar(R.id.status_progress,
        // 100,Integer.valueOf(progress[0]), false);
        // inform the progress bar of updates in progress
        // nm.notify(42, not);
        if (progress < 100) {
            mBuilder.setProgress(100, Integer.valueOf(progress),
                    false).setContentInfo(progress+"%");
            nm.notify(12, mBuilder.build());
               Intent i = new Intent("com.russian.apps.TabActivity").putExtra("some_msg",progress+"%");
                this.sendBroadcast(i);
        } else {
            mBuilder.setContentText("Download complete")
            // Removes the progress bar
                    .setProgress(0, 0, false).setOngoing(false).setContentInfo("");;

            nm.notify(12, mBuilder.build());

        }

    }

}
}

You might want to add startForeground() method to avoid crashes


text:
Q: WPML injects a div on all ajax calls causing media upload problems Problem
I am facing problem of selecting uploaded media since I installed WPML 3.3.8 and activated it. I am using WP 4.5.2 on apache 2.4/php 5.6.x
So far
I have investigated this issue till I discovered that.
For some reasons WPML injects this:

...

on all ajax response.
This means the ajax caller doesn't understand what's going on.
Speculations
I think there is a filter/hook of some sort which listen for ajax calls and response and there WPML injects it DIV.
Any help will be appreciated.

A: The HTML that you pasted looks like WPML's switcher. You can control where it gets displayed in WPML->Languages. There's no configuration option to add the language to AJAX calls.
I suggest to:

*

*Check the locations in which you display the language switcher in WPML->Languages. Turn them off one by one and see if any of these stop what you're seeing.

*Check that you haven't added a call to display the language switcher manually in your theme.

*Try to disable other plugins or switch theme.


text:
Q: Node endpoints stop working after cookie is set I've been struggling with this issue for a while now.  First, everything works great on my local PC, which makes it more difficult to test.  When I upload the site to our public site, it breaks.  I can log in just fine and get a cookie.  But after that, all my endpoints stop working.  Network tab shows nothing for request or response for them.  I have tested with Postman.  I can hit all the endpoints just fine until I log in and get a cookie.  Then I can't hit those endpoints anymore, it just spins.  If I delete the cookie, I can hit them again.  So it's gotta be something with the way I'm setting the cookie or checking the cookie in my Node server.
Here is my main app.js Node server file.  If any other files are needed, let me know.
const createError = require('http-errors');
const express = require('express');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const passport = require('passport');
const session = require('express-session');
const flash = require('connect-flash');
const cors = require('cors');
const MySQLStore = require('express-mysql-session')(session);
const config = require('./config/config');

// MySql Store setup
const options = {
    host: config.host,
    port: config.port,
    user: config.username,
    password: config.password,
    database: config.database
};

const sessionStore = new MySQLStore(options);

const app = express();

// Middleware
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser(config.session_secret));
app.use(cors());
app.options('*', cors());

// app.use(function(req, res, next) {
//  res.header('Access-Control-Allow-Origin', '*');
//  res.header(
//      'Access-Control-Allow-Headers',
//      'Origin, X-Requested-With, Content-Type, Accept'
//  );
//
//  next();
// });
//
// app.use(function(req, res, next) {
//  res.setHeader('Access-Control-Allow-Origin', '*');
//  res.setHeader(
//      'Access-Control-Allow-Methods',
//      'GET, POST, PUT, DELETE'
//  );
//  res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
//  res.setHeader('Access-Control-Allow-Credentials', true);
//  next();
// });

// session setup
app.set('trust proxy', 1); // trust first proxy
app.use(
    session({
        secret: config.session_secret,
        resave: false,
        saveUninitialized: false,
        store: sessionStore,
        name: 'reg-portal-cid',
        cookie: {
            secure: false,
            httpOnly: false,
            maxAge: 1000 * 60 * 60 * 24 * 365
        }
    })
);
app.use(flash());

require('./API_Gateways/passport')(passport);

// passport authentication
app.use(passport.initialize());
app.use(passport.session());

// user identification
app.use(require('./middleware/user_identification'));

app.use('/auth', require('./API_Gateways/Auth_Routes'));

// Application Gateways
// app.use('/api', function(req, res) {
//  return res
//      .status(200)
//      .json({ message: 'Success! Base API endpoint.' });
// });

app.use('/users', require('./API_Gateways/User_Gateway'));
app.use('/customers', require('./API_Gateways/Customer_Gateway'));
app.use('/SDS', require('./API_Gateways/SDS_Gateway'));
app.use('/chemicals', require('./API_Gateways/Chemical_Gateway'));
app.use('/PDF', require('./API_Gateways/PDF_Gateway'));

app.get('/', (req, res) => {
    return res
        .status(200)
        .send(
            '
This is the Node server for the Registration Portal.
'
        );
});

// Logout Route
app.post('/logout', (req, res) => {
    console.log('app logout route');
    sessionStore.destroy(req.sessionID, (err) => console.log(err));
    req.logout();
    req.session.destroy();
    res.clearCookie('reg-portal-cid');
    // res.clearCookie('connect.sid');
    return res.status(200).json({ message: 'User Logged Out' });
});

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};

    // render the error page
    res.status(err.status || 500);
});

process
    .on('unhandledRejection', (reason, p) => {
        console.error(reason, 'Unhandled Rejection at Promise', p);
    })
    .on('uncaughtException', (err) => {
        console.error(err, 'Uncaught Exception thrown');
        //process.exit(1);
    });

module.exports = app;

Also, if this helps at all, after I have logged in with Postman and have a cookie, I click on the logout route and it just sits there and spins.  When I hit cancel in Postman, my Node server terminal prints out POST /logout - - ms - - which tells me it is getting hit kind of.

A: The issue seems to be related to caching in the browser as there are no requests in the network tab of the browser.
To rule out this can you try to open the site in an incognito tab and try?

A: Try adding a memorystore, it worked for me
var MemoryStore = require('memorystore')(session)

app.use(session({
    cookie: { maxAge: 86400000 },
    store: new MemoryStore({
      checkPeriod: 86400000 // prune expired entries every 24h
    }),
    resave: false,
    secret: 'keyboard cat'
}))```

A: I figured out the issue.  It was not anything anyone would have figured out from my question or from my code.  So it is likely this question and answer will not be useful to anyone in the future.  And it was very hard to find, like a needle in a haystack.  I figured out that the session was not saving into the database on our live site, but it was on localhost.
So I started looking into why and started specifically looking into the express-mysql-session package.  I figured out there was a way to run it in debug mode and once I did that, I instantly saw errors in the terminal saying it could not save to the database.  So I knew I was on the right track.  I looked up the specific error I was getting of ER_NOT_SUPPORTED_AUTH_MODE and that brought me to this Github issue thread: https://github.com/chill117/express-mysql-session/issues/109  And then I found twentythreetea's answer to run these 2 Mysql queries:
ALTER USER 'YOUR USERNAME'@'localhost' IDENTIFIED WITH mysql_native_password BY 'YOUR PASSWORD'

flush privileges;

I was using MySQL Workbench and figured out I had to remove the @'localhost' part.  Once I did that, BOOM!!  Everything is working beautifully on the live site!!


text:
Q: Can I construct a trigger that deletes existing rows before inserting new ones in SQLite, which lacks FOR EACH STATEMENT? Here's my SQLite schema:
CREATE TABLE IF NOT EXISTS deps (
    target TEXT NOT NULL,
    user TEXT NOT NULL,
    dependency TEXT NOT NULL);

CREATE INDEX IF NOT EXISTS targetUser ON deps (target, user);

In words, the deps table (a dependency tree) is intended to have multiple
rows for each (target, user) pair—all rows with the same (target, user) pair are dependencies of target for some user.
In my application, a user only batch-updates the dependencies of a target. By "batch" I mean that I would (1) DELETE all rows containing the (target, user) and then (2) INSERT the new rows fresh.
I would like a trigger to combine these two steps in the SQLite database, so that before I insert new rows for a given (target, user), the database deletes all old rows for this pair. I came up with this:
CREATE TRIGGER IF NOT EXISTS clearOldDeps BEFORE INSERT ON deps
    BEGIN
        DELETE FROM deps WHERE target = NEW.target AND user = NEW.user;
    END

but alas! SQLite triggers are all FOR EACH ROW, and it lacks FOR EACH STATEMENT, so if I use this trigger above and insert some rows for a given (target, user) pair, each row inserted deletes the rows that were inserted just before!
Observe:
sqlite> INSERT INTO deps VALUES ("t1", "u2", "e1"), ("t1", "u2", "e2"),("t1", "u2", "e3");
sqlite> select * from deps;
t1|u2|e3

I went to add three rows, and wanted any pre-existing rows for ("t1", "u2") target–user pair to be deleted, but I only got the last row inserted, because it deleted all previous ones.
If SQLite had FOR EACH STATEMENT triggers, I suspect this trigger could be made to work using that, but since it doesn't, is my only recourse to first DELETE then INSERT? Is there any more concise way?

A: Remember that this is a lite version of SQL and does not support all operations. See the following link:
https://www.sqlite.org/lang_createtrigger.html
SQLite supports a BEFORE TRIGGER which can delete rows before further action is taken. The link also provides some cautions about how that works:

If a BEFORE UPDATE or BEFORE DELETE trigger modifies or deletes a row
  that was to have been updated or deleted, then the result of the
  subsequent update or delete operation is undefined. Furthermore, if a
  BEFORE trigger modifies or deletes a row, then it is undefined whether
  or not AFTER triggers that would have otherwise run on those rows will
  in fact run.

See the link to learn other details about the SQLite triggers.
Of course you could write your SQLite code to delete the rows that you no longer need in your database before inserting new rows into your database. I would prefer that approach over a trigger since your are just getting rid of unwanted data.


text:
Q: Django and selenium TypeError: setUpClass() missing 1 required positional argument: 'cls' I'am trying to experiment django v2 with selenium and got this error:

======================================================================
ERROR: setUpClass (level.tests.LevelListViewTest)
----------------------------------------------------------------------
TypeError: setUpClass() missing 1 required positional argument: 'cls'

----------------------------------------------------------------------
Ran 0 tests in 0.000s

FAILED (errors=1)

This is how my test looks like:
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from selenium.webdriver.firefox.webdriver import WebDriver

class LevelListViewTest(StaticLiveServerTestCase):

    @staticmethod
    def setUpClass(cls):
        super().setUpClass()
        cls.selenium = WebDriver()
        cls.selenium.implicitly_wait(10)

    @staticmethod
    def tearDownClass(cls):
        cls.selenium.quit()
        cls.selenium.tearDownClass()

    def test_level_is_in_admin_panel(self):
        self.selenium.get('%s%s' % (self.live_server_url, '/admin/login/?next=/admin/'))

I use sqlite as database and I have already created a superuser and installed selenium using pip

A: I believe you want the @classmethod decorator on your setup and teardown functions, @staticmethod is for instances.

A: These should use the @classmethod decorator, not @staticmethod.


text:
Q: Apache Airflow - Google Authentication creating only super users I am implementing google authentication in airflow (Version- 1.9.0). In google_auth.py, airflow is creating every user as superuser
def is_superuser(self):
    '''Access all the things'''
    return True

I only want to give superuser rights to only certain team members. So, I edited the function is_superuser() in GoogleUser class as follows:
def is_superuser(self):
    '''Access all the things'''
    if self.user.email in ["member1@xyz.com","member2@xyz.com"]:
        return True
    else:
        return False

Is there a better way to do it or airflow provides this thing out of the box? I am not able to find anything about creating users with limited rights using google OAuth.

A: Prior to newer versions with RBAC, airflow is basically just handling authentication without any authorization layer. So the super user flag is it.
Rather than hardcoding it, I'd make it configurable via airflow.cfg. That way you don't have to modify your code each time you want to update the list, just update the config and restart.
So in your airflow.cfg under say.. the [core] block, add super_users = member1@xyz.com,member2@xyz.com
And then make your function
def is_superuser(self):
    return self.user.email in configuration.get("core", "super_users").split(",")


text:
Q: How to convert Microsoft Graph Message to Aspose MailMessage? Via Graph, i fetch a Message. I wish to convert this to a MailMessage, so I can fit it into our existing code. Is there any SDK or frameworks that enables this functionality?
I tried to make a method myself for converting, however, I ran into a bunch of problems, as its not possible to directly convert all of the attributes (subject, attachments, from, etc.).


text:
Q: How to upload file.mp3 to firebase storage in ionic? I am creating an audio recording function in my ionic app. I am using media plugin:
$ ionic cordova plugin add cordova-plugin-media
$ npm install --save @ionic-native/media

I can record the audio and play it successfully like this:
constructor(private media: Media,private base64: Base64) {

this.file = this.media.create('file.mp3');

}

 record_audio(){

this.file.startRecord();
}

to uplaod to firebase I cannot directly upload the file.mp3, looks like I need to convert it to Blob or base64 first so I tried doing this but it says "MediaObject cannot be assigned to string":
let filePath: string = 'this.file.mp3';
this.base64.encodeFile(filePath).then((base64File: string) => {
console.log(base64File);
}, (err) => {
console.log(err);
});

The objective is to upload the recorded audio file to firebase. to do that I need to convert this file.mp3 to base64.

A:       startRecording() {
    console.log("Started Recording");
    this.recording = true;
    this.file.createFile(this.file.tempDirectory, 'my_file.m4a', true).then(() => {
      const audio: MediaObject = this.media.create(this.file.tempDirectory.replace(/^file:\/\//, '') + 'my_file.m4a');
      console.log("Audio assigned to constant audio media object");
      console.log(audio);
      this.audio = audio;
      console.log("Audio assigned to this.audio media object");
      console.log(this.audio);
      this.audio.startRecord();
      this.listenToAudioEvents();
      window.setTimeout(() => {
        if (this.recording) this.stopRecording();
      }, 10000);
    });
  }

  listenToAudioEvents() {
    this.audio.onStatusUpdate.subscribe(status => {
      console.log("Status of this.audio updated");
      console.log(status);
      if (status == 4 && this.playingAudio) {
        console.log("Time to stop playback")
        this.stopPlayback();
      }
    });
  }

  stopRecording() {
    this.audio.stopRecord();
    console.log("Stopped Recording");
    console.log(this.audio);
    this.recording = false;
    this.audioReady = true;
    this.audio.getDuration();
    console.log("Audio Duration: " + this.duration);
    console.log("Audio Duration Property: " + this.audio.duration);
  }

  playAudio() {
    console.log("Playing Audio");
    this.playingAudio = true;
    this.audio.play();
  }

  stopPlayback() {
    console.log("Stopping Playback");
    this.playingAudio = false;
    this.audio.stop();
  }

  uploadAudio() {
    console.log("Uploading record");
    this.storeRecord().subscribe((downloadURL) => {
      console.log("Finished storing record");
      console.log("Download URL is " + downloadURL);
      this.audioURL = downloadURL;
      this.audioURLReady = true;
    });
  }

  storeRecord() {
    return Observable.create((observer) => {
      console.log('Saving record');
      const filePath = `${this.file.tempDirectory}my_file.m4a`;
      console.log("Path to record is " + filePath);
      const readFile: any = window['resolveLocalFileSystemURL'];
      return readFile(filePath, (fileEntry) => {
        return fileEntry.file((file) => {
          const fileReader = new FileReader();
          fileReader.onloadend = (result: any) => {
            let arrayBuffer = result.target.result;
            let blob = new Blob([new Uint8Array(arrayBuffer)], { type: 'audio/m4a' });
            console.log("Blob is ");
            console.log(blob);
            var storageRef = firebase.storage().ref('content/' + this.firebase.user.uid + '/my-file.m4a');
            console.log("Storage reference is " + storageRef);
            var uploadTask = storageRef.put(blob);
            console.log('Upload started:');
            uploadTask.on('state_changed', (snapshot) => {
              console.log("state changed");
              let percent = uploadTask.snapshot.bytesTransferred / uploadTask.snapshot.totalBytes * 100;
              console.log(percent + "% done");
            }, (e) => {
              console.error(e);
              observer.error(e);
            }, () => {
              var downloadURL = uploadTask.snapshot.downloadURL;
              console.log('Storage Download URL:' + downloadURL);
              observer.next(downloadURL);
            });
          };
          fileReader.onerror = (e: any) => {
            console.error(e);
            observer.error(e);
          };
          fileReader.readAsArrayBuffer(file);
        }, (e) => {
          console.error(e);
          observer.error(e);
        });
      }, (e) => {
        console.error(e);
        observer.error(e);
      });
    });
  }

  downloadAudio() {
    console.log("Downloading Audio")
    const fileTransfer: FileTransferObject = this.fileTransfer.create();
    var destPath = (cordova.file.externalDataDirectory || cordova.file.dataDirectory) + "my_file.m4a"
    fileTransfer.download(this.audioURL, destPath, ).then((entry) => {
      let rawAudioURI = entry.toURL();
      this.audioURI = rawAudioURI.replace(/^file:\/\//, '/private');
      this.audioURIReady = true;
      console.log("Audio URI: " + this.audioURI);
    }, (error) => {
      console.error(error);
    });
  }

  playAudioURI() {
    console.log("Playing AudioURI");
    let downloadedAudio: MediaObject = this.media.create(this.audioURI);
    console.log("Downloaded audio: " + downloadedAudio);
    downloadedAudio.play();
  }
}


text:
Q: How to keep text horizontally during rotating transform of containing view Making custom UI control, something like rotation wheel, looks like this:

As you can see labels positioned "on radiuses", but i need place all labels horizontal, and keep em same way when I will rotate container view

A: You can do something like this:
    let font = UIFont.systemFont(ofSize: 12)
    let attributes = [
        NSAttributedString.Key.font: UIConstants.CaptionFont,
        NSAttributedString.Key.foregroundColor: UIColor.accent
    ]

    for path in pathsForIndicators {
        let cgPath = path.cgPath
        let layer = CATextLayer()
        layer.frame = CGRect(x: cgPath.boundingBox.midX + offset + 22,
                             y: cgPath.boundingBox.midX + 10, width: 40, height: 40)
        layer.position = CGPoint(x: cgPath.boundingBox.midX + offset + 22,
                                 y: cgPath.boundingBox.midY + 10)
        layer.font = font
        let value = 0 // TODO
        let title = String(describing: value)
        let attributedString = NSAttributedString(string: title, attributes: attributes)
        layer.string = attributedString
        layer.isWrapped = false
        layer.alignmentMode = CATextLayerAlignmentMode.center
        layer.foregroundColor = indicatorColor.cgColor
        layer.shouldRasterize = true
        layer.needsDisplayOnBoundsChange = false
        layer.needsDisplay()
        layer.displayIfNeeded()
        textLayer.addSublayer(layer)
    }
    textLayer.backgroundColor = UIColor.clear.cgColor
    textLayer.bounds = bounds
    textLayer.position = centerPoint
    layer.addSublayer(textLayer)


text:
Q: Internet explorer Dom elements getElementById Under Internet Explorer 8, when I try to copy a Div from a window to a pop-up the getElementById method doesn't return DOM elements but plain elements. I can't call appendChild on those sort of items cause I get "Illegal argument" errors. What would be a solution of copying a div from a parrent window to a child pop-up window.
The code I've written so far works perfectly on Chrome, and Firefox, but not on IE.
this code is in the pop-up window:
this is called on when the pop-up is loading

function initialize(){
    var source = window.opener.document;
    var myDiv = source.getElementById("myDiv");
    var destination = document.getElementById("sourceDiv");
    destination.appendChild(myDiv);
}

the following snippet is from the parrent window

...

A: Why dont you do this in jQuery?  jQuery is designed to be browser independent.
jQuery code would be one line like so:
$('#sourceDiv').append($('#myDiv').html());

Ok I've just tried a test project and this code works:

myDiv text

You need to make sure the document is loaded when you call your function.


text:
Q: Declaring uninterpreted polyadic functions with Z3Py Using Z3Py, I'm trying to write a function decl_func(fname, arity) which takes in two arguments : fname, the name of the function to be declared, and arity, its number of arguments, and returns the corresponding (uninterpreted) Z3 function over integers. The problem is that the value of arity cannot be predetermined, so the function body cannot be
return Function(fname, IntSort(), IntSort())

or
return Function(fname, IntSort(), IntSort(), IntSort())

as it would be for unary or binary functions. Here's one crude workaround I've considered :
exec('f = Function(\'%s\', %s)' % (fname, ('IntSort(), ' * arity + 'IntSort()')))
return f

but this does not work, seemingly due to the way exec handles variable declarations (I'm using Python 3, if that is relevant).
Any thoughts?

A: This question is about variadic functions in Python.

You can use the same "*" syntax to apply the function to an existing list of arguments:

Therefore, something like this should work:
sorts = [IntSort(), IntSort(), IntSort()]
return Function(fname, *sorts)


text:
Q: Using an UIView as a Mask in another UIView on Swift I am developing an App on xCode with Swift. My screen has an Image of an animal (outlet "backImage"), over this image I have a view (outlet "coverView"), color black, which covers all the screen. So so far you can't see the animal image, because the "coverView" is in front of it. Then I have another view (outlet "maskView") which is smaller and it's over the big view "coverView". What I want is to use this "maskView" as mask and therefor see the "backImage" through it, like a window.
Is there anyone out there able to figure this out?
Here is my screen, I want to see the woman character behind the big gray view through the smaller white view:

A: You can set the alpha property from your mask view and add in front of the other view, for instance:
let maskView = UIView()
maskView.backgroundColor = UIColor(white: 0, alpha: 0.5) //you can modify this to whatever you need
maskView.frame = CGRect(x: 0, y: 0, width: imageView.frame.width, height: imageView.frame.height)

yourView.addSubview(maskView)

EDIT: Now that you edited your question with an image, now I see what you need, so here is how you can accomplish that.
func setMask(with hole: CGRect, in view: UIView){

    // Create a mutable path and add a rectangle that will be h
    let mutablePath = CGMutablePath()
    mutablePath.addRect(view.bounds)
    mutablePath.addRect(hole)

    // Create a shape layer and cut out the intersection
    let mask = CAShapeLayer()
    mask.path = mutablePath
    mask.fillRule = kCAFillRuleEvenOdd

    // Add the mask to the view
    view.layer.mask = mask

}

With this function, all you need is to have a view and create a shape that it's going to be a hole in that view, for instance:
// Create the view (you can also use a view created in the storyboard)
let newView = UIView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height))
newView.backgroundColor = UIColor(white: 0, alpha: 1)

// You can play with these values and find one that fills your need
let rectangularHole = CGRect(x: view.bounds.width*0.3, y: view.bounds.height*0.3, width: view.bounds.width*0.5, height: view.bounds.height*0.5)

// Set the mask in the created view
setMask(with: rectangularHole, in: newView)

A: Thank you, @Alexandre Lara! You did it!
Here goes the solution:
@IBOutlet weak var windowView: UIView!
@IBOutlet weak var bigCoverView: UIView!

func setMask(with hole: CGRect, in view: UIView){

    // Create a mutable path and add a rectangle that will be h
    let mutablePath = CGMutablePath()
    mutablePath.addRect(view.bounds)
    mutablePath.addRect(hole)

    // Create a shape layer and cut out the intersection
    let mask = CAShapeLayer()
    mask.path = mutablePath
    mask.fillRule = kCAFillRuleEvenOdd

    // Add the mask to the view
    view.layer.mask = mask

}

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    let rectangularHole = windowView.frame.integral

    // Set the mask in the created view
    setMask(with: rectangularHole, in: bigCoverView!)

}


text:
Q: Save images not properly display on heroku i'm using Rails 3.2.6 and using carrierwave to upload images.When i upload image it is display fine and its image url also working well. But when i push next git commit on heroku.
       git push staging master

than all images that i had already upload not display and its image path are not working
why?
Please anyone can tell what's the problem is running.
Thnaks

A: Did you setup carrierwave with s3 (https://github.com/jnicklas/carrierwave#using-amazon-s3)?
Heroku has a read only file system (https://devcenter.heroku.com/articles/s3).

A: Whilst your uploads will work - the moment you push new code, or your application is restarted you will loose any uploads.
Heroku uses an Ephemeral file system, in that each dyno receives a separate copy (slug) of the originally deployed code so uploads would only exist on the dyno that handled the upload (https://devcenter.heroku.com/articles/dynos#ephemeral-filesystem).
You need to use an external persistant data store like Amazon S3, Rackspace Files etc - fortunately with Carrierwave it's trivial to update it to use it as it supports it out of the box.


text:
Q: Can't manually send transactional email? I'm trying to send a transactional email template to myself manually (on a test.php page) but it won't send despite all of my efforts and research.
I've tried all three posts linked in this question and can't get it to send anything.
include_once "app/Mage.php";
umask(0);
Mage::app();

$mailTemplate        = Mage::getModel('core/email_template');
$translate           = Mage::getSingleton('core/translate');
$templateId          = 20;
$template_collection = $mailTemplate->load($templateId);
$template_data       = $template_collection->getData();

if(!empty($template_data))
{
    // var_dump($template_data);
    $templateId  = $template_data['template_id'];
    $mailSubject = $template_data['template_subject'];

    $from_email  = 'trvsw@example.com';
    $from_name   = 'trvsw';
    $sender      = array('name'=> $from_name,
                         'email' => $from_email);

    $vars        = array('customerName' => 'trvsw');
    $storeId     = 2;

    $model = $mailTemplate->setReplyTo($sender['email'])->setTemplateSubject($mailSubject);
    $email = 'trvsw@example.com';
    $name  = 'trvsw';
    echo "template ".$templateId." sender ".$sender['name'].", ".$sender['email']." email ".$email." name ".$name." vars ".$vars['customerName']." store id ".$storeId."
";
    $model->sendTransactional($templateId, $sender, $email, $name, $vars, $storeId);
    if(!$mailTemplate->getSentSuccess()) {
        echo "Something went wrong...
";
    } else {
        echo "Message sent to ".$email."!!!
";
    }
    $translate->setTranslateInline(true);
}

Every time, it just spits out "Something went wrong..." Any ideas?
The transactional email is titled "Test" with the subject "Test" and the body
This is a test.

Thank you, {{var customerName}}

Edit:
Here is the exception that I'm finding in my exception.log
2015-08-06T13:15:01+00:00 ERR (3):
exception 'Zend_Mail_Protocol_Exception' with message '5.1.1 Recipient unknown
' in /var/www/sites/mbs/lib/Zend/Mail/Protocol/Abstract.php:431
Stack trace:
#0 /var/www/sites/mbs/lib/Zend/Mail/Protocol/Smtp.php(289): Zend_Mail_Protocol_Abstract->_expect(Array, 300)
#1 /var/www/sites/mbs/lib/Zend/Mail/Transport/Smtp.php(217): Zend_Mail_Protocol_Smtp->rcpt('travisw@example...')
#2 /var/www/sites/mbs/lib/Zend/Mail/Transport/Abstract.php(348): Zend_Mail_Transport_Smtp->_sendMail()
#3 /var/www/sites/mbs/lib/Zend/Mail.php(1194): Zend_Mail_Transport_Abstract->send(Object(Zend_Mail))
#4 /var/www/sites/mbs/app/code/local/Moogento/Pickpack/Model/Core/Email/Templateattach.php(1983): Zend_Mail->send(Object(Zend_Mail_Transport_Smtp))
#5 /var/www/sites/mbs/app/code/core/Mage/Core/Model/Email/Template.php(508): Moogento_Pickpack_Model_Core_Email_Templateattach->send('travisw@example...', 'trvsw', Array)
#6 /var/www/sites/mbs/test.php(50): Mage_Core_Model_Email_Template->sendTransactional('Test', Array, 'travisw@example...', 'trvsw', Array, '1')
#7 {main}

A: Looking at your code there are a few items that doesn't seem right.
You can update it to the following:
include_once "app/Mage.php";
umask(0);
Mage::app();

$mailTemplate        = Mage::getModel('core/email_template');
$translate           = Mage::getSingleton('core/translate');
$templateId          = 20;
$template_collection = $mailTemplate->load($templateId);
$template_data       = $template_collection->getData();

if(!empty($template_data)) {
    $mailSubject = 'Subject';
    $from_email  = 'trvsw@example.com';
    $from_name   = 'trvsw';
    $sender      =  array(
                       'name'  => $from_name,
                       'email' => $from_email
                   );

    $vars        = array('customerName' => 'trvsw');
    $storeId     = Mage::app()->getStore()->getStoreId();

    $model = $mailTemplate->setReplyTo($sender['email'])->setTemplateSubject($mailSubject);
    $email = 'trvsw@example.com';
    $name  = 'trvsw';
    try {
        $model->sendTransactional($templateId, $sender, $email, $name, $vars, $storeId);
    if(!$mailTemplate->getSentSuccess()) {
        echo "Something went wrong...
";
    } else {
        echo "Message sent to ".$email."!!!
";
    }
    $translate->setTranslateInline(true);
    } catch(Exception $e) {
       Mage::logException($e)  ;
    }
}

Originally in your code you're assigning $templateId  = $template_data['template_id']; which doesn't exist.
I tested the code and that seems to be the only item that doesn't seem right. I'd also look at changing how you're loading the template to use the name rather than the ID e.g
Mage::getModel('core/email_template')->loadByCode('Tests') if Tests is the name of your template you have setup.
EDIT:
Looking at your update looks like its your SMTP server on your local environment that is unable to send the email. see https://stackoverflow.com/questions/7504424/sendmail-returns-error-code-550-5-1-1-user-unknown


text:
Q: How to bind Database and a datagrid to an ObservableCollection WPF I've been googling to find an answer but I couldn't find.
Here is my problem, I have a

*

*database table call sold_item_details

*datagrid with seven columns

*ObservableCollection

1 Need to bind ObservableCollection with database
I want to get set of strings from database and need to add to ObservableCollection as
    rows. I want to achieve, something similar to following code,
 ObservableCollection<string> o = new ObservableCollection<string>();
 o.add("string1","string2","string3","string4","string5"); // this has to be one row
 o.add("string6","string7","string8","string9","string10");

likewise there are set of data sets. So far I've seen that Objects are added and from that
    this is achieved but I don't want to create objects for each set of strings.
2 Need to bind ObservableCollection with the datagrid
so datasets inside the ObservableCollection is added as rows to the datagrid (there are
    five columns)
Can anyone suggest me a method to achieve this?
EDIT: These are the codes what I've achieved,
<DataGrid x:Name="dataGrid" AutoGenerateColumns="False" CanUserResizeRows="False" Grid.ColumnSpan="8"
    Margin="-20,0,30.5,0" CanUserResizeColumns="False" CanUserReorderColumns="False"
    CanUserSortColumns="False" CanUserAddRows="False">
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding supplier_id}" CanUserResize="False" FontSize="16"
            Header="Supplier" Width="0.18*" />
        <DataGridTextColumn Binding="{Binding item_id}" CanUserResize="False" FontSize="16"
            Header="ItemID" Width="0.13*" />
        <DataGridTextColumn Binding="{Binding item_name}" CanUserResize="False" FontSize="16"
            Header="Item name" Width="0.2*" />
        <DataGridTextColumn Binding="{Binding weight}" CanUserResize="False" FontSize="16" Header="kg"
            Width="0.1*" />
        <DataGridTextColumn Binding="{Binding price_per_kg}" CanUserResize="False" FontSize="16"
            Header="Price/kg" Width="0.1*" />
        <DataGridTextColumn Binding="{Binding no_of_bags}" CanUserResize="False" FontSize="16"
            Header="Bags" Width="0.07*" />
        <DataGridTextColumn Binding="{Binding rent_amt}" CanUserResize="False" FontSize="16"
            Header="Rent" Width="0.07*" />
        <DataGridTextColumn Binding="{Binding total_price}" CanUserResize="False" FontSize="16"
            Header="Value" Width="0.15*" />
    </DataGrid.Columns>
</DataGrid>

OrderItem class properties of this class should goes to the columns of the datagrid
public class OrderItem
{
    public OrderItem(string supplierId,
        string itemId,
        string itemName,
        decimal weight,
        decimal price,
        int noOfBags,
        decimal rentAmt)
    {
        SupplierId = supplierId;
        ItemId = itemId;
        Weight = weight;
        Price = price;
        NoOfBags = noOfBags;
        RentAmt = rentAmt;

        BagPrice = // bag price will get from a method
        TotalPrice = // something

    }

    public string SupplierId { get; set; } // Supplier's ID
    public string ItemId { get; set; } // Item ID
    public string ItemName { get; set; }// Item Name
    public decimal Weight { get; set; } // weight of the item
    public decimal Price { get; set; } // Total sum of the order
    public int NoOfBags { get; set; } // Number of bags in a single order
    public decimal BagPrice { get; set; }
    public decimal RentAmt { get; set; } // To weigh the item
    public decimal TotalPrice { get; private set; }
}

when adding an item it is sent to the ObservableCollection
ObservableCollection<OrderItem> orderItems = new ObservableCollection<OrderItem>();
//and at the right event (key enter is pressed) the orderItem object is added to the orderItems
orderItems.add(orderI);

In the xaml code for grid I have already bound to the database directly what i need is to bind this to ObservableCollection

A: Why don't you create a datagrid with 5 columns and create a dataclass for that. So that the source of the datagrid could be bound to an ObservableCollection in your view model. You can set each column inside the template of the data grid. In this case, you need not add each item to the list. Maybe add all the items fetched from database to the ObservableCollection.
Maybe the memory consumption would be less, but still a better design is to have a dataclass and a list of items that binds to the datagrid. These 5 strings would be serving some purpose, right? For further computation or calculation, it would be better to reuse the fetched data by using an ObservableCollection for your requirement. Anyways it's upto you. If you want you could hold on to the way of passing 5 strings also.


text:
Q: Binary column by combining categories? I have a question! I know what do but I'm having a hard time when trying to start coding.
I need to create a binary column by combining categories A and B (Low Risk) into one category and all the remaining categories in another (High Risk).


text:
Q: Drupal 9 Commerce Opayo (previously Sagepay) SCA - Strong Customer Authentication I have been trying to implement a Drupal 9 Commerce site with Opayo (previously Sagepay) as a payment gateway.  The site was working up until Monday when the EU Strong Customer Authentication (SCA).
Opayo have said
You are using PI integration but its on protocol 3- it must be upgraded to protocol 4 to be compliant for 3D Secure V2 (SCA).
Does anyone have a Drupal 9 Commerce Opayo site that has PI integration with protocol 4.
Would you possibly tell me how you implemented this.
Many thanks for your help.
N


text:
Q: The PHP Websocket server cannot handle multiple requests at the same time I have tried many ways over the past few days to let the PHP Websocket server handle multiple requests at the same time but it doesn't seem to be possible.
Here is my full code:
...
//check for any incoming data
        while (socket_recv($changed_socket, $buf, 1024, 0) >= 1) {
            $received_text = unmask($buf); //unmask data
            $tst_msg = json_decode($received_text); //json decode
            if (isset($tst_msg->name) && isset($tst_msg->message)) {
                $user_name = $tst_msg->name; //sender name
                $user_message = $tst_msg->message; //message text

                //prepare data to be sent to client
                $response_text = mask(json_encode(['type' => 'usermsg', 'name' => $user_name, 'message' => $user_message]));
                send_message($response_text); //send data

                while (true) {
                    $curl = curl_init();
                    curl_setopt_array($curl, array(
                        CURLOPT_RETURNTRANSFER => 1,
                        CURLOPT_URL => 'http://localhost/api.php',
                        CURLOPT_SSL_VERIFYPEER => false
                    ));

                    $Response2 = json_decode(curl_exec($curl));
                    curl_close($curl);

                    if ($Response2->msg->{$user_message} == "true") {
                        $response_text = mask(json_encode(['type' => 'usermsg', 'name' => "Server", 'message' => "Success"]));
                        send_message($response_text); //send data

                        break 3;
                    }
                }
            }

            break 2; //exist this loop
        }
...

It will receive the message from the client then will curl continuously to the url http://localhost/api.php. Here is the code in the file api.php:
<?php

echo json_encode([
    "status" => "success",
    "msg" => [
        "one" => "false"
    ]
]);

When curl arrives at http:localhost/api.php, it responds with a json snippet.
The server then checks if $user_message exists in $Response2. And if exists is it equal to "true"?
If $Response2->msg->{$user_message} equals "true" then the client response will be Success.
If there are 2 requests at the same time and the first incomplete request ($Response2->msg->{$user_message)} is not equal to "true", the server will continue curling until it is "true" then process the second request.
This article is translated using Google Translate because I am not good at English. I really need help. Thank you very much. I spent too much time on this problem.


text:
Q: wxStreamToTextRedirector newlines are lost I am getting result from wxStreamToTextRedirector as one line. The newlines are lost ....
 wxStreamToTextRedirector  with just one parameter supposed to redirect output to cout, I have
 no clue why the newlines are not treated by cout, as such...
Update: a simplified example: produces the same result i.e newlines are lost.
    textctrl = new wxTextCtrl(this, -1, wxT(""), wxPoint(-1, -1),
     wxSize(250, 150));
{
    wxStreamToTextRedirector redirect(textctrl);
       string result = "line1\n Line2\n";
      cout << result;

}

Output ---> line1 Line2, as appears in the textctrl window. May it be that textctrl
window does not interpret
\n correctly? I am using wxWidets on a Windows machine.

A: When creating a wxTextCtrl, by default it is created without support for multiple lines. You have to tell it that you intend to use multiple lines. If you are using Code::Blocks with wxSmith (which I recommend), you can specify that in the properties of the wxTextCtrl:

If you are creating it manually with code, you only need to specify wxTE_MULTILINE in the style parameter of the constructor, like this:
textctrl = new wxTextCtrl(this, -1, wxT(""), wxPoint(-1, -1), wxSize(250, 150),wxTE_MULTILINE);

For more information, you can check this page  about the possible styles, and in particular, this section about the constructor.


text:
Q: Tenses in 'Did I tell you what happened to me?' Why can't we use Past Perfect in the second clause of the sentence

'Did I tell you what happened to me?'

if the second clause happened before 'Did I tell you'
As far as I know, we use Past Perfect to say that something happened before another action in the past. Of course, sometimes we can use Simple Past instead when we have 'after', 'before' in the sentence and Past Perfect becomes optional there.
I googled 'Did I tell you what had happened to me?' in quotation marks and there was nothing on the Internet.
Could you, please, explain why we can't say that way?

A: That sentence is perfectly fine.  There's an implicit "had" before "happened", making it past perfect.  Try

Did I tell you what had happened to me?

Although the "had" isn't written, it's assumed to be there.


text:
Q: Is pitch and speed the same thing in audio programming context? Pitch means "perceived frequency". Nice. But when I make pitch very low in OpenAL, sound plays a lot of times longer. If I make it very high, sound plays very short but with high frequency. For me, logically the consequence of making slower or faster.
Or is pitch != speed?

A: Paul R has a pretty good answer, but I'd like to expand on it a bit. If you think of the sound as a series of pulses (and it kind of is), then a higher pitch will have more pulses per second (higher frequency) and a lower pitch will have fewer (lower frequency). To lower the pitch of an existing sound, you have to spread those pulses out (make them further apart from each other). As a result, the duration of the sound will increase because you haven't reduced the number of pulses, you've just made them further apart (fewer per second). The opposite happens if you try to increase the pitch: the pulses are closer together, thus making the sound shorter in duration.
If you want the duration to remain constant regardless of changes to the recorded pitch, you have to either throw information away (lower pitch) or manufacture information (higher pitch). This is where the fancy processing comes in. What can be safely discarded? What can be safely duplicated or constructed?

A: It's relatively easy to vary pitch and rate together, since all you need to do is vary the rate at which you play back samples. If you play samples back at half their intended rate then pitch will be halved and the sound will come out at half speed (think about a tape deck running at the wrong speed). Conversely playing samples back faster than intended will increase pitch and make everything faster.
You can vary pitch and rate independently, but it takes a lot more processing to do this, typically using some kind of analysis and re-synthesis algorithm (e.g. PSOLA for speech).

A: Using the algorithm you're describing in OpenAL, pitch = f(speed), and speed = f'(pitch).
It is possible to vary these parameters somewhat independently using a different algorithm.  There are a variety of algorithms for doing this.
The algorithms in question can exist in the frequency domain (vocoder, frequency domain convolution) or in the time domain (PSOLA, WSOLA, extended WSOLA) or in both at the same time (hybrid models that use time-domain methods for transient sections and vocoder methods for tonal sections).


text:
Q: functors unique up to self-equivalence of the source category Call two functors two functors $H,H':S\longrightarrow T$  weakly equivalent, or equivalent up to a self-equivalence of the source category, iff
there exists a self-equivalence of $s:S \longrightarrow S$ such that functors $H$ and $H'\circ s$ are equivalent.

Can this property "weakly equivalent" be nicely reformulated in the language of higher category theory? or maybe homotopy theory?
Are there theorems claiming that any two functors with certain properties (not involving choice) are weakly equivalent?

That is, for such a theorem to be interesting, the properties should not explicitly involve an arbitrary choice, e.g. it should not say: choose a topology, bijection, self-equivalence and then construct the functor in the following way. Rather, a functor should be described in terms of preserving some structure etc.
Below is the original question which was phrased very confusingly, it seems. I hope now it maybe is clearer.
Say a functor is "well-defined up to a self-equivalence of the source category"
by certain properties/definition/construction iff, well,
for any two functors $H,H':S\longrightarrow T$ with satisfying these properties/definition/obtained by this construction,
there exists a self-equivalence of $s:S \longrightarrow S$ such that functors $H$ and $H'\circ s$ are equivalent.

Is there a nice way to reformulate this property
  "a functor unique up to self-equivalence of the source category", say in the language of 2-categories?
Are there any interesting examples of properties/definitions/constructions NOT involving arbitrary choice
  and yet such that the functor is well-defined  up to a self-equivalence of source category ?

I am mostly interested to see an "algebraic" definition of a functor between "algebraic" categories which is well-defined up to self-equivalence but not well-defined.

A: In short, this is equivalence of objects in the weak slice 2-category $\mathbf{CAT}/T$.
First recall the classical notion of slice category: given any category $\mathcal{C}$ and object $C$, there's a category $\mathcal{C}/C$ (called $\mathcal{C}$ sliced over $C$) whose objects are the maps in $\mathcal{C}$ with codomain $C$ and whose maps are commutative triangles.
When $\mathcal{C}$ is a 2-category, you can make the same sort of definition (so that any object $C$ of $\mathcal{C}$ gives rise to a slice 2-category $\mathcal{C}/C$), but you now have a choice to make.  The objects of $\mathcal{C}/C$ are defined as before, but you could ask for the 1-cells in $\mathcal{C}/C$ to be strictly commutative triangles, or triangles that commute up to a specified invertible 2-cell, or triangles that commute up to a specified not-necessarily-invertible 2-cell (and then you have to decided which way it points).  In all cases, there's an obvious way to define the 2-cells of $\mathcal{C}/C$.
Let's take the "weak" or "pseudo" version of $\mathcal{C}/C$, in which the 1-cells are triangles that commute up to a specified invertible 2-cell.  Take two objects of $\mathcal{C}/C$, say $h\colon D \to C$ and $h'\colon D' \to C$.  In any 2-category, there's a notion of equivalence of objects.  In this case, $h$ and $h'$ are equivalent in $\mathcal{C}/C$ if and only if there's an equivalence $s\colon D \to D'$ in $\mathcal{C}$ such that $h' \circ s \cong h$.
Applied to $\mathcal{C} = \mathbf{CAT}$, this gives the notion of "weak equivalence" you mention.  (It just so happens that in your setting, the domains of $H$ and $H'$ are equal.)

A: This is a mine observation (from old personal paper), may be can help. I hope my English is understandable
I thought about this question in correlation to proposition 2.2.1 p.31 of "Indexed categories and its Applications" LNM 661:
Give a functor $F:\mathcal{C}^{op}\to Cat$ (i.e. a strict indexed category) if its  objets and morphisms presheaf are representable:  $\mathcal{A}(C_0, -)\cong F_0$, $\mathcal{A}(C_1, -)\cong F_1$ by Yoneda lemma  domain, codomain the transformations $d_0:  F_1\Rightarrow F_0$, $d_1:  F_1\Rightarrow F_0$ ecc. describe a internal category $\underline{C}$ of $\mathcal{A}$ and a isomorphism $F\cong [\mathcal{C} ]$ where $[\mathcal{C}]$ is the presheaf of (small) categories defined as $|[\mathcal{C}](A)|_0=\mathcal{A}(A, C_k)\ k=0, 1$ ecc.
But what if $F$ is a pseudo.functor? ($F_0$, $F_1$ aren't presheaves, for the composition we haven't the strict coherence, but accompanied by automorphisms on codomain..)
The authors of the reference above consider $F_0(A)$ as the class of (canonically) isomorphic object of $|F(A)|_0$, and for $F_1(A)$ as the class of (canonically) isomorphic morphisms (as objects of $F(A)^{\underline{2}}$). At first reading I seem that this reduction to "pseudo-skeletons"  avoid the trouble of the canonical isomorphisms. I remember that the skeleton of a (small) category is make by a chose of a object for any isomorphic call, and make the full subcategory. But how is related a small category $\mathcal{C}$ with its pseudo-skeleton $pS(\mathcal{C})$?
Of course we have the natural functor (make  the quotient maps) $\pi: \mathcal{C}\to pS(\mathcal{C})$, now, try to define a reciprocal (equivalence we hope) functor $P$, merely a "chose functor":  then $P$ map any object $\xi\in pS(\mathcal{C})$ to a  its representant $X_{\xi}\in \mathcal{C}$ with $[X_\xi]=\xi$, and any morphism $\alpha: \xi\to \xi'$ to a its representant $f_\alpha: X_\xi\to X_{\xi'}$ with $[f_\alpha]=\alpha$,
(observe that a different chose $g_{\xi}$ is related to $f_\xi$ by automorphisms on domain and codomain $X_\xi$, $X_{\xi'}$ this is a generalization to the initial question)
we can chose $P(1_\xi)=1_{X_\xi}$ of course, but in general $f_{\gamma\circ\xi}\neq f_{\gamma}\circ f_\xi$ but these are related by automorphisms on domain and codomain.
Then I consider 2-category $G(\mathcal{C})$ make as follow: take the usual skeleton $Sk(\mathcal{C})$, then for $f, g: X\to Y$ define 2-cell $f\Rightarrow g$ as a couple of isomorhisms $s: X\to X,\ t: Y\to Y$ with $t\circ f=g\circ s$ (with natural composition and identities) then I have a correct 2-equivalences (make by a 2-functor and a pseudo-functor)) from $G(\mathcal{C})$ and its local skeleton (take skeleton on Hom-categories) that is just the pseudo-skeleton  $pS(\mathcal{C})$ .


text:
Q: Composition of boolean function In this problem we describe the boolean functions of $n$ variables like a vectors with lenght $2^n$ with standard assumption that $k$-th component of the vector $0\leq k \leq 2^n -1$ is thе value of the function on this boolean assessment, which is the record of k in binary positional system.
The problem :
Let $f=(0, 1, 0, 1, 0, 0, 0, 1), g=(0, 1, 1, 1)$ and $h=(0, 0, 0, 1)$.
Write the composition of :
1.$$f(g(u, v), y, z)$$
 2.$$ g(h(u, z), z)$$
 3.$$f(g(u, v), g(u, v), g(h(u, z), h(u, z)) )$$
Can you help me with the first one...than I will try to do the other two myself. Thanks.

A: $f(g(u,v),y,z)$: Treat the input to this composition as a $4$-tuple $\langle u,v,y,z\rangle$. Let's look at a few sample inputs. The $0$-th input is $u=v=y=z=0$, and for that input we get
$$f(g(0,0),0,0)=f(0,0,0)=0\;.$$
The $5$-th input is $u=y=0,v=z=1$, and for that input we get
$$f(g(0,1),0,1)=f(1,0,1)=0\;.$$
More generally, we can make a table:
$$\begin{array}{c|c|c}
u&v&g(u,v)&y&z&f(g(u,v),y,z)\\ \hline
0&0&0&0&0&0\\
0&0&0&0&1&1\\
0&0&0&1&0&0\\
0&0&0&1&1&1\\ \hline
0&1&1&0&0&0\\
0&1&1&0&1&0\\
0&1&1&1&0&0\\
0&1&1&1&1&1\\ \hline
1&0&1&0&0&0\\
1&0&1&0&1&0\\
1&0&1&1&0&0\\
1&0&1&1&1&1\\ \hline
1&1&1&0&0&0\\
1&1&1&0&1&0\\
1&1&1&1&0&0\\
1&1&1&1&1&1
\end{array}$$
The composition is therefore described by the $2^4$-place vector
$$\langle 0,1,0,1,0,0,0,1,0,0,0,1,0,0,0,1\rangle\;.$$


text:
Q: Limit the number of appends in JQuery I wan't to limit the number of append that happen in Jquery whenever I click the button
    function standardRoom() {
  var flag = 0
  if ($('select#selectBoxStandard option').length > 1 ) {
    flag++
    $('#selectBoxStandard').find("option:nth-last-child(-n+" + $('#selectBoxStandard').val() + ")").remove();
    if (flag <= 1) {
        $("#roomDetail ul").append('
Standard Room - Regular Online Rate
').append('

PHP {{$availableRooms[0]['nightRate']}}

').append('
Number of night(s): {{$n_nights}}
').append('
Number of person(s):
').append('
Number of room(s):
').append(flag);
    }
  }else {
    alert("No more rooms");
  }
}

I tried using if statement based on what I find here. But it's not working, it just keeps on appending.

A: Everytime you call standardRoom function the flag variable is reset to 0, so it will always keeps adding the elements. Make sure you store that variable somewhere more global where you don't need to reset it:
   var flag = 0;
   function standardRoom() {
       if ($('select#selectBoxStandard option').length > 1 ) {
           flag++
           $('#selectBoxStandard').find("option:nth-last-child(-n+" +
           $('#selectBoxStandard').val() + ")").remove();
           if (flag <= 1) {
               $("#roomDetail ul").append('
Standard Room - Regular Online Rate
').append('

PHP {{$availableRooms[0]['nightRate']}}

').append('
Number of night(s): {{$n_nights}}
').append('
Number of person(s):
').append('
Number of room(s):
').append(flag);
           }
       } else {
          alert("No more rooms");
       }
    }

A: flag gets reset on every function call. Define it outside the function.
 var flag = 0
    function standardRoom() {

          if ($('select#selectBoxStandard option').length > 1 ) {
        flag++
        $('#selectBoxStandard').find("option:nth-last-child(-n+" + $('#selectBoxStandard').val() + ")").remove();
        if (flag <= 1) {
            $("#roomDetail ul").append('
Standard Room - Regular Online Rate
').append('

PHP {{$availableRooms[0]['nightRate']}}

').append('
Number of night(s): {{$n_nights}}
').append('
Number of person(s):
').append('
Number of room(s):
').append(flag);
        }
      }else {
        alert("No more rooms");
      }
    }

A: You may use custom data attributes instead of your  local variable.
At dom ready you can set the value of flag data attribute for your selectBoxStandard element and after you can use it:
// init flag value
$('#selectBoxStandard').data('flag', 0);

function standardRoom() {
    // get flag value
    var flag = $('#selectBoxStandard').data('flag');

    if ($('select#selectBoxStandard option').length > 1 ) {

        // update flag value
        $('#selectBoxStandard').data('flag', flag++)

        $('#selectBoxStandard').find("option:nth-last-child(-n+" + $('#selectBoxStandard').val() + ")").remove();
        if (flag <= 1) {
            $("#roomDetail ul").append('
Standard Room - Regular Online Rate
').append('

PHP {{$availableRooms[0]['nightRate']}}

').append('
Number of night(s): {{$n_nights}}
').append('
Number of person(s):
').append('
Number of room(s):
').append(flag);
        }
    }else {
        alert("No more rooms");
    }
}


text:
Q: Using Jackson annotations in java-library (not application) I am writing a java-library that will be included included as a dependency in other projects. I want some of the library's classes to de/serializable with Jackson's ObjectMapper. Out of habit, I have used annotations to tell Jackson how to de/serialize my classes.

*

*Will the annotations' functionality get exported by the library (like api)?

*Will a dependent application be able to use the an ObjectMapper created by the default constructor? Is any further configuration necessary?

*Can I put the annotations into a custom Jackson Module for dependent applications to register with their ObjectMapper?

I have been very surprised to find a dearth of documentation for this use case.


text:
Q: Are there any binary serializers available? Going for space savings here. I have an object that I need to serialize for each row.
In theory, it needs to consist of 168 16b unsigned integers (even though there's no explicit typing in php), that should be worth 336 bytes.
If I go for the serialize() function that creates strings though, the size is up to 2349 bytes.
Is there a binary kind of serializer for php?

A: Store the data in a plain and simple array. Then pack it:
$len = count($arr);
$data = pack("S$len", ...$arr); // requires PHP5.6+

To get the array back you want to unpack()it:
$arr = unpack("S$len", $data);

Mind you that you need to keep the $len variable along the $data block.
More about it here.


text:
Q: How to pass a string variable as an argument to a javascript function? I am new to JavaScript and I am trying to pass a string variable as an argument to a JavaScript function, but I am getting no results on doing it, nothing inside the functions gets executed when a call to a JavaScript function is made.
A little help also is appreciable.

A: the function will be like this
declaring and defining function
function demo(arg)
{
 //use arg for your code
}

calling function
demo("hello");

hope this helps....

A: function show(value) {
  alert(value);
}

show('test');

If this is not what you're looking for, you should clarify your question.

A: In Javascript, you don't need to specify the type of a variable. If your variable is a string, the system will handle it as such. Here is a basic example embedded in an HTML page to get you started:
Edit:
<!DOCTYPE html>

        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

A: you can dump you variable as json format, and then parse json string to variable in your function
//this is your params
my_params =
[
  "dict": {
    "abc":true,
    "xyz":1
  },
  "data": "blah blah blah..."
]

//dump params to json
var myObject = JSON.stringify(my_params);

//pass param to function
my_function( myObject );

function my_function( object )
{
    //parse json to object
    myObject = JSON.parse( object );
    alert( myObject ["data"] );
    ...
}


text:
Q: Lattice full plot area I want to delete R's default margin around the lattice plot. This means that I want to get rid of all the white spaces beyond the red rectangular. Here is the example:
library (raster)
library(rasterVis)

f <- system.file("external/test.grd", package="raster")
r <- raster(f)
levelplot(r, margin=T)

A: You can adjust the margins with the layout.heights and layout.widths arguments to lattice.options:
lattice.options(
  layout.heights=list(bottom.padding=list(x=0), top.padding=list(x=0)),
  layout.widths=list(left.padding=list(x=0), right.padding=list(x=0))
)
levelplot(r, margin=TRUE)

Select the image above (e.g. by clicking to the right of it and dragging left) to verify that the margins are as expected.
However, white space will still fill the horizontal extent of the graphics device, so you need to either adjust the xlim so that the white space is within the plot rather than outside it, or just adjust the width of the device appropriately. I did the latter, which might take a bit of trial and error if plotting to a file, but which is straightforward if plotting to an x11/windows/quartz device (just resize the pane).


text:
Q: Center google Map on place ID without specifying lat and long? How do you center a google map based on a placeID, without setting the lat and lng explicitly in the map object?
All examples I've seen have a value set e.g.
var pyrmont = new google.maps.LatLng(-33.8665433,151.1956316);

Form: developers.google.com
Surely you can getDetails on a place based on an ID, then use the lat and lng to center the map?
function initializeGoogleMaps() {
  jQuery('.site-content').prepend('

');

  var request = {
    placeId: 'ChIJzXBGLkQFdkgRoyT2MIxgWGw'
  };

  function callback(place, status) {
    if (status == google.maps.places.PlacesServiceStatus.OK) {
      var marker = new google.maps.Marker({
        map: map,
        position: place.geometry.location
      });
    }
  }

  var map = new google.maps.Map(document.getElementById('map-canvas'), {
    center: {
      lat: 51.509526,
      lng: -0.156314
    },
    zoom: 15
  });

  service = new google.maps.places.PlacesService(map);
  service.getDetails(request, callback);
}

A: You can set the center of the map using the value returned from the places service (or the position of the marker):
proof of concept fiddle
  function callback(place, status) {
    if (status == google.maps.places.PlacesServiceStatus.OK) {
      var marker = new google.maps.Marker({
        map: map,
        position: place.geometry.location
      });
      map.setCenter(marker.getPosition());
    }
  }

  var map = new google.maps.Map(document.getElementById('map-canvas'), {
    zoom: 15
  });

code snippet:

function initializeGoogleMaps() {
  var request = {
    placeId: 'ChIJzXBGLkQFdkgRoyT2MIxgWGw'
  };

  function callback(place, status) {
    if (status == google.maps.places.PlacesServiceStatus.OK) {
      var marker = new google.maps.Marker({
        map: map,
        position: place.geometry.location
      });
      map.setCenter(marker.getPosition());
    }
  }

  var map = new google.maps.Map(document.getElementById('map-canvas'), {
    zoom: 15
  });

  service = new google.maps.places.PlacesService(map);
  service.getDetails(request, callback);
}
google.maps.event.addDomListener(window, 'load', initializeGoogleMaps);
html,
body,
#map-canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}


text:
Q: Auto populate a Form I'd like to auto populate a form / Text area with the post content !
For Example :
The link below has got a link which take it to the form !
http://cozysms.com/passenger-tumne-mere-jeb-me-hath/

When somebody click at the link - Send Sms Now just below the social buttons
it will take it to the form -
http://cozysms.com/send-free-sms/

I want to auto populate the form with - the_content() of the www.cozysms.com/passenger-tumne-mere-jeb-me-hath/
Similarly for other articles. Is this doable?

A: add_filter( 'comment_form_defaults', 'bootstrap3_comment_form' );

function bootstrap3_comment_form( $args ) {
    $args['comment_field'] = '<div class="form-group comment-form-comment">
    <textarea class="form-control" id="comment" name="comment" cols="45" rows="8" aria-required="true" placeholder="' . __( 'Comment', "beautiful" ) . '"></textarea>
</div>';
return $args;
}

fetch your content and put it inside textarea tag.
you should add this function to your functions.php it's better to change name of the function and language text domain.
this function override WordPress default textarea of comment section. it's also with bootstrap 3


text:
Q: How to compare Twilio 'From' numbers I would like to compare two Twilio numbers in a database. Since they begin with "+", I'm not sure how to compare them. Here's my code to collect and save numbers to the database. I'm trying to check incoming numbers against the database.
if request.method == 'POST':
    a = Number.objects.all()
    from_number = request.POST.get('From', None)
    u = Number(cell_number=from_number)
    u.save()
    msg_new = 'We recorded your number as %s' % (from_number)
    m = Response()
    m.message(msg_new)
    return m

As always, thank you for your help!
Update
Based on the answer I received, I updated the code. It works!
 if request.method == 'POST':
        from_number = request.POST.get('From', None)
        if Number.objects.filter(cell_number=from_number).exists():
            msg = "We already have your number recorded in our system."
            r = Response()
            r.message(msg)
            return r
        else:
            u = Number(cell_number=from_number)
            u.save()
            msg_new = 'We recorded your number as %s' % (from_number)
            m = Response()
            m.message(msg_new)
            return m

A: I assume that the Twilio numbers you are referring to are stored in the standard E.164 format, which is standardised to remove all spaces etc.
If so then all you need to do is look up the number in the database. So to see if a number already exists you could do:
if Number.objects.filter(cell_number='+4412349834024').exists():
    # The number already exists in the database
else:
    # The number doesn't exist in the database, go ahead and add it

You probably want to make sure that your cell_number field is indexed if you will be querying it in this way.


text:
Q: Laravel 5.2: How to autofill the creation date of the form I'm struggling with a question that i'm asking myself. I have a form in laravel that posts a new row with data on the index file. Right now I have a couple of set values that I insert into the database. One of those values is "date", I am asking myself: How can I from the moment that I press on the 'save' button automatically fill the created_at field in my database.
Would love to get some help with this

A: just use date('Y-m-d H:i:s'); for created_at field inside your controller (or where you save your obj)
Or use laravel timestamps. It wil auto stamp the date of update and creation
Edit: like our Dutch friend mentioned. just use date