text:
Q: Can this multistep SORT JCL be condensed? I'm using the following JCL to transform the results of a DSNTEPZ query into a required layout, as well as slap on a header and trailer. I've been able to complete my task, but it feels unwieldy. Any JCL wizards out there able to condense any of these steps? I really hate the final sort, but I can't find any way to output a date inside the header of format MMYYYY.
//**********remove extra output lines/reformat   *******************
//SORT     EXEC PGM=SORT,
//             REGION=2000K
//SORTIN   DD  DSN=&&SORT1IN,DISP=(OLD,DELETE,DELETE)    * pds of query results
//SORTWK01 DD  UNIT=SYSDA,SPACE=(CYL,(20,5))
//SORTOUT  DD  DSN=&&SORT1OUT,
//             DISP=(NEW,PASS,DELETE),
//             AVGREC=K,LRECL=100,
//             SPACE=(100,(900,100),RLSE)
//SYSOUT   DD  SYSOUT=*
//SYSIN    DD  *
  SORT FIELDS=COPY -
  INCLUDE COND=(97,1,CH,EQ,C'1',OR,    * This removes the 'informational' Query lines
                97,1,CH,EQ,C'2',OR,
                97,1,CH,EQ,C'0') -
  OUTREC FIELDS=(C'DTL',32,9,71,10,5X,49,19,2X,84,4,89,2,      *Arranging the Output
              92,2,97,1,43X)
/*
//************************ add hdr/trl  ***********************
//SORT2    EXEC PGM=SORT,
//             REGION=2000K
//SORTIN   DD  DSN=&&SORT1OUT,DISP=(OLD,DELETE,DELETE)
//SORTWK01 DD  UNIT=SYSDA,SPACE=(CYL,(20,5))
//SORTOUT  DD  DSN=&&SORT2OUT,
//             DISP=(NEW,PASS,DELETE),
//             AVGREC=K,LRECL=100,
//             SPACE=(100,(900,100),RLSE)
//SYSOUT   DD  SYSOUT=*
//SYSIN    DD  *
  OPTION COPY
  OUTFIL REMOVECC,
  HEADER1=(C'HEADERENE',DATENS=(DM4),19:82X),
  TRAILER1=(C'TRAILER',COUNT=(M11,LENGTH=9),83X)
/*
//************************ CONVERT DATE  ***********************
//SORT3    EXEC PGM=SORT,
//             REGION=2000K
//SORTIN   DD  DSN=&&SORT2OUT,DISP=(OLD,DELETE,DELETE)
//SORTWK01 DD  UNIT=SYSDA,SPACE=(CYL,(20,5))
//SORTOUT  DD  SYSOUT=*
//SYSOUT   DD  SYSOUT=*
//SYSIN    DD  *
  OPTION COPY
  OUTREC IFTHEN=(WHEN=(1,7,CH,EQ,C'HEADERE'),
         BUILD=(1,9,12,6,85X))
/*
//

A: Firstly, JCL is the stuff starting with // (and also /*) in columns one and two. What you want is SORT Control Cards.
  OPTION COPY
  INCLUDE COND=(97,1,CH,EQ,C'1',OR,
                97,1,CH,EQ,C'2',OR,
                97,1,CH,EQ,C'0')

  INREC BUILD=(C'DTL',
               32,9,
               71,10,
               5X,
               49,19,
               2X,
               84,4,
               89,2,
               92,2,
               97,1,
               43X)

  OUTFIL REMOVECC,
      HEADER1=(01:C'HEADERENE',
               10:DATENS=(DM4),
               100:X),
      TRAILER1=(C'TRAILER',
                COUNT=(M11,LENGTH=9),
                100:X)

That's your first two steps.I've removed the spurious "-"s, I've only removed your comments as they didn't fit, you can have inline comments as you had done, or an entire line, starting with an *. I've changed FIELDS to BUILD (FIELDS has been around since Day One, and has multiple uses in different contexts: BUILD has been around for 10 years, and every time you see it (on INREC, OUTREC or OUTFIL) it only means BUILD.
As you have discovered, the content of HEADER1 is limited to what is allowed. Either live with that, or if the content of HEADER1 is not what you want, you can make your own header.
You will: temporarily extend the records to include a SEQNUM, which is large enough to comfortably represent all your records: in OUTFIL, identify the first record, and use the slash-operator (/) to output two records, first the header, which you format how you want, then the actual data record (remembering to exclude any data that you have temporarily extended by).


text:
Q: XML String index out of range I have this code:
string Str = "<String><MoreString>";
int Start = Str.LastIndexOf('<') + 1;
int End = Str.IndexOf('>', Start);
string S = Str.Substring(Start, End);

If Str is just "<String>", then it works fine, but if Str is "<String><MoreString>", then it throws an index out of range error. Is it because of the "<",">" characters?

A: Substring doesn't work like this.
Example :
String myString = "abc";
bool test1 = myString.Substring(2, 1).Equals("c"); // This is true.

The second argument is the number of characters you're going to select, so you should do :
string S = Str.Substring(Start, End-Start);

A: As you can see when you hover over the Str.Substring function you see that the second argument of this function is length
This will work
string Str = "<String><MoreString>";
int Start = Str.LastIndexOf('<') + 1;
int End = Str.IndexOf('>', Start);
string S = Str.Substring(Start, End - Start);

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to evaluate the following sum if $n$ is an even number? In a mathematical physical problem, the sum below needs to be calculated:
$$
F_n(\xi) =
 \sum_{k=0}^{\operatorname{ceil} \left(\frac{n}{2}-1 \right)} (-1)^k \frac{\xi^{2k}}{n-2k}
=
 \begin{cases}
  \qquad\qquad\qquad\qquad\qquad\qquad ? & \text{if $n$ is even} \, , \\
  (-1)^{\frac{n-1}{2}} \xi^{n-1} \Big( 1+\frac{1}{2} \Phi \left( -\xi^2,1,-\frac{1}{2} \right) \Big) - \frac{1}{2} \Phi \left( -\xi^2, 1, -\frac{n}{2} \right) & \text{if $n$ is odd} \, ,
 \end{cases}
$$
wherein $\xi$ is a positive real number.
Here, $\operatorname{ceil}(x)$ denotes the ceiling function, which maps a variable $x$ to the least integer greater than or equal to $x$.
Accordingly,
$$
\operatorname{ceil}\left( \frac{n}{2}-1 \right)=
\begin{cases}
\frac{n}{2}-1 & \text{if $n$ is even} \, , \\
\frac{n-1}{2} & \text{if $n$ is odd} \, .
\end{cases}
$$
When $n$ is an odd number, it turned out that the sum can conveniently be expressed in terms of the Lerch transcendent function.
However, when $n$ is even, i have no idea how to evaluate the sum.
It would be highly appreciated if someone here could try to be of help and let me know whether an analytical evaluation is possible. Any hint would be most welcome!

A: If $n=2m$, Maple says the sum is
$$
-{\frac { \left( -{\xi}^{2} \right) ^{m}}{2\;m} \left( \ln  \left( {
\frac {{\xi}^{2}+1}{{\xi}^{2}}} \right) m+ \left( {\xi}^{2} \right) ^{
-m} \left( -1 \right) ^{m} \left( {\it LerchPhi} \left( -{\xi}^{-2},1,
m \right) m-1 \right)  \right) }
$$


text:
Q: WordPress: Pass variable on page change I'm trying to find the most efficient way to do the following.

*

*I have a page which shows a selection of projects. There are 2 possible views: a list and a map.

*When the user clicks on "map", the list disappears and the map appears. This is all done in JavaScript, so there is not page reload.

*The user can filter projects by category. When he changes the category, the page reloads. I have fiddled with doing it in JavaScript (so there wouldn't be any reload), but the reload is important since when want different pages with different URLs for each catagory.

*When the user changes the category (hence, the page reloads), I want to be able to retrieve the previous display state selected, list or map.

Which would be to most efficient way to go? How should I store the value so I can retrieve it on the next page load? Global var, cookie?
Thank you!

A: i uess your best option would be to use ajax to load the content based on users selection and toggle the map and list views according without reloading the page. This will allow you to retain all selected values.


text:
Q: OpenCV python 3.7 handle cv2.VideoCapture(0) asynchronously I am new to python and openCV. I hope this question makes sense. I want to use a asyncio/multithreading in python in order process cv2.VideoCapture(0) in openCV asynchronously.
The reason: I can only create one cv2.VideoCapture(0) object and I cannot copy it - as far as I know. Here the errors I got.

TypeError: cannot pickle 'cv2.VideoCapture' object

TypeError: 'cv2.VideoCapture' object is not subscriptable

First I want to show the video capturing by the PCs cam in a window:
cap = cv2.VideoCapture(0)
def one():
        while cv2.waitKey(1) < 0:
        hasFrame, frame = cap.read()
        cv2.imshow('Capturing1', frame)

While I process the same frames in a different function:

def two():
    while cv2.waitKey(1) < 0:
        hasFrame, frame = cap.read()
        frameWidth = frame.shape[1]
        frameHeight = frame.shape[0]

        inpBlob = cv2.dnn.blobFromImage(frame, 1.0 / 255, (inWidth, inHeight),
                                        (0, 0, 0), swapRB=False, crop=False)

        net.setInput(inpBlob)
        output = net.forward()

        H = output.shape[2]
        W = output.shape[3]
        # Empty list to store the detected keypoints
        points = []
        for i in range(nPoints):
            threshold = 0.1
            # confidence map of corresponding body's part.
            probMap = output[0, i, :, :]

            # Find global maxima of the probMap.
            minVal, prob, minLoc, point = cv2.minMaxLoc(probMap)

            # Scale the point to fit on the original image
            x = (frameWidth * point[0]) / W
            y = (frameHeight * point[1]) / H

            if prob > threshold:
                # cv2.circle(frameCopy, (int(x), int(y)), 8, (0, 255, 255), thickness=-1, lineType=cv2.FILLED)
                # cv2.putText(frameCopy, "{}".format(i), (int(x), int(y)), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2, lineType=cv2.LINE_AA)

                # Add the point to the list if the probability is greater than the threshold
                points.append((int(x), int(y)))
                print(points)
            else:
                points.append(None)

I want to do this, because the
 cv2.imshow('Capturing1', frame)

in def one() is slown down by the code in def two() if I would combine those two functions in one.
Many thanks for help. I hope it makes sense to you.

A: You don't have to copy VideoCapture and probably you couldn't use two copies to read camera because only one VideoCapture can access camera.
You can use threads to run two or more processes at the same time - and because threads share memory so you don't have to use queue or pickle to send frame from one thread to another.
You can create one VideoCapture in main thread and use one thread to read frame and other threads to run few processes which create few frames, but GUI (displayng  frame) you have to run in main thread.
import cv2
import threading
import time

# --- functions ---

def read_frame():
    global has_frame
    global frame

    while running:
        has_frame, frame = cap.read()
        #time.sleep(.1)  # 0.1s to use less CPU

def one():
    global frame1

    while running:
        if has_frame:
            # processing frame
            frame1 = frame.copy()
            frame1 = cv2.putText(frame1, "One: fast process", (10, 30), cv2.FONT_HERSHEY_PLAIN, 2, (255, 255, 255))
        time.sleep(.1)  # 0.1s to use less CPU

def two():
    global frame2

    while running:
        if has_frame:
            # processing frame
            frame2 = frame.copy()
            frame2 = cv2.putText(frame2, "Two: slow process", (10, 30), cv2.FONT_HERSHEY_PLAIN, 2, (255, 255, 255))
            # simulate long running code
            time.sleep(2)
        time.sleep(.1)  # 0.1s to use less CPU

#--- main ---

# - init ---

# create variables at start with default values
has_frame = False
frame = None   # original frame from camera

frame1 = None  # frame after processing
frame2 = None  # frame after processing

cap = cv2.VideoCapture(0)  # create only one access to camera

# - create threads -

t0 = threading.Thread(target=read_frame)
t1 = threading.Thread(target=one)
t2 = threading.Thread(target=two)

# - start threads -

running = True  # use in threads to stop loops

t0.start()
t1.start()
t2.start()

# - GUI has to be in main thread -

while cv2.waitKey(100) != 27:  # ESC  # 100ms to use less CPU

    if frame1 is not None:
        cv2.imshow('Capturing1', frame1)

    if frame2 is not None:
        cv2.imshow('Capturing2', frame2)

    #time.sleep(.1)  # 0.1s to use less CPU

# - stop threads -

running = False

t0.join()
t1.join()
t2.join()

# - quit -

cv2.destroyAllWindows()
cap.release()

EDIT: Author of cv2 created also class to run VideoCapture in separated Thread.
from imutils.video import WebcamVideoStream

See details in Increasing webcam FPS with Python and OpenCV no PyImageSearch.com


text:
Q: SQL SUM enquiry So I'm new to SQL/self taught and I have built the below code, (i know its ugly but its a combination of google/stack over flow/me mucking through it, I need to SUM the "inforce, submitted,  and deferred, under assessment defined in the #step4 in separate column, i have been running in circles all day, so if anyone can answer that would be cool. I'M getting NULL  from the SUM line other steps work fine.
SELECT DISTINCT #step1.staff_user_id,
                #step1.PBUID,
                #step1.staff_Branch,
                #step1.create_time,
                #step2.UserFullName,
                #step2.PositionName,
                Isnull(#step2.KBDepartmentName, 'Franchise') kb2,
                #step2.USERID                                AS userid2,
                #step2.EmployeeStatus,
                #step2.dss_current_flag,
                #step3.KBDivisionName,
                Sum(#step4.Inforce)                          AS Inforce,
                Sum(#step4.Submitted)                        AS Submitted,
                Sum(#step4.deferred)                         AS Deferred,
                Sum(#step4.[Under Assessment])               AS UnderAssessment
FROM   #step1
       LEFT JOIN #STEP2
              ON #step1.staff_user_id = #step2.UserId
       LEFT JOIN #STEP3
              ON #step1.staff_user_id = #step3.UserId
       LEFT JOIN #step4
              ON #step1.staff_user_id = #step4.Staff_user_Name
WHERE  #step2.dss_current_flag = 'Y'
       AND #step2.employeestatus = 'Active'
GROUP  BY #step1.staff_user_id,
          #step1.PBUID,
          #step1.staff_Branch,
          #step1.create_time,
          #step2.UserFullName,
          #step2.PositionName,
          Isnull(#step2.KBDepartmentName, 'Franchise'),
          #step2.USERID,
          #step2.EmployeeStatus,
          #step2.dss_current_flag,
          #step3.KBDivisionName


text:
Q: One step ahead forecast on test data using holtwinters I want to train holt model on training data, and then make a forecast on test data without estimating parameters again. On several sites I found this solution, but for ARIMA model:
library(forecast)
m_train <- holt(rnorm(500)+runif(500))
m_test <- holt(rnorm(100), model = m_train)
m_train$model
m_test$model

but when I look at the print I can see that smoothing parameters are different for both models.


text:
Q: Method Interception using Reflection in C# I wrote an abstract class that uses reflection to find fields marked with an Attribute in the constructor, like this:
[AttributeUsage(AttributeTargets.Field)]
public class TrackedField : Attribute {}

public class ATrackedObject {
    public ATrackedObject() {
        Type objType = this.GetType();
        foreach(FieldInfo f in objType.GetFields()) {
            if(f.IsDefined(typeof(TrackedField)), false)) {
                //Add field to list to keep tabs on periodically
            }
        }
    }
}

What I would like to do, is:

*

*Create another attribute, TrackedMethod

*In the constructor, in the
same fashion as with the TrackedFields, find all methods tagged with
TrackedMethod

*Change the method so that when it gets called, a
method inside ATrackedObject gets called first or instead, either by
replacing the method entirely or by injecting code into it, but
without breaking the ability to at least see what the original
method call was, including parameters

*No third-party libaries, and should be .NET 3.5 compatible

I have seen a number of SE threads discussing how to do this, and all of the answers relied on being able to use a third party library - however, none of the questions seemed to match my use case exactly - I can ensure 100% that every object that needs to have methods tracked will inherit from the class that does the tracking.
I don't know for sure this is possible, but I am wondering since IoC/AOP libraries like PostSharp and others exist, surely they must operate by some kind of mechanism - I assume Reflection.Emit plays a part - but what, and how?
Here are some similar questions, which did not have what seemed to me to be answers to my specific scenario, or relied on third party libraries:
custom-attribute-to-process-info-before-a-method-is-called
how-do-i-intercept-a-method-call-in-c (this was helpful, but missing the crucial component of how to actually inject code
intercept-method-calls
Is there a way to make this technique (Attribute -> Base Class Constructor -> Reflection -> Method Interception) viable?

A: Could something like this work for what you need?
[AttributeUsage(AttributeTargets.Field)]
public class TrackedField : Attribute { }

public class ATrackedObject
{
    public ATrackedObject()
    {
        Type objType = this.GetType();
        foreach (FieldInfo f in objType.GetFields())
        {
            if (f.IsDefined(typeof(TrackedField), false)) {
                if (f.FieldType == typeof(Action))
                {
                    var currentValue = f.GetValue(this) as Action;
                    Action newValue = () =>
                    {
                        Console.WriteLine($"Tracking {f.Name}");
                        currentValue.Invoke();
                    };

                    f.SetValue(this, newValue);
                }
            }
        }
    }

    [TrackedField]
    public Action SomeMethod = () => Console.WriteLine("Some Method Called");
}

this is done with a simple Action property but it could be extended to use Func<>
edit: forgot to include usage and output.
usage:
static void Main(string[] args)
{
    var obj = new ATrackedObject();
    obj.SomeMethod();

    Console.Read();
}

output:
Tracking SomeMethod
Some Method Called


text:
Q: Bootstrap btn-group flex-wrap issue I'm having some trouble with a bootstrap form (using Bootstrap 4). I need my btn-group buttons to wrap when resizing. It works like a charm when adding flex-wrap BUT there's one problem : the bottom of my buttons are hidden.. And i can't understand why!
I've tried everything (adding padding all type of things) but i can't figure it out.
Here is a screenshot
And here is the code :

    Type de bien *

        <input type="radio" name="options" id="option1" autocomplete="off" checked> Maison

        <input type="radio" name="options" id="option2" autocomplete="off"> Appartement

        <input type="radio" name="options" id="option3" autocomplete="off"> Duplex

        <input type="radio" name="options" id="option3" autocomplete="off"> Triplex

        <input type="radio" name="options" id="option3" autocomplete="off"> Loft/Atelier

        <input type="radio" name="options" id="option3" autocomplete="off"> Hôtel Particulier

Anyone having an idea for how to fix this one?


text:
Q: 64bit centos m2crypto crash during load_key I'm trying to run m2crypto on 64 bit centos 5.6 and/or rhel 5.6. I've compiled python 2.6 and placed into a separate directory (necessary on centos/rhel). I've tried compiling m2crypto against the built-in openssl 0.9.8e as well as manually compiled 0.9.8e, and the behavior is the same. I've even tried epel's python26 and python26-m2crypto. It also crashes.

[root@ip-10-172-10-135 ~]# /usr/local/bin/python m2test.py
Segmentation fault

The code is:
from M2Crypto import EVP

file = './foo'
cert_priv_key = EVP.load_key(file)

The key foo (generated with openssl genrsa for this test):

-----BEGIN RSA PRIVATE KEY-----
MIIBOgIBAAJBAK/y+9J2tnTq0ZhesUV2BjtbY2ND+ZBsIPMACUCFGTbMS59JJ05e
0s2WVqb7ljvm/KsWtJ9qoqnljeaX64E9llECAwEAAQJABZOA0Zm7jJcIj3ioy5fC
+MybqMC1vxL+NFVS9b2CIA9p/f/F/FAZtSOL/+FvvccxnhNogB+J4VMXTbbEURn0
5QIhANceLguDtazhDyjj+tVyIvGrkOfPEUs3lNWpiVABYea7AiEA0WMvE+SImzug
Tj+PSDf2puHQqvoBFz9qJ+5pcT1EVGMCIHOMx4jx162kOqNpSnxK0dBkqvKJfK2d
jnnylkp+Y5svAiBbH4f4Z0eQDvXnt796VWiRHcr67YwV+vIO6LGYp2oaMwIhAKBc
ig+JAHsT9R5Gq9TZ67YcdfI4LHFdswXw/e7eBCs4
-----END RSA PRIVATE KEY-----

This same test works on 32bit (and of course our application uses this a lot). Perhaps I've compiled python or openssl with the wrong options for 64 bit. Both have shared libs enabled and installed, added to ldconfig, etc.
Anyone have any hints? Has anyone successfully run python26+m2crypto on 64bit?

A: Turns out this is an issue with the version of swig I was using to compile m2crypto. I was using something on the order of swig-1.3.29-2.el5. Upgrading to the latest swig and recompiling m2crypto fixes the issue. See for reference https://bugzilla.redhat.com/show_bug.cgi?id=707676

A: For Centos5 I did the following:
cd /tmp/
mkdir rpmbuild
cd rpmbuild/
wget http://downloads.sourceforge.net/project/swig/swig/swig-1.3.40/swig-1.3.40.tar.gz?r=http%3A%2F%2Fsourceforge.net%2Fprojects%2Fswig%2Ffiles%2Fswig%2Fswig-1.3.40%2F&ts=1356897393&use_mirror=ignum
tar xzvf swig-1.3.40.tar.gz
cd swig-1.3.40
./configure
make
make install
yum info swig
/usr/local/bin/swig -version
mv /usr/bin/swig /usr/bin/swig-1.3.29
cd /usr/bin/
ln -s /usr/local/bin/swig

Then in the next step entered my virtualenv dir, activated it, removed all M2crypto-eggs from the site-packages. Then downloaded the m2crypto sources via yum, untar-ed it, entered the dir, and executed the ./fedora_setup.py. That's it. Done.
No dependency problems occured with the latest Centos5 updates.


text:
Q: How to add multiple editable fields in page layout in SP 2013 (office 365) How can I place multiple page content fields so I can edit them from Web Interface...? I tried copy pasting snippet from gallery but content in both fields are same (from second field)
For testing purposes, I have created two columns (in a table row) in Page Layout. Now I want to put different text in both fields. Both texts should be editable through the browser. I'd place page content field twice but as I said the content is same. Please help me I m new in SharePoint.
Editing

After Editing

A: This is pretty simple, use below steps.

*

*Add site column "MyColumn". You can do this step through SPD2013 or portal.

*Add this column to Pages library. Use Portal to do this.

*Add the internal name of this column "MyColumn" to field reference of copied snippet.

For #3
There will be FieldName attribute in copied snippet (Just find FieldName="{guid value}"). You only need to change it to FieldName="MyColumn"

A: The easiest way is to change the Field Namevalue under the Misc heading in the Customization - Page Field section in the snippets gallery.  Hit Update and copy the new snippet.


text:
Q: I am implementing react-google-recaptch v2 in my form-builder , but it is not responsive for smaller screens I am using react-google-recaptcha v2 , in my form builder but it is not responsive for small device screen as you can see in my image , can anybody knows how to resolve this issue reagarding responsiveness of react-google-captcha v2.
I tried using all css , that I can apply but unable to make is responsive.
I am expecting a solution for this problem.


text:
Q: How can I have one android app send a message to another to start it up in android O? Before android O, I was able to trigger the functionality of a second sister-app based on the action of a first app. I did this by sending the second app an intent that was defined as a broadcast receiver in the second app. All as well.
But apparently as of api 26, any broadcast receivers defined in the manifest that aren't particular system ones (ie, app specific ones like mine) get ignored. I get errors in the logcat to that effect, I forget the details.
The only way I can think to get this to work is to have the second app start on boot (that broadcast receiver still seems to work) and have it start a service that installs a broadcast receiver programatically, and the service keeps enough of the app alive to receive those messages.
I haven't tried that yet because that seems like overkill and very resource intensive just to receive an intent to do something.
Is there any other mechanism to make this work?
Thanks.

A:
But apparently as of api 26, any broadcast receivers defined in the manifest that aren't particular system ones (ie, app specific ones like mine) get ignored

Not true. You're misunderstanding the restriction.
As of API 26, you can no longer receive implicit broadcasts with a Manifest-declared receiver. However, explicit broadcasts are exempt.
Target the receiver explicitly in your Intent:
Intent intent = new Intent("my_action");
intent.setComponent(new ComponentName("com.sister.packagename", "com.sister.packagename.Receiver");
sendBroadcast(intent);

You'll obviously need to use your own action and the proper package/class name, but that will allow you to keep your Manifest-defined receiver.
Make sure you're checking the action in that receiver's onReceive() method, though. By sending an explicit broadcast, Android ignores your intent filter and sends the intent anyway.


text:
Q: Brownian bridge expectation Let $X_t=B_t-tB_1$, where $B_t$ represents standard Brownian motion for $0\leq t\leq 1$. For $0\leq s<t\leq 1$, find $$\mathbb{E}(X_s|X_t=1).$$
So, here's what I thought. We have $X_t=1$, so $B_t-tB_1=1$, which means that $B_1=\frac{1}{t}(B_t-1)$. Then, our expression becomes $$\mathbb{E}(B_s-sB_1|B_1=\frac{1}{t}(B_t-1))=\mathbb{E}(B_s|B_1=\frac{1}{t}(B_t-1))-s\mathbb{E}(B_1|B_1=\frac{1}{t}(B_t-1)).$$
The second term is easy to solve, it becomes $-\frac{s}{t}(B_t-1)$. What about the first term? I am suspecting that $\mathbb{E}(B_s|B_1=\frac{1}{t}(B_t-1))=\frac{s}{t}(B_t-1)$ using some kind of binomial, but I can't justify this. Is this approach correct?

A: Can you please check if the following works? I have left it in term of $B_1$

We will assume a weiner process for the brownian motion with $B_{t+1} - B_t \sim \mathcal N(0,1) \forall t$
\begin{align*}
X_t &= B_t-tB_1\\
X_{t-\Delta t} &= B_{t-\Delta t}-(t-\Delta t)B_1\\
X_t - X_{t-\Delta t} &= B_t - B_{t-\Delta t}-\Delta t B_1\\
X_{t-\Delta t} &= X_t + \Delta t B_1 - (B_t - B_{t-\Delta t})\\
\mathbb E [X_{t-\Delta t} |X_t = 1] &= \mathbb E [X_t + \Delta tB_1 - (B_t - B_{t-\Delta t}) |X_t = 1]\\
&= 1 + \Delta t B_1 + \mathbb E (B_t - B_{t-\Delta t}) |X_t = 1]\\
&= 1 + \Delta t B_1 \\
\end{align*}
The last equality is by using the fact that the brownian motion is a weiner process with gaussian increments.
We can rewrite this in terms of $s$
\begin{align*}
\mathbb E [X_{s} |X_t = 1] &= 1+(t-s)B_1
\end{align*}

A: Let's decompose
$$X_s=B_s -sB_1 = \left( B_s - \frac{s}{t}B_t \right)+ \frac{s}{t}\left(B_t-tB_1 \right)$$
We have $\left( B_s - \frac{s}{t}B_t \right) = \left(1-\frac{s}{t}\right)B_s-\frac{s}{t}(B_t-B_s)$ and $(B_t-tB_1)=(1-t)B_t-t(B_1-B_t)$; so both follow normal distribution. Besides,
\begin{align}Cov( B_s - \frac{s}{t}B_t,B_t-tB_1)& =s-ts-\frac{s}{t}t+\frac{s}{t}t\times t= 0
\end{align}
Then $\left( B_s - \frac{s}{t}B_t \right)$and $\left(B_t-tB_1 \right)$ are independant. We deduce that
$$E(B_s - \frac{s}{t}B_t |B_t-tB_1)=0$$
Hence,
\begin{align}
E(X_s|X_t) &= E\left( \left( B_s - \frac{s}{t}B_t \right)+ \frac{s}{t}\left(B_t-tB_1 \right) |B_t-tB_1\right)\\
&= E\left( B_s - \frac{s}{t}B_t |B_t-tB_1\right)+E\left(\frac{s}{t}\left(B_t-tB_1 \right)|B_t-tB_1\right)\\
&= \frac{s}{t}(B_t-tB_1) \\
&=\frac{s}{t}X_t \\
\end{align}
We deduce the particular case
$$E(X_s|X_t = 1) = \frac{s}{t}$$

A: $(X_s)_{0\le s\le 1}$ is a Gaussian process with $\Bbb E[X_s] =0$ and $\Bbb E[X_sX_t]=s(1-t)$ for $0\le s\le t\le 1$. Consequently, if we choose $c=s/t$ then the covariance of $X_s-cX_t$ and $X_t$ is $0$, so $X_s-cX_t$ and $X_t$ are independent! With this choice, the conditional distribution of $X_s=(X_s-cX_t) +cX_t$, given that $X_t=x$, is normal with mean $cx$ and variance that of $X_s-cX_t$, namely $s(1-s)+c^2t(1-t)-2cs(1-t) = s(1-s/t)$.


text:
Q: std::map allocation node packing? I have noticed that the std::map implementation of Visual Studio (2010) allocates a new single block of memory for each node in its red-black tree. That is, for each element in the map a single new block of raw memory will be allocated via operator new ... malloc with the default allocation scheme of the std::map of the Visual Studio STL implementation.
This appears a bit wasteful to me: Wouldn't it make more sense to allocate the nodes in blocks of "(small) n", just as std::vector implementations over-allocate on growth?
So I'd like the following points clarified:

*

*Is my assertion about the default allocation scheme actually correct?

*Do "all" STL implementations of std::map work this way?

*Is there anything in the std preventing a std::map implementation from putting its nodes into blocks of memory instead of allocation a new block of memory (via its allocator) for each node? (Complexity guarantees, etc.)?

Note: This is not about premature optimization. If its about optimization, then its about if an app has problem with (std::)map memory fragmentation, are there alternatives to using a custom allocator that uses a memory pool? This question is not about custom allocators but about how the map implementation uses its allocator. (Or so I hope it is.)

A: Your assertion is correct for most implementations of std::map.
To my knowledge, there is nothing in the standard preventing a map from using an allocation scheme such as you describe.  However, you can get what you describe with a custom allocator — but forcing that scheme on all maps could be wasteful.  Because map has no a priori knowledge of how it will be used, certain use patterns could prevent deallocations of mostly-unused blocks.  For example, say blocks were allocated for 4 nodes at a time, but a particular map is filled with 40 nodes, then 30 nodes erased, leaving a worst case of one node left per block as map cannot invalidate pointers/references/iterators to that last node.

A: When you insert elements into a map, it's guaranteed that existing iterators won't be invalidated.  Therefore, if you insert an element "B" between two nodes A and C that happen to be contiguous and inside the same heap allocated area, you can't shuffle them to make space, and B will have to be put elsewhere.  I don't see any particular problem with that, except that managing such complexities will swell the implementation.  If you erase elements then iterators can't be invalidated either, which implies any memory allocation has to hang around until all the nodes therein are erased.  You'd probably need a freelist within each "swollen node"/vector/whatever-you-want-to-call-it - effectively duplicating at least some of the time-consuming operations that new/delete currently do for you.

A: I'm quite certain I've never seen an implementation of std::map that attempted to coalesce multiple nodes into a single allocation block. At least right offhand I can't think of a reason it couldn't work, but I think most implementors would see it as unnecessary, and leave optimization of memory allocation to the allocator instead of worrying about it much in the map itself.
Admittedly, most custom allocators are written to deal better with allocation of a large number of small blocks. You could probably render the vast majority of such optimization unnecessary by writing map (and, of course, set, multiset, and multimap) to just use larger allocations instead. OTOH, given that allocators to optimize small block allocations are easily/common/widely available, there's probably not a lot of motivation to change the map implementation this way either.

A: I think the only thing you cannot do is to invalidate iterators, which you might have to do if you have to reallocate your storage. Having said that, I've seen implementations using single sorted array of objects wrapped in the std::map interface. That was done for a certain reason, of course.
Actually, what you can do is just instantiate your std::map with you custom allocator, which will find memory for new nodes in a special, non-wasteful way.

A:
This appears a bit wasteful to me. Wouldn't it make more sense to allocate the nodes in blocks of "(small) n", just as std::vector implementations over-allocate on growth

Interestingly I see it in a completely different way. I find it is appropriate and it doesn't waste any memory. At least with defaul STL allocators on Windows (MS VS 2008), HP-UX (gcc with STLport) and Linux (gcc without STLport). What is important is that these allocators do care about memory fragmentation and it seems they can handle this question pretty well. For example, look for Low-fragmentation Heap on Windows or SBA (Small block allocator) on HP-UX. I mean that frequently allocating and deallocating memory only for one node at a time doesn't have to result in memory fragmentation. I tested std::map myself in one of my programs and it indeed didn't cause any memory fragmentation with these allocators.

Is my assertion about the default
  allocation scheme actually correct?

I have MS VisualStudio 2008 and its std::map behaves in the same way. On HP-UX I use gcc with and without STLport and it seem that their STL maps have the same approach to allocating memory for nodes in the std::map.

is there anything in the std
  preventing a std::map implementation
  from putting its nodes into blocks of
  memory instead of allocation a new
  block of memory (via its allocator)
  for each node?

Start with tuning a default allocator on your platform if it is possible. It is useful here to quote the Douglas Lea who is an author of DL-Malloc

... first I wrote a number of
  special-purpose allocators in C++,
  normally by overloading operator new
  for various classes. ...
However, I soon realized that building
  a special allocator for each new class
  that tended to be dynamically
  allocated and heavily used was not a
  good strategy when building kinds of
  general-purpose programming support
  classes I was writing at the time.
  (From 1986 to 1991, I was the the
  primary author of libg++ , the GNU C++
  library.) A broader solution was
  needed -- to write an allocator that
  was good enough under normal C++ and C
  loads so that programmers would not be
  tempted to write special-purpose
  allocators except under very special
  conditions.

Or as a little bit more difficult idea you can even try to test your application with Hoard allocator. I mean just test your application and see if there is any benefit as for performance or fragmentation.


text:
Q: How to autowire a property which has no beans defined, using @Autowired DI on constructor? I have an EquityOrder class consisting of List of Equity and a String as its properties. A method "placeOrder" is also defined. I have autowired my constructor and beans for Equity have been defined in my XML file.
@Autowired
public EquityOrder(String name, List<Equity> equity) {
    this.name = name;
    this.equity = equity;
}

public void placeOrder() {

    for (Equity eq : equity)
        System.out.println("Placing order for " + eq.getSecurityName()
                + "with quantity " + eq.getQuantity());
}

In the xml I have below scenario, which is error free.
<context:annotation-config />
<bean name="testEquity" class="com.sapient.Spring.Equity.Equity">

    <property name="symbol" value="MSFT"></property>
    <property name="securityName" value="Microsoft"></property>
    <property name="type" value="IT"></property>
    <property name="quantity" value="100"></property>

</bean>

<bean name="testOtherEquity" class="com.sapient.Spring.Equity.Equity">

    <constructor-arg value="GOOG">
    </constructor-arg>
    <constructor-arg value="Google"></constructor-arg>
    <constructor-arg value="IT"></constructor-arg>
    <constructor-arg value="100"></constructor-arg>

</bean>

<bean name="testEquityOrder" class="com.sapient.Spring.Equity.EquityOrder">
</bean>

Issue - when in the constructor I have no String, then the project runs fine. But if the constructor has the String in it, it throws exception as -
Error creating bean with name 'testEquityOrder' defined in class path resource
[SpringConfig.xml]: Unsatisfied dependency expressed through constructor argument with
index 0 of type [java.lang.String]: : No matching bean of type [java.lang.String] found
for dependency: expected at least 1 bean which qualifies as autowire candidate for this
dependency. Dependency annotations: {}; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of
type [java.lang.String] found for dependency: expected at least 1 bean which qualifies
as autowire candidate for this dependency. Dependency annotations: {}

which means the container is looking for String bean but it can not be there. How to solve this issue. One way is to use annotation on setter. But how to do it using the @Autowire annotation on Constructor? Thanks

A: You can provide value for the name attribute using the <constructor-arg> element as follows:
<bean name="testEquityOrder" class="com.sapient.Spring.Equity.EquityOrder">
    <constructor-arg value="dummyValue" />
</bean>

The other constructor argument anyway gets autowired as it's a bean already defined.
P.S. Also, I must say that EquityOrder appears to be a data object and unless it is some configuration data, it shouldn't be injected/autowired like this if it depends on the user input.


text:
Q: lighttpd rewrite-once rule isn't working I just got some problems serving static files via Lighttpd.
Here's what I would want to do:
www.example.ch is my domain.
If a call comes to www.example.ch/static/.....css
then I want to reroute it and actually serve the file from static.example.ch/files/....css (see my url.rewrite-once rule).
Somehow this just doesn't work. Am I missing something completely?
$HTTP["host"] =~ "(^|\.)example\.ch$" {
fastcgi.server = (
    "/django.fcgi" => (
        "main" => (
            "socket" => env.HOME + "/webqs/webqs.sock",
            "check-local" => "disable",
        )
    ),
)
alias.url = (
    "/media" => env.HOME + "/webqs/media",
)

url.rewrite-once = (
    "^(/media.*)$" => "$1",
    "^/favicon\.ico$" => "/media/favicon.ico",
    "^(/static.*)$" => "http://static.example.ch/files/$1",
    "^(/.*)$" => "/django.fcgi$1",
)
}

A: Given the regular expression "^(/static.*)$" it looks like $1 is going to contain /static/...css. Is there a static/ directory under your files/ directory? If not, try changing the regular expression to something like:
"^/static/(.*)$"

This should match everything after /static/ but won't also include the string /static/.


text:
Q: eBPF bcctools get contents from tracepipe This is small program that traces communication in tracepipe. My question is how do I access the contents of tracepipe using bcctools.
I tried manually reading the file using fopen but that does not work, is there any function I am not aware of?
Modified  #define KBUILD_MODNAME "filter"
#include <linux/bpf.h>
#include <linux/if_ether.h>
#include <linux/ip.h>
#include <linux/in.h>
#include <linux/udp.h>

#include <linux/if_packet.h>
#include <linux/if_vlan.h>

int udpfilter(struct xdp_md *ctx) {
  bpf_trace_printk("got a packet\n");
  void *data = (void *)(long)ctx->data;
  void *data_end = (void *)(long)ctx->data_end;
  struct ethhdr *eth = data;
  if ((void*)eth + sizeof(*eth) <= data_end) {
    struct iphdr *ip = data + sizeof(*eth);
    if ((void*)ip + sizeof(*ip) <= data_end) {
      if (ip->protocol == IPPROTO_UDP) {
        struct udphdr *udp = (void*)ip + sizeof(*ip);
        if ((void*)udp + sizeof(*udp) <= data_end) {
          if (udp->dest == ntohs(7999)) {
            bpf_trace_printk("udp port 7999\n");
            udp->dest = ntohs(7998);
          }
        }
      }
    }
  }
  return XDP_PASS;
}

A: To display the output from the trace pipe, you can simply use:
bpftool prog tracelog

Note however that the trace pipe is only meant for debugging. If you check your system logs, you'll notice a big warning whenever you use bpf_trace_printk. Instead you should use the perf ring buffer.


text:
Q: Using ADF for REST API authentication using client certificate We want to call a REST API endpoint of a SaaS application. i.e. system to system interaction.
We are using Azure Data Factory to call and we could see that ADF support(Web client activity) client certificate authentication.
We have the certificate with us. Added the certificate to AKV, configured ADF to use the certificate.
Question:

*

*Do we need an app registration to be able to use?

*What details do we need to send to the SaaS vendor so that they can recognize that our call is a legit call?

*Are there any other steps in the process?

A: From the way you're describing this issue, it sounds like the SaaS isn't an application that is protected using Azure AD.  In that case, the SaaS determines what credentials are suitable - likely a username and client certificate.  I can't think of a reason for you to need to create an app registration.  All of this said - you need to talk to the vendor to ask them what credentials are necessary for access.


text:
Q: count result output don't show if result is zero Count multiple column using the following query:
select count(price) as a ,count(buy_price) as b from table where c=1

if a or b one of result are zero then that column don't show. suppose count(price) as a output is 0 and count(buy_price) as b is 10 then output will be:
b
10

A: First and foremost, your query should look like this:
select count(price) as a, count(buy_price) as b from table where c=1

Note the comma (",") between ...as a and count(buy_price)....
In general, you should have commas separating the fields in your projection, e.g.:
select field1, field2, field3 from myTable

If you really want both fields to appear in your result set, you'll need to use the built-in IFNULL function:
select COUNT(IF(price=0,1,price)) as a, COUNT(IF(buy_price=0,1,buy_price)) as b from table where c=1


text:
Q: Github does not display a font defined in a SVG I've got an SVG file with a font defined like this:
<defs>
    <style>
      @font-face {
        font-family: "Virgil";
        src: url("https://somedomain.com/somefont.woff2");
      }
    </style>
</defs>

I want to add this SVG to a markdown file stored on Github. So I uploaded the SVG and added the image link to the markdown file. Now Github displays the markdown with the image just fine except the font. Github displays some default font instead of somefont.woff2 specified in SVG.
Am I missing something ? How can I fix the issue ?
The font URL -- https://somedomain.com/somefont.woff2 -- works fine for me in my computer.


text:
Q: How to compare 2 textures in JavaScript / WebGL2? I am writing a fragment shader for an image processing algorithm. The shader will run multiple times between two framebuffers in a loop (ping-pong). At some point I need to stop the loop when input and output textures are identical.
What I intend to do is the last step of Canny edge detector algorithm, "hysterezis edge tracking". I want to make a real time GPU/WebGL2 version of Canny algorithm and upload it to a web site.
This last step is as follows:
Given a double thresholded image containing "strong" edge pixels (1.0) and "weak" edge pixels (0.5)

*

*find all chains of weak pixels connected with a strong pixel and mark them "strong"

*keep all "strong" pixels and discard all remaining "weak" ones.
This can be implemented in a fragment shader running multiple times in a loop. The current "weak" pixel is marked "strong" if there is at least one strong pixel in its 8-pixel neighbourhood. At every iteration, we should have more strong pixels and less weak pixels. At the end, only isolated chains of weak pixel should remain. This is the point where the fragment shader becomes a pass-through shader and should be detected to stop the loop.
Update Sept 2019: I uploaded the GPU Canny Edge Detector here http://www.oldrinb.info/dip/canny/ . It works in browsers with WebGL2 support, as well in browsers that support WebGL1 and 'WEBGL_draw_buffers' extension. I'll put also the source code to github shortly.

A: I'm not 100% sure what you're asking. You're asking to compare on the CPU. You can read the contents of a texture by attaching it to a framebuffer and then calling gl.readPixels. you can then compare all the pixels. Note: not all texture formats can be attached to a framebuffer but assuming you're using a format that can. You've already attached textures to framebuffers for your ping-ponging so what more did you want?
Like I wrote in the comment on the GPU you can write a shader to compare 2 textures
#version 300 es
precision highp float;

uniform sampler2D tex1;
uniform sampler2D tex2;

out vec4 outColor;

void main() {
  ivec2 size = textureSize(tex1, 0);  // size of mip 0
  float len = 0.0;
  for (int y = 0; y < size.y; ++y) {
    for (int x = 0; x < size.x; ++x) {
      vec4 color1 = texelFetch(tex1, ivec2(x, y), 0);
      vec4 color2 = texelFetch(tex2, ivec2(x, y), 0);
      vec4 diff = color1 - color2;
      len = length(diff);
      if (len > 0.0) break;
    }
    if (len > 0.0) break;
  }
  outColor = mix(vec4(0), vec4(1), step(len, 0.0));
}

now just draw 1 pixel and read it with readPixels. if it's 0 the textures are the same. If it's not they are different.
The code assumes the textures are the same size but of course if they aren't the same size then we already know they can't be the same.

// make 3 canvaes as sources for textures
const canvases = ['A', 'B', 'B'].map((msg) => {
  const canvas = document.createElement('canvas');
  canvas.width = 128;
  canvas.height = 128;
  const ctx = canvas.getContext('2d');
  ctx.fillStyle = 'blue';
  ctx.fillRect(0, 0, 128, 128);
  ctx.font = '80px monospace';
  ctx.textAlign = 'center';
  ctx.textBaseline = 'middle';
  ctx.fillStyle = 'yellow';
  ctx.fillText(msg, 64, 64);
  document.body.appendChild(canvas);
  return canvas;
});

const gl = document.createElement('canvas').getContext('webgl2');
if (!gl) { alert('need webgl2'); }

const vs = `#version 300 es
void main() {
  gl_PointSize = 1.0;
  gl_Position = vec4(0, 0, 0, 1);
}
`;

const fs = `#version 300 es
precision highp float;

uniform sampler2D tex1;
uniform sampler2D tex2;

out vec4 outColor;

void main() {
  ivec2 size = textureSize(tex1, 0);  // size of mip 0
  float len = 0.0;
  for (int y = 0; y < size.y; ++y) {
    for (int x = 0; x < size.x; ++x) {
      vec4 color1 = texelFetch(tex1, ivec2(x, y), 0);
      vec4 color2 = texelFetch(tex2, ivec2(x, y), 0);
      vec4 diff = color1 - color2;
      len = length(diff);
      if (len > 0.0) break;
    }
    if (len > 0.0) break;
  }
  outColor = mix(vec4(0), vec4(1), step(len, 0.0));
}
`;

// compile shaders, link program, look up locations
const programInfo = twgl.createProgramInfo(gl, [vs, fs]);

const textures = canvases.map((canvas) => {
  // gl.createTexture, gl.bindTexture, gl.texImage, etc.
  return twgl.createTexture(gl, {src: canvas});
});

compareTextures(0, 1);
compareTextures(1, 2);

function compareTextures(ndx1, ndx2) {
  gl.useProgram(programInfo.program);

  // gl.activeTexture, gl.bindTexture, gl.uniform
  twgl.setUniforms(programInfo, {
    tex1: textures[ndx1],
    tex2: textures[ndx2],
  });

  // draw the bottom right pixel
  gl.viewport(0, 0, 1, 1);

  gl.drawArrays(gl.POINTS, 0, 1);  // draw 1 point

  // read the pixel
  const result = new Uint8Array(4);
  gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, result);

  console.log('textures', ndx1, 'and', ndx2, 'are', result[0] ? 'the same' : 'not the same');
}
canvas { padding: 5px; }
<script src="https://twgljs.org/dist/4.x/twgl.min.js"></script>

You could also use occlusion queries. The plus is they might not block the GPU where as readPixels does. The minus is you can't check them in the same JavaScript event so they might not fit your needs

// make 3 canvaes as sources for textures
const canvases = ['A', 'B', 'B'].map((msg) => {
  const canvas = document.createElement('canvas');
  canvas.width = 128;
  canvas.height = 128;
  const ctx = canvas.getContext('2d');
  ctx.fillStyle = 'blue';
  ctx.fillRect(0, 0, 128, 128);
  ctx.font = '80px monospace';
  ctx.textAlign = 'center';
  ctx.textBaseline = 'middle';
  ctx.fillStyle = 'yellow';
  ctx.fillText(msg, 64, 64);
  document.body.appendChild(canvas);
  return canvas;
});

const gl = document.createElement('canvas').getContext('webgl2');
if (!gl) { alert('need webgl2'); }

const vs = `#version 300 es
void main() {
  gl_PointSize = 1.0;
  gl_Position = vec4(0, 0, 0, 1);
}
`;

const fs = `#version 300 es
precision highp float;

uniform sampler2D tex1;
uniform sampler2D tex2;

out vec4 outColor;

void main() {
  ivec2 size = textureSize(tex1, 0);  // size of mip 0
  float len = 0.0;
  for (int y = 0; y < size.y; ++y) {
    for (int x = 0; x < size.x; ++x) {
      vec4 color1 = texelFetch(tex1, ivec2(x, y), 0);
      vec4 color2 = texelFetch(tex2, ivec2(x, y), 0);
      vec4 diff = color1 - color2;
      len = length(diff);
      if (len > 0.0) break;
    }
    if (len > 0.0) break;
  }
  if (len > 0.0) {
    discard;
  }
  outColor = vec4(1);
}
`;

// compile shaders, link program, look up locations
const programInfo = twgl.createProgramInfo(gl, [vs, fs]);

const textures = canvases.map((canvas) => {
  // gl.createTexture, gl.bindTexture, gl.texImage, etc.
  return twgl.createTexture(gl, {src: canvas});
});

function wait(ms = 0) {
  return new Promise((resolve) => {
    setTimeout(resolve, ms);
  });
}

async function test() {
  await compareTextures(0, 1);
  await compareTextures(1, 2);
}
test();

async function compareTextures(ndx1, ndx2) {
  gl.clear(gl.DEPTH_BUFFER_BIT);
  gl.enable(gl.DEPTH_TEST);
  gl.useProgram(programInfo.program);

  // gl.activeTexture, gl.bindTexture, gl.uniform
  twgl.setUniforms(programInfo, {
    tex1: textures[ndx1],
    tex2: textures[ndx2],
  });

  // draw the bottom right pixel
  gl.viewport(0, 0, 1, 1);

  const query = gl.createQuery();
  gl.beginQuery(gl.ANY_SAMPLES_PASSED, query);
  gl.drawArrays(gl.POINTS, 0, 1);  // draw 1 point
  gl.endQuery(gl.ANY_SAMPLES_PASSED);
  gl.flush();

  let ready = false;
  while(!ready) {
    await wait();
    ready = gl.getQueryParameter(query, gl.QUERY_RESULT_AVAILABLE);
  }

  const same = gl.getQueryParameter(query, gl.QUERY_RESULT);

  console.log('textures', ndx1, 'and', ndx2, 'are', same ? 'the same' : 'not the same');
}
canvas { padding: 5px; }
<script src="https://twgljs.org/dist/4.x/twgl.min.js"></script>


text:
Q: Python private class variables that aren't class variables When trying to access __variables from a class, the parser assumes the 2 underscores are private relative to the current class. Notice how an unrelated function gets a "private" variable.
Is this a bug?

>>> def f(): pass
...
>>> class A:
...     def g(self):
...             f.__x = 1
...             def h():
...                     pass
...             h.__y = 2
...             return h
...
>>> z = A().g()
>>> dir(z)
['_A__y', '__call__', '__class__', '__delattr__', '__dict__', '__doc__', '__get_
_', '__getattribute__', '__hash__', '__init__', '__module__', '__name__', '__new
__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'func_
closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals',
 'func_name']
>>> dir(f)
['_A__x', '__call__', '__class__', '__delattr__', '__dict__', '__doc__', '__get_
_', '__getattribute__', '__hash__', '__init__', '__module__', '__name__', '__new
__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'func_
closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals',
 'func_name']

Tested on python 2.5 and 3.2

A: This is a well documented behavior.

This mangling is done without regard to the syntactic position of the identifier, as long as it occurs within the definition of a class.

A: Here's a way to declare private variables: overload the __setattr__ (and other many methods about attributes) method, in the method, you can check current executing method is in the own class. If it is true, let it pass. Otherwise, you can raise an exception, or you can use your own customize error handle logic. (Tips: use inspect.stack function)


text:
Q: MainActivity does not receive result from StartActivityForResult I have the following common problem, easy, yet I don't know what more I can do.
I have the MainActivity that starts for result AnotherActivity.
In the MainActivity I have (extends Activity):
Intent i = new Intent(MainActivity.this, Altele.class);
startActivityForResult(i, 0);
...

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    Toast something; //toast NOT showing
    webview.loadUrl(data.getStringExtra("adresa"));
}

In the AnotherActivity I have (extends ListActivity):
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    Toast something; //toast showing
    Intent intentMessage = new Intent();
    intentMessage.putExtra("adresa", something);
    setResult(RESULT_OK, intentMessage);
    finish();
}

Now, whatever I do, the data from AnotherActivity doesn't seem to reach the MainActivity. In this sample here, I skipped on purpose the requestCode and resultCode since it's the same thing. So what I have here, is basically all over the internet, but to me it doesn't work. Any ideas?
Source code: http://www3.zippyshare.com/v/13090519/file.html
UPDATE
i've noticed a thing. if i start my second activity for result as soon as the application starts, it's onActivityResult in the main activity gets triggered. if i wait 2 seconds after application's start or try again running the second activity for result, nothing happens anymore.

A: You are doing a "putExtra" and trying to get a "getStringExtra". You should either use "putStringExtra" or "getExtra".

A: May be you can try this one
startActivityForResult(i, **2**);

.
.
.
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
  super.onActivityResult(requestCode, resultCode, intent);
    switch (requestCode) {
     case **2**:
        toast something;//toast NOT showing
        webview.loadUrl(data.getStringExtra("adresa"));
     break;
    }
}

In the list view You can change it as
setResult(0, (new Intent()).setAction(i.getStringExtra("String")));

A: What you have done seems to be correct. I have tried and it works for me.. I am sharing sample code I have written. Hope this helps.
My MainActivity
import android.os.Bundle;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity implements android.view.View.OnClickListener{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button b1 = (Button)findViewById(R.id.button1);
        b1.setOnClickListener(this);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        System.out.println("abcd");
        Toast.makeText(this, data.getStringExtra("abc"), Toast.LENGTH_LONG).show();
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        if(v.getId() == R.id.button1){
             Intent in = new Intent(MainActivity.this,MainActivity1.class);
             startActivityForResult(in, 1);
        }

    }

}

My MainActivity1 which extends ListActivity
It works very fine and prints out put in ddms and also toast message
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity1 extends ListActivity{

    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
            "Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
            "Linux", "OS/2" };
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, values);
        setListAdapter(adapter);
      }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        // TODO Auto-generated method stub
        super.onListItemClick(l, v, position, id);
        Intent intentMessage=new Intent();
        intentMessage.putExtra("abc","def");
        setResult(RESULT_OK,intentMessage);
        finish();
    }

}

A: Make sure your manifest file doesn't contain singletask for the activity you are starting from.

A: May these help you..
Instead of using INTENT to pass data between your activity try to use SharedPreference
It can store data and data can be retrieved easily..
Hope these will help you..

A: A late answer, but probably useful at someone. I had the same problem, when I noticed that in the definition of MainActivity in AndroidManifest.xml file I had the line
android:noHistory="true"

The problem disappeared when I correct this line to
android:noHistory="false"

In fact you may also delete the whole line (see this link)
Hope this will work also for you.


text:
Q: Android Studio - Button opens new activity I want to make an onclick listener so that when I touch the start button on the home page it will lead me to disclaimer. I have read many answers but I still have some problems with it.
I have declared my new activity in the manifest:
 <activity
            android:name=".Disclaimer"
            android:label="@string/title_activity_disclaimer" >
        </activity>

This is how my start button looks like in the page:
<Button
    android:layout_width="100dp"
    android:layout_height="50dp"
    android:text="START"
    android:id="@+id/button"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true" />

And this is my main activity:
public class Home extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        Button btn = (Button)findViewById(R.id.open_activity_button);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(Home.this, Disclaimer.class));
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_home, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

One of the problems is that it cannot resolve symbol open_activity_button. Any ideas how I can resolve that?

A: You're <Button>'s andorid:id attribute should be
<Button
    ...
    android:id="@+id/open_activity_button"

That's why R.id.open_activity_button isn't generated and the compiler complains about not being able to find that. Alternatively, you can change your onCreate() code to
Button btn = (Button) findViewById(R.id.button);

A: In your code make the changes

*

*Your first & second activity is not extending Activity Class(Instead of ActionBarActivity)

*Also override OnCreate() activity of second activity.

*Also include the button in first activity by taking the ID.
ex.In first Activity, private Button btnname;(In activity)
now in onCreate(),btnname=(Button)findViewById(R.id.buttonid);
and then on click of btnname give the code to move for second activity.

Refer this for an example
Moving from one activity to another Activity in Android


text:
Q: The act of making rolls of dough Bakers (usually) take small pieces of dough off much bigger dough that they already prepared before starting shaping it in a way they want like spreading or scoring it. I found a picture that might help. In Persian, we call it چانه گرفتن. What's it called in english?

A: Assuming the dough has already risen (and is past the final proof):
I would call this the divide and pre-shape step.
It is the step before final shaping.  In this step you divide the dough into smaller balls.  (image from bakerpedia.com)

A: Shaping.
tr.v. shaped, shap·ing, shapes
    1. To create or fashion, as:
        a. To give a particular form to (a material): shape the dough into baguettes.


text:
Q: Face API DetectAsync Error I wanted to create a simple program to detect faces using Microsoft Azure Face API and Visual Studio 2015. Following the guide from (https://social.technet.microsoft.com/wiki/contents/articles/37893.c-face-detection-and-recognition-with-azure-face-api.aspx), whenever my program calls UploadAndDetectFaces:
private async Task<Face[]> UploadAndDetectFaces(string imageFilePath)
{
    try
    {
        using (Stream imageFileStream = File.OpenRead(imageFilePath))
        {
            var faces = await faceServiceClient.DetectAsync(imageFileStream,
                true,
                 true,
                 new FaceAttributeType[]
                 {
                     FaceAttributeType.Gender,
                     FaceAttributeType.Age,
                     FaceAttributeType.Emotion
                 });
            return faces.ToArray();
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
        return new Face[0];
    }
}

I also declared the keys to the endpoint:
private readonly IFaceServiceClient faceServiceClient = new FaceServiceClient("MY_KEY_HERE");

an error returns:

"Exception of type 'Microsoft.ProjectOxford.Face.FaceAPIException' was thrown."

Does anyone know what's wrong or any changes required to prevent the error?

A: Change the key and endpoint declaration to:
private readonly IFaceServiceClient faceServiceClient = new FaceServiceClient("MY_KEY_HERE", "ACTUAL_ENDPOINT_HERE");


text:
Q: How to retain textbox value after click submit button I have a search text box after click in submit button textbox value is retain, but when i reload the page the textbox value still in a text box, how do i remove the value of text box after reloading/refreshing the page.
<script>
    $(document).ready(function(){
    document.getElementById("text1").value = localStorage.getItem("item1");
        });

   $(window).on('beforeunload', function() {
    localStorage.setItem("item1",document.getElementById("text1").value);
  });
</script>

Html.
<td>
<form action="/searchemp" method="post" >
    Selected Employee <input type="text"  name="EmployeeName" id="text1">
                     <input type ="submit" value="check">
</form>

Give me a help or suggestion to fix it.
Thank you.

A:         $(document).ready(function () {
            $("#form1").submit(function () {
                window.localStorage['text1_val'] = $("input[name = 'text1']").val();
            });
            $(window).load(function () {
                $("input[name = 'text1']").val(window.localStorage['text1_val']);
                window.localStorage['text1_val'] = '';
            });
        });

  <form id="form1" method="post">
    <input type="text" name="text1">
    <input type="submit">
  </form>

A: By default a textbox value is empty at page loading.
I guess your problem is due to storing and fetching the value from the local storage.
The code responsible for the text appearance
$(document).ready(function(){
    document.getElementById("text1").value = localStorage.getItem("item1");
});

A: Why don't you clear the localstorage?
$(window).unload(function() {
    window.localStorage.removeItem(item1);
});

Code is not tested, but this should give you an idea...


text:
Q: Angular 9 - Routing - Stack History (Clear) is it possible with angular 9 routing to manage a scenarious as described below?
There are three page (A, B and C). The user enters in the page A (this is a registration page), then he inserts registration data and he enters in the second page (B) where he must insert a confirmation code. I  would like that from this page the user can go forward (page C) and clear history (page a and b not more accessible with back function), but he can go back on the page A. Is this possible?
A -> B -> C [When in C, A e B not more available]
A -> B -> A [When in B, i can go back in A]
Thanks in advance.

A: There're multiple ways to do this. Two of them are mentioned below:

*

*You will manipulate the history manually with the native browser location.history API.

*Create a service with a rxjs/subject that contains the isRoute data. Instantiate it in the next page (after B). Check the data & perform the route.

Personally, I would prefer the 2nd one. To do this:
1) Generate a service with you preferred name.
2) In the service, create a subject that will store the data of our route (isAllowed) (Initially set to true).
3) In your Page B access it as a private class variable in the constructor as well as the router for routing.
constructor(private service: ServiceName, private router: Router) {}

4) Check whether the value isAllowed is true or not by subscribing to the isAllowed subject. If not, route to the preferred component.
this.service.isAllowed.subscribe({isAllowed} => {
  isAllowed ? this.router.navigate("component path here") : false
})


text:
Q: Why do you use `stream` for GRPC/protobuf file transfers? I've seen a couple examples like this:
service Service{
  rpc updload(stream Data) returns (google.protobuf.Empty) {};
  rpc download(google.protobuf.Empty) returns (stream Data) {};
}

message Data { bytes bytes = 1; }

What is the purpose of using stream, does it make the transfer more efficient?
In theory - yes - I obviously wan't to stream my file transfers but that's what happens over a connection... So, what is the actual benefit to this keyword, does it enforce some form of special buffering to reduce some overhead? Either way, the data is being transmitted, in full!

A: It's more efficient because, within a single call, multiple messages may be sent.
This avoids, not only re-establishing another (hopefully TLS i.e. even more work) connection with the server but also avoids spinning up client and server "stubs"; both the client and server are ready for more messages.
It's somewhat similar to being connected on a telephone call with your friend who, before hanging up, says "Oh, another thing...". Instead of hanging up the call and then, 5 minutes later, calling you back, interrupting dinner and causing you to pause a movie.

A: The answer is very similar to the gRPC + Image Upload question, although from a different perspective.
Doing a large download (10+ MB) as a single response message puts strong limits on the size of that download, as the entire response message is sent and processed at once. For most use cases, it is much better to chunk a 100 MB file into 1-10 MB chunks than require all 100 MB to be in memory at once. That also allows the downloader to begin processing the file before the entire file is acquired which reduces processing latency.
Without streaming, chunking would require multiple RPCs, which are annoying to coordinate and have performance complications. Because there is latency to complete RPCs, for reasonable performance you either have to do many RPCs in parallel (but how many?) or have a large batch size (but how big?). Multiple RPCs can also hit colder application caches, as each RPC goes to a different backend.
Using streaming provides the same throughput as the non-chunking approach without as many headaches of normal chunking approaches. Since streaming is pipelined (server can start sending next chunk as soon as previous chunk is sent) there's no added per-chunk latency between the client and server. This makes it much easier to choose a chunk size, as there is a wide range of "reasonable" sizes that will behave similarly and the system will naturally react as network performance varies.
While sending a message on an existing stream has less overhead than creating a new RPC, for many users the difference is negligible and it is generally better to structure your RPCs in a way that is architecturally beneficial to your application and not just to eek out small optimizations in gRPC. The reason to use the stream in this case is to make your application perform better at lower complexity.


text:
Q: Prevent flushing the buffer How can I prevent the flushing of the buffer until the playing is finished in AS3?
Is it possible?
The buffer is emptied and flushed 10-11 seconds before the real end of the flv file.
The file is locally saved and I stream it though crtmp server.
I cannot seek the last 10 seconds because of empty buffer. How can I stop flash from flushing the buffer at end?

A: In case you create your own flash based player, I think you should use the proper signal handlers to signal end-of-stream.
Also, I'm not experiencing that problem. Just to test it, use JWPlayer or FlowPlayer and see if you can seek around. On my side, everything works as expected


text:
Q: where is .bash_profile in cloudera? I am unable to locate .bash_profile in cloudera machine. can anyone tell me what command do I use to find this file ?
i have tried
find -name ".bash_profile"

and nothing happen I just don't understand why. new to cloudera and linux command

A: .bash_profile might not exist by default then it's just a matter of creating it. Read useful information about .bash_profile & .profile here: https://superuser.com/questions/278433/whats-the-difference-between-profile-and-bash-profile-and-when-do-you-config


text:
Q: If current menu item is child or parent with child? Is it possible to check in WP if the current page/menu item is a child or a parent with child (in my wp_nav_menu)? So not if the page has a child page, but if the menu item is a parent with child or a child (based on my wp_nav_menu).

A: I agree with ialocin, if you can use the built-in nav menu css classes you should but if those aren't enough there's a nice little filter which can help with css classes. If you need something other than CSS classes you can use a Custom Walker ( as ialocin suggested ) and use the same logic as the function below.
Add some CSS Classes to WP Nav Menu
/** Custom `wp_nav_menu()` Classes **/
function add_class_to_wp_nav_menu( $classes, $item ) {

    if( hasChildren( $item->object_id ) ) {                     // hasChildren is a Custom Function
        array_push( $classes, 'has-children' );
    }

    if( 0 !== wp_get_post_parent_id( $item->object_id ) ) {     // 0 means there is no parent
        array_push( $classes, 'has-parent' );
    }

    return $classes;
}
add_filter( 'nav_menu_css_class', 'add_class_to_wp_nav_menu', 10, 2 );

/** Check if Page has Children **/
function has_children( $pid ) {
    $children = get_pages( "child_of={$pid}" );
    return ( $children );
}


text:
Q: Looking for short story about genius children Short Story in the 50's - 60's, children from women around world impregnated by a cloud drifting in space.
Protagonist notes it's easier for him to stay hidden as his IQ is under 150. I want to find his quote.

A: This sounds a bit like The Midwich Cuckoos by John Wyndham, though that's not a short story, but a full novel.
The small English town of Midwich is caught in some sort of a stasis field for a day, after which all women are suddenly pregnant. They give birth to about 60 children, who are all blond and have psychic abilities.
Other towns and communities around the world have experienced the same, in Australia, Russia, Mongolia, and in the Arctic.
There is an elderly villager (I think ex-military) whom The Children, as they're called, trust. And while they're noted for their intelligence, I don't recall him or any other protagonist noting anything about his own IQ.
There's no cloud drifting in space, either.

A: There are points of similarity to Children of the Atom, a fix-up novel by Wilmar H. Shiras.  The first story, "In Hiding", is fairly well-known and has been in a lot of sf children themed anthologies.  It was also in the Science Fiction Hall of Fame anthology.
The stories are about children around the world who are born super-intelligent, which fits with the OP's description.  But, the root cause is radiation caused mutation (hence the name of the novel) instead of a space cloud, so that would be a vote against it.  From Wikipedia

These children were born to workers caught in an explosion at an
atomic weapons facility, and orphaned just a few months after birth
when their parents succumbed to delayed effects from the blast.

The time frame is right, though.


text:
Q: Where to place 'this.setState in this case? I'm trying to make a page where you can click on a thumbnail, and get an enlarged version to display, using state. Got the state working just fine, but I get the error message Cannot read property 'setState' of undefined when trying to set it in an onClick on the thumbnails. I can understand why it doesn't really work like this, but having a hard time understanding exactly how to arrange things for it to work the way I intend it to. Here's the code in question:
const WorkThumb = ({work}) => (
  <Col xs={3} md={4}>
    <WorkImage src={work.metadata.image.imgix_url} onClick={this.setState({selected: work._id})} />
  </Col>
)

export default class ArtContent extends React.Component {

  constructor(props) {
    super(props);
    this.state = {selected: props.works[0]["_id"]};
  }

  render () {
    return (
      <Row>
        <Col xs={6}>
          <Row between="xs" center="xs" middle="xs">
            {this.props.works.map((work) => (
              <WorkThumb key={work._id} work={work} />
            ))}
          </Row>
        </Col>
        <Col xs={6}>
          <Selected src={this.props.works.filter((work) => (work["_id"] == this.state.selected))[0].metadata.image.imgix_url} />
        </Col>
      </Row>
    )
  }
}

All help appreciated.

A: You can't call setState on stateless component that should be a pure function (i.e. depends only on its arguments: no this context, no state, same input - same output). But you can pass a callback from its stateful parent
const WorkThumb = ({work, onSelect}) => (
  <Col xs={3} md={4}>
    <WorkImage src={work.metadata.image.imgix_url} onClick={() => onSelect(work)} />
  </Col>
)

export default class ArtContent extends React.Component {

  constructor(props) {
    super(props);
    this.state = {selected: props.works[0]["_id"]};
    this.selectWork = this.selectWork.bind(this)
  }

  selectWork(work) {
    this.setState(...)
  }

  render () {
    return (
      <Row>
        <Col xs={6}>
          <Row between="xs" center="xs" middle="xs">
            {this.props.works.map((work) => (
              <WorkThumb key={work._id} work={work} onSelect={this.selectWork} />
            ))}
          </Row>
        </Col>
        <Col xs={6}>
          <Selected src={this.props.works.filter((work) => (work["_id"] == this.state.selected))[0].metadata.image.imgix_url} />
        </Col>
      </Row>
    )
  }
}


text:
Q: For what $1\leq r\leq a$ does $\gcd(a,r)\mid b$? For what $1\leq r\leq a$ does $\gcd(a,r)\mid b$?
I am looking for an easy way to calculate these $r$ for any given $a$ and $b$.

A: If $(a,r)\mid b$ then, since $(a,r)\mid a$ automatically, the stronger claim $(a,r)\mid(a,b)$ is also satisfied, and the converse holds as well since $(a,b)\mid b$. That is, $(a,r)\mid b\iff (a,r)\mid(a,b)$.
The $1\le r\le a$ for which $(a,r)\mid(a,b)$ are $\{dc:~d\mid(a,b),~1\le c\le a/d,~(c,a)=1\} $.

A: Hint $\rm\ \  (a,r)\mid b \iff (a,r)\mid a,b \iff (a,r)\mid (a,b)$

A: Hint:
Case 1:
$a=a_1a_2..a_n$
$b=b_1b_2..b_n$
$\gcd(a,b)=1$
If you have $\gcd(a,r) | b \implies \gcd(a,r)=1$
For the other case, take $\gcd (a,b)=k$ and see how it works.
Then $a=nk$, and $b=mk$ (Where again $\gcd (m,n)=1$)
If $\gcd (a,r) |b \implies \gcd(a,r)=k$
The conditions for $r$ is $\gcd (a,r) =\gcd(a,b)$


text:
Q: simulate separate alpha map in glTF I have an existing 3D application that was developed back in the days of the ThreeJS r92 that made use of a separate alpha map to simulate holes cut in wooden panels. This allowed re-use of a high quality woodgrain texture across all models, while using easily compressible black and white images to create the 'holes' in the wooden panels.
Now that I have begun migration of the project to the current glTF format, I find that the base color and alpha map now have to be combined. The result for my project is that now each of 130+ wooden panels will need their own "wood grain + alpha" texture, rather than being able to share a single wood grain texture.
From all my research, it seems like there are no obvious options to this situation using glTF.. my question now is - does anyone know of ANY workaround using glTF that allows me to separate the base color texture from the alpha map texture?
At this point the best way ahead sadly seems to be to avoid glTF and go back to using ObjectLoader, which is a pain as the binary objects of glTF are a huge plus.

A: You could export the GLTF with only the base color. Once imported into Three.js, you can manually assign the black/white texture as the material's .alphaMap property.
// Fetch texture
const texLoader = new THREE.TextureLoader();
const alphaTexture = texLoader.load("path/to/alphaTexture");

gltfLoader.load("path/to/model", function(gltf){
    // Find the mesh you want to assign an alphaMap to
    const myMesh = gltf.getObjectByName("meshName");

    // Now just bind your texture to the alphaMap property
    myMesh.material.alphaMap = alphaTexture;
    myMesh.material.transparent = true;
});

The docs state that only the green channel is used so it doesn't have to be black and white.


text:
Q: End sox recording once silence is detected I'm writing a script that uses sox to record me talking.
Now I need sox to wait until it detects sound before it begins recording, and I do have that figured out. But I also need sox to exit once there has been silence for at least 3 seconds.
As it is now, I have to manually kill sox once I finish talking, otherwise sox just waits again until I talk some more, appending to the output file (That's not what I want).
Here is the command for recording I am using now:
rec /tmp/recording.flac rate 32k silence 1 0.1 3% -1 3.0 3%

Again, just to be clear, Sox should wait until I start talking, and then record until I stop talking, then the sox program should quit.

A: I tweaked the above ideas some more. It records forever, records all noise until (roughly) a second of silence is encountered. Then:

*

*Ensures two subdirectories are created

*Calculates two spectrographs of the recording - one before normalisation, and one after, and writes to datestamped folders.

*Writes the normalised one to a file to a datestamped folder.

*Plays the normalised file back, with two chirp .ogg files (back through voice operated CB Radio)

(Makes for a very handly little UHF / 2 metre echo repeater)

#!/bin/bash
while true; do
  rec buffer.ogg silence 1 0.1 5% 1 1.0 5%
  DATE=`date +%Y%m%d%H%M%S`
  DPATH=`date +%Y/%m/%d/`
  mkdir -p ./spectro/$DPATH
  mkdir -p ./voice/$DPATH
  echo Renaming buffer file to $DATE
  sox buffer.ogg -n spectrogram -x 300 -y 200 -z 100 -t $DATE.ogg -o ./spectro/$DPATH/$DATE.png
  sox buffer.ogg normbuffer.ogg gain -n -2
  sox normbuffer.ogg -n spectrogram -x 300 -y 200 -z 100 -t $DATE.norm.ogg -o ./spectro/$DPATH/$DATE.norm.png
  mv normbuffer.ogg ./voice/$DPATH/$DATE.ogg
  play pre.ogg ./voice/$DPATH/$DATE.ogg post.ogg
done

A: I found a kind of shaky way that sort of solves this problem.
I noticed that when silence is detected, sox naturally won't append anything more to the file until it hears more sound. So I decided I could try and take advantage of this fact.
First of all, I start up sox's sound recorder in the background:
rec /tmp/recording.flac rate 32k silence 1 0.1 3% -1 3.0 3% &

Next I get the PID of the recording process with: p=$!
Then I give the recording process a second to finish starting up, and then wait until the file starts to grow.

sleep 1
until [ "$var1" != "$var2" ]; do
    var1=`du "/tmp/recording.flac"`
    sleep 1
    var2=`du "/tmp/recording.flac"`
done

After this loop breaks, that means that sound has been detected. So now I create another loop to wait until data stops being appended to the file (This will happen once sox detects silence again).

echo "Sound Detected"
until [ "$var1" == "$var2" ]; do
    var1=`du "/tmp/recording.flac"`
    sleep 0.5
    var2=`du "/tmp/recording.flac"`
done

Now I just need to quit rec:

echo "Silence Detected"
kill $p

And that's it.
Here is the completed script:

rec /tmp/recording.flac rate 32k silence 1 0.1 3% -1 3.0 3% &
p=$!
sleep 1
until [ "$var1" != "$var2" ]; do
    var1=`du "/tmp/recording.flac"`
    sleep 1
    var2=`du "/tmp/recording.flac"`
done
echo "Sound Detected"
until [ "$var1" == "$var2" ]; do
    var1=`du "/tmp/recording.flac"`
    sleep 0.5
    var2=`du "/tmp/recording.flac"`
done
echo "Silence Detected"
kill $p

Now I would prefer a better, more stable way to do this, but this will have to work for now.

A: This listens forever, records only the last sounds until it hears one second of silence, then writes the file, timestamps it, and restarts:
#!/bin/bash
/usr/bin/sox -t alsa default /home/default/working/recording.wav silence 1 0.1 5% 1 1.0 5%
DATE=$(date +%Y%m%d%H%M%S)
mv /home/default/working/recording.wav /home/default/waiting/$DATE.recording.wav
/home/default/startrecord.sh

A: Remove the negative sign from your original command:
rec /tmp/recording.flac rate 32k silence 1 0.1 3% 1 3.0 3%

When the "below count" is negative, the silence command will trim all silences from the middle of the file. When it's positive, it trims silence from the end of the file.


text:
Q: RatingBar does not show 'numStars' stars The activity has a RecyclerView which consists of multiple card_layouts
A card_layout has a full ImageView and RatingBar.
I set the 'numStars' of RatingBar to show the maximum rating score
and use 'setRating' to set the actual rate within Java code.
However, the RatingBar does not have 'numStars' stars.
What did I do wrong?
Here is xml code of my RatingBar
 <RatingBar
        android:id="@+id/ratingBar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="top|left"
        android:isIndicator="true"
        android:numStars="5"
        android:scaleX="0.5"
        android:scaleY="0.5"
        android:theme="@style/RatingBar"
        android:transformPivotX="8dp"
        android:transformPivotY="8dp" />

I appreciate your help

A: Hi you can try numStars progrmatically using this syntax:
ratingbar.setNumStars(int numStars);
You can refer to this doc for other additional info on rating bar;
https://developer.android.com/reference/android/widget/RatingBar
If still the rating (stars) still not showing or rendering , you can try these steps:

*

*check the ratingbar container

*check your model holding the value for ratings

hope this helps


text:
Q: compactness property  I am a new user in Math Stack Exchange. I don't know how to solve part of this problem, so I hope that one of the users can give me a hand.
Let $f$ be a continuous function from $\mathbb{R}^{n}$ to $\mathbb{R}^{m}$ with the following properties:$A\subset \mathbb{R}^{n}$ is open then $f(A)$ is open. If $B\subset \mathbb{R}^{m}$ is compact then $f^{-1}(B)$ is compact.
I want to prove that $f( \mathbb{R}^{n}) $ is closed.

A: I've left some of the details to you, but here's the main outline.
Suppose that $f[\Bbb R^n]$ is not closed in $\Bbb R^m$. Then there is a point $p\in\operatorname{cl}f[\Bbb R^n]\setminus f[\Bbb R^n]$, and there is a sequence $\langle x_n:n\in\Bbb N\rangle$ in $f[\Bbb R^n]$ converging to $p$. Let $K=\{p\}\cup\{x_n:n\in\Bbb N\}$, and show first that $K$ is compact, so that $f^{-1}[K]$ is compact in $\Bbb R^n$. Now for each $n\in\Bbb N$ choose $y_n\in f^{-1}[K]$ such that $f(y_n)=x_n$, and consider the sequence $\langle y_n:n\in\Bbb N\rangle$. This is a sequence in the compact set $f^{-1}[K]$, so it has a convergent subsequence $\langle y_{n_k}:k\in\Bbb N\rangle$, say with limit $y$. What must $f(y)$ be? Why is this a contradiction?

A: Try another approach; show that the complement of $f(\mathbb{R}^n)$ is open.
This is trivial if the complement is empty, so suppose the complement is not empty, and choose $\hat y \notin f(\mathbb{R}^n)$. You want to show that there exists some $\epsilon>0$ such that the set $B(\hat y, \epsilon)$ also lies in the complement.
You can proceed by contradiction and generate a sequence of points  $y_k \in f(\mathbb{R}^n)$ that converge to $\hat y$.
Now consider the set $\{y_k\} \cup \{\hat y\}$. What properties does it have in relation to the second property above, and how does this lead to a contradiction?

A: Take $y \in \overline{f(\mathbb{R}^n)}$.
Let $B_\varepsilon = \{x | d(x,y) \leq \varepsilon\}$.
Now,
$\emptyset \neq B_\varepsilon \cap f(\mathbb{R}^n) = f\left(f^{-1}(B_\varepsilon)\right)$.
Because $f^{-1}(B_\varepsilon)$ is compact, $B_\varepsilon \cap f(\mathbb{R}^n)$,
as the image of a compact by $f$, is a decreasing sequence of nonempty compact sets.
Therefore,
$\bigcap_\varepsilon (B_\varepsilon \cap f(\mathbb{R}^n))$ is nonempty.
Now,
$\emptyset \neq \bigcap_\varepsilon (B_\varepsilon \cap f(\mathbb{R}^n))
\subset
\bigcap_\varepsilon B_\varepsilon = \{y\}$
implies that $y \in f(\mathbb{R}^n)$.
That is, $f(\mathbb{R}^n) = \overline{f(\mathbb{R}^n)}$.
By the way, the only "clopen" sets in $\mathbb{R}^m$ are $\emptyset$ and
$\mathbb{R}^m$. Since $f(\mathbb{R}^n)$ is not empty, we have that
$f(\mathbb{R}^n) = \mathbb{R}^m$.

A: I think that the most instructive proof is that of Proposition 5.3 of this file. Indeed, it shows that proper maps between locally compact topological spaces are always closed. This is a generalization of this discussion. I find it interesting since "standard" proofs tend to use sequences, and one might believe that everything might be lost without a metric.
By the way, a very nice corollary of the proposed exercise is that non-constant maps with the two properties are always surjective, since $f(\mathbb{R}^n)$ is connected.


text:
Q: Add text annotations to each data point in Holoviews plot In Bokeh I am able to add a text annotation to each point in my plot programmatically by using LabelSet. Below I give an example for a simple bar plot:
import numpy as np
import pandas as pd

# Make some data
dat = \
(pd.DataFrame({'team':['a','b','c'], 'n_people':[10,5,12]})
    .assign(n_people_percent = lambda x: (x['n_people']/np.sum(x['n_people'])*100)
        .round(1).astype('string') + '%')
)

dat

# Bar plot with text annotations for every bar
from bkcharts import show, Bar
from bkcharts.attributes import CatAttr
from bokeh.models import (ColumnDataSource, LabelSet)

source_labs = ColumnDataSource(data = dat)
p = Bar(data = dat, label = CatAttr(columns = 'team'), values = 'n_people')
labels = LabelSet(x = 'team', y = 'n_people',
    text = 'n_people_percent', source = source_labs)
p.add_layout(labels)
show(p)

However I am not sure how to achieve the same thing with Holoviews. I can make the same bar plot without the annotations very easily:
import holoviews as hv
hv.extension('bokeh')

p = hv.Bars(dat, kdims=['team'], vdims=['n_people'])
p

I can add a single text label adding an Overlay with the hv.Text element
p * hv.Text('a', 11, '37.0%')

But I have no idea how I can label each bar without explicitly calling hv.Text separately for every data point (bar). The problem seems to be that hv.Text does not accept a data argument like other elements e.g. hv.Bars, instead just x and y coordinates. My intuition would be that I should be able to do something like
p * hv.Text(dat, kdims=['team'], vdims=['n_people_percent'])

Any help with this appreciated!

A: Looks like this commit adds vectorized labels to hv.Labels, so try:
import holoviews as hv
hv.extension('bokeh')

p = hv.Bars(dat, kdims=['team'], vdims=['n_people'])
p * hv.Labels(dat, kdims=['team', 'n_people'], vdims=['n_people_percent'])


text:
Q: Form doesn't post without backslash at the end of action url Today i faced this strange problem and it's blowing my mind because i have no idea why is this happening,i have a form with this action http://localhost/wp/ but it doesn't work without the backslash at the end , i mean when the action is http://localhost/wp it doesn't work ,
let me show you with example :
<form action="<?php bloginfo("url"); ?>" method="post">
       <input type="text" name="example">
</form>

<?php
      var_dump( $_POST ); // will output an empty array
?>

but now we add a "/" to the end of action url it works, but i want it to work in both ways because i'm designing this website for a customer.
<form action="<?php bloginfo("url"); ?>/" method="post">
       <input type="text" name="example">
</form>

<?php
      var_dump( $_POST ); // will output array( "example" => "XXXX" )
?>

can anyone tell me what's wrong please!!
:: it's wordpress installed on XAMPP - Windows 8.1

A: When you use `http://localhost/wp/, this will execute any Apache default file in the directory /path/to/localhost/wp/. For example in the WordPress case index.php.
When you use http://localhost/wp, it is telling Apache to execute the file wp in the directory /path/to/localhost/.
So the two cases ask for two different things, with different results.
If you always want to run WordPress, modify your .htaccess file to always go to /localhost/wp/, even if the user didn't add the slash.


text:
Q: Can changes to a dll be made, while keeping compatibility with pre-compiled executables? We have a lot of executables that reference one of our dlls. We found a bug in one of our dlls and don't want to have to re-compile and redistribute all of our executables to fix it.
My understanding is that dlls will keep their compatibility with their executables so long as you don't change anything in the header file. So no new class members, no new functions, etc... but a change to the logic within a function should be fine. Is this correct? If it is compiler specific, please let me know, as this may be an issue.

A: Your understanding is correct. So long as you change the logic but not the interface then you will not run into compatibility issues.
Where you have to be careful is if the interface to the DLL is more than just the function signatures. For example if the original DLL accepted an int parameter but the new DLL enforced a constraint that the value of this parameter must be positive, say, then you would break old programs.

A: This will work.  As long as the interface to the DLL remains the same, older executables can load it and use it just fine.  That being said, you're starting down a very dangerous road.  As time goes by and you patch more and more DLLs, you may start to see strange behaviour on customer installations that is virtually impossible to diagnose.  This arises from unexpected interactions between different versions of your various components. Historically, this problem was known as DLL hell.
In my opinion, it is a much better idea to rebuild, retest, and redistribute the entire application.  I would even go further and suggest that you use application manifests to ensure that your executables can only work with specific versions of your DLLs. It may seem like a lot of work now, but it can really save you a lot of headaches in the future.

A: It depends
in theory yes, if you load the dll with with LoadLibrary and haven't changed the interface you should be fine.
If you OTOH link with the .dll file using some .lib stub there is no guarantee it will work.
That is one of the reasons why COM was invented.


text:
Q: How can I send an image (form-data file) with wp_remote_post? I have curl, which works:
$ch = curl_init();

$cfile = new CURLFile($_FILES['form_name']['tmp_name'], $_FILES['form_name']['type'], $_FILES['form_name']['name']);
$new_image = ["image" => $cfile];

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $new_image);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);

But when I trying to send form-data with wp_remote_post like:
$result = wp_remote_post($url, [
                        'headers' => ['Content-Type' => 'multipart/form-data'],
                        'body' => $new_image
                    ]);

I have 400 error in answer, and error in [body]:
[body] => {"status":"error","msg":"$_FILES[\u0027image\u0027] not found"}

How can I correctly sending an image with wp_remote_post?


text:
Q: change the uiview frame when it has some constraints There is a subview (UIView) on the main view, I want change the size of the subview (_test).
_test has two constraints:

*

*top space to main view: 20

*trailling space to main view: 136

When I want change the size of _test (subview),but this seems not work:
self._test.frame = CGRectMake(self._test.frame.origin.x + 10,
                              self._test.frame.origin.y,
                              self._test.frame.size.width - 10,
                              self._test.frame.size.height);

I think this is because constraints, but, how can I do that?

A:
_test has two constraints:
top space to main view: 20
trailling space to main view: 136

Well, there's your first problem. If this really is a generic UIView, then that is not enough constraints. If you are going to use constraints at all, you must completely determine both the position and the size of the view, and you are failing to do that. Thus, your constraints are invalid.
Once your constraints become valid, then indeed you will face the fact that you cannot set the position and size of the view by means of its frame. Setting the frame and using constraints are mutually exclusive! If you are going to position and size this thing using constraints, then to reposition or resize it you must change its constraints, not its frame.


text:
Q: Can I use @Entity @MappedSuperclass both? Idea is UserSummary contains few properties needed for general purpose. UserDetail contains all of users properties.
@Entity
@Table(name="user")
@MappedSuperclass
@Immutable
class UserSummary{}

@Entity
@Table(name="user")
class UserDetail extends UserSummary{}


text:
Q: Get Keys of an Array Error & Stream Conditions I want to get the keys from an array and put them into a List.
V[] values;
private List<K> getVals (){
 return  IntStream.range(arr.length/2,arr.length).filter(i-> arr[i]!=null && i%2==0 ).collect(Collectors.<K>toList());}

When I am compiling that code I get the error:
IntStream cannot be applied to the given types.

I knew, since it is an IntStream I get ints in my List, right? And my type is K, but even if don´t use generics, nothing changes.
2nd question:
I would like to know how it's possible to iterate over that array
and set Data on an specified index.
But with the condition that if on that index is already an value I recalculate the key.
Lets say I want to write something like:
if (arr[i]==0) {
    // do something and return
} else {
    // do something else and return
}

I don't get what's wrong here. I am using the same code as on some internetpages.

A: You are using the type K in your lambdas but the array has the type V. I don' know where these types come from in your cod, but obviously they are not compatible. To compile this, you should have V extends K.

A: For your first question,
List<K> getVals() {
    return IntStream.range(arr.length/2, arr.length)
        .filter(i -> arr[i] != null && i%2 == 0)
        .collect(Collectors.<K>toList());
}

This doesn't work because the output of filter is an IntStream, which doesn't have a single-arg collect method. If you want to collect to a List you need to convert the int values from the IntStream into objects of reference type. I don't know how you get a value of K from your array. Is K the element type of arr? If so, then you should use mapToObj like this:
List<K> getVals() {
    return IntStream.range(arr.length/2, arr.length)
        .filter(i -> arr[i] != null && i%2 == 0)
        .mapToObj(i -> arr[i])
        .collect(Collectors.<K>toList());
}

If this works, you probably don't need the type witness <K> in your Collectors.toList() call.
For your second question, you can conditionally set elements of an array using Arrays.setAll:
int[] arr = ... ;
Arrays.setAll(arr, i -> arr[i] == 0 ? compute() : arr[i]);

This is basically a shorthand for running an IntStream over the array indexes. In fact, that's how it's implemented.
Alternatively, you write out the IntStream over the array indexes, filter out indexes you don't want to assign, and do the assignment within forEach:
IntStream.range(0, arr.length)
    .filter(i -> arr[i] == 0)
    .forEach(i -> arr[i] = compute());