问:
How to sort pandas dataframe in a special way
Given a pandas dataframe

```<code>df = pd.DataFrame({'a': [1,2,3,4,5,6,7,8],
                   'b': [0,0,1,1,2,2,3,3]})
</code>```

How to sort it along the column b in such a way that it is rearranged as {0,1,2,3,0,1,2,3}.

I.e. the resulting dataframe is

```<code>1   0
3   1
5   2
7   3
2   0
4   1
6   2
8   3
</code>```

答:
Another solution, with quick benchmark:

```<code>pd.DataFrame(sorted(df.values.tolist(), key=lambda k: (k[0]%2==0, k[1])), columns=['a', 'b'])
</code>```

Prints:

```<code>   a  b
0  1  0
1  3  1
2  5  2
3  7  3
4  2  0
5  4  1
6  6  2
7  8  3
</code>```

Benchmark:

```<code>df = pd.DataFrame({'a': [1,2,3,4,5,6,7,8],
                   'b': [0,0,1,1,2,2,3,3]})

from timeit import timeit

def f1():
    return pd.DataFrame(sorted(df.values.tolist(), key=lambda k: (k[0]%2==0, k[1])), columns=['a', 'b'])

def f2():
    s = df.groupby('b').cumcount().sort_values(kind='mergesort')
    return df.loc[s.index]

def f3():
    return df.iloc[np.lexsort([df['b'], df.groupby('b').cumcount()])]

t1 = timeit(lambda: f1(), number=1_000)
t2 = timeit(lambda: f2(), number=1_000)
t3 = timeit(lambda: f3(), number=1_000)

print(t1)
print(t2)
print(t3)
</code>```

Prints (AMD 2400G/Ubuntu 18.04, Python 3.8.3, Pandas 1.0.3):

```<code>0.45131446300365496
2.2533202580088982
1.6977271080104401
</code>```

So solution with sorted() seems fastest.

EDIT: After around ~3000 elements the solution with np.lexsort starts to win.

Body:
Given a pandas dataframe

df = pd.DataFrame({'a': [1,2,3,4,5,6,7,8],
                   'b': [0,0,1,1,2,2,3,3]})

How to sort it along the column b in such a way that it is rearranged as {0,1,2,3,0,1,2,3}.

I.e. the resulting dataframe is

1   0
3   1
5   2
7   3
2   0
4   1
6   2
8   3

Body:
Another solution, with quick benchmark:

pd.DataFrame(sorted(df.values.tolist(), key=lambda k: (k[0]%2==0, k[1])), columns=['a', 'b'])

Prints:

   a  b
0  1  0
1  3  1
2  5  2
3  7  3
4  2  0
5  4  1
6  6  2
7  8  3

Benchmark:

df = pd.DataFrame({'a': [1,2,3,4,5,6,7,8],
                   'b': [0,0,1,1,2,2,3,3]})

from timeit import timeit

def f1():
    return pd.DataFrame(sorted(df.values.tolist(), key=lambda k: (k[0]%2==0, k[1])), columns=['a', 'b'])

def f2():
    s = df.groupby('b').cumcount().sort_values(kind='mergesort')
    return df.loc[s.index]

def f3():
    return df.iloc[np.lexsort([df['b'], df.groupby('b').cumcount()])]

t1 = timeit(lambda: f1(), number=1_000)
t2 = timeit(lambda: f2(), number=1_000)
t3 = timeit(lambda: f3(), number=1_000)

print(t1)
print(t2)
print(t3)

Prints (AMD 2400G/Ubuntu 18.04, Python 3.8.3, Pandas 1.0.3):

0.45131446300365496
2.2533202580088982
1.6977271080104401

So solution with sorted() seems fastest.

EDIT: After around ~3000 elements the solution with np.lexsort starts to win.


来源: stackexchange

答:
Here is a simpler version that worked for me.  It takes advantage of the fact that by default, the GUD window and IO window are dedicated.  So it's sufficient to just ask display-buffer to an existing window (since there is only one choice available).</p>

```<code>;; Ensure that all source files are opened in the same window when gdb
;; is running.
(add-to-list 'display-buffer-alist
         (cons 'gdb-source-code-buffer-p
           (cons 'display-buffer-use-some-window nil)))

(defun gdb-source-code-buffer-p (bufName action)
  "Return whether BUFNAME is a source code buffer and gdb is running."
  (let ((buf (get-buffer bufName)))
    (and buf
         (eq gud-minor-mode 'gdbmi)
         (with-current-buffer buf
           (derived-mode-p buf 'c++-mode 'c-mode)))))
</code>```

ContentLicense: CC BY-SA 3.0

Title: [emacs][gdb customization] How to display source-buffer in one window?

Body:
I have customized gdb windows in emacs. After it during debugging new source code opens in different windows. I'd like to see source code only in one window. My gdb customization is:

;     _____________________________________________________________________________________
;    |                                          |                                          |
;    |              BREAKPOINTS                 |                                          |
;    |__________________________________________|                                          |
;    |                                          |                                          |
;    |                 STACK                    |                                          |
;    |__________________________________________|                                          |
;    |                                          |                                          |
;    |                                          |                                          |
;    |                 LOCALS                   |                                          |
;    |                                          |                SOURCE CODE               |
;    |__________________________________________|                                          |
;    |                                          |                                          |
;    |                                          |                                          |
;    |                                          |                                          |
;    |                                          |                                          |
;    |                                          |                                          |
;    |                                          |                                          |
;    |                  GDB                     |                                          |
;    |                                          |__________________________________________|
;    |                                          |                                          |
;    |                                          |                                          |
;    |                                          |                    I/O                   |
;    |                                          |                                          |
;    |__________________________________________|__________________________________________|

(require 'gud)

; invoke
(global-set-key [f8] 'gdb)

; GDB layout
(defadvice gdb-setup-windows (after activate)
  (gdb-setup-my-windows)
)

(defun gdb-setup-my-windows ()
  (set-window-dedicated-p (selected-window) nil)
  (switch-to-buffer gud-comint-buffer)
  (delete-other-windows)
  (let
    ((win0 (selected-window))             ; breakpoints
     (win1 (split-window-horizontally
         (floor (* 0.5 (window-width)))))   ; source + i/o
     (win2 (split-window-vertically
         (floor (* 0.5 (window-body-height))))) ; gdb
     (win3 (split-window-vertically
        (floor (* 0.5 (window-body-height))))) ; locals
     (win4 (split-window-vertically
         (floor (* 0.6 (window-body-height))))) ; stack
    )
    (select-window win1)
    ; configurating right window
    (let
    ((winSrc (selected-window)) ; source
     (winIO (split-window-vertically (floor (* 0.9 (window-body-height))))) ; I/O
     )
      (set-window-buffer winIO (gdb-get-buffer-create 'gdb-inferior-io))
      (set-window-buffer
    winSrc
    (if gud-last-last-frame
     (gud-find-file (car gud-last-last-frame))
      (if gdb-main-file
       (gud-find-file gdb-main-file)
     (list-buffers-noselect))))
      (setq gdb-source-window winSrc)
      (set-window-dedicated-p winIO t)
   )

    (set-window-buffer win0 (gdb-get-buffer-create 'gdb-breakpoints-buffer))
    (set-window-buffer win3 (gdb-get-buffer-create 'gdb-locals-buffer))
    (set-window-buffer win4 (gdb-get-buffer-create 'gdb-stack-buffer))
    (select-window win2)
  )
)

; GDB variables
(setq gdb-many-windows t)
(setq gdb-show-main t)
(setq gdb-show-changed-values t)
(setq gdb-use-colon-colon-notation t)
(setq gdb-use-separate-io-buffer nil)
(setq gdb-delete-out-of-scope t)
(setq gdb-speedbar-auto-raise t)

The main screen is:
gdb screen after start

But when I started debugging then next source file opens in another window. See example bellow:
New source code  in gdb window

The example of application to reproduce is:

main.cpp

#include "classB.h"

int main()
{
  B *b = 0;
  b = new B();
  return 0;
}

classA.h

#ifndef CLASS_A_H
#define CLASS_A_H

class A
{
public:
  A();
};

#endif

classA.cpp

#include "classA.h"
#include <iostream>

A::A()
{
  std::cout << "Constructor A" << std::endl;
}

classB.h

#ifndef CLASS_B_H
#define CLASS_B_H

#include "classA.h"

class B : public A
{
public:
  B();
};

#endif

classB.cpp

#include "classB.h"
#include <iostream>

B::B() : A()
{
  std::cout << "Constructor B" << std::endl;
}

Makefile

SOURCES=main.cpp classA.cpp classB.cpp
TARGET=test
CXX_FLAGS=-g

.PHONY: all

all: $(TARGET)

$(TARGET): $(SOURCES)
    $(CXX) $(CXX_FLAGS) $^ -o $@

.PHONY: clean

clean:
    rm -vf $(TARGET)

Step to reproduce:

Run emacs

M-x gdb

gdb -i=mi test

In gdb command window run: start

run: next

run: step

My environment is: Ubuntu14.04, gdb - 7.7.1, emacs - 25.1.1.

I tried to use set-window-dedicated-p. But this is not solution for my problem.
I'm new in emacs, help me please, what is wrong in my configuration?

Body:
Here is a simpler version that worked for me.  It takes advantage of the fact that by default, the GUD window and IO window are dedicated.  So it's sufficient to just ask display-buffer to an existing window (since there is only one choice available).

;; Ensure that all source files are opened in the same window when gdb
;; is running.
(add-to-list 'display-buffer-alist
         (cons 'gdb-source-code-buffer-p
           (cons 'display-buffer-use-some-window nil)))

(defun gdb-source-code-buffer-p (bufName action)
  "Return whether BUFNAME is a source code buffer and gdb is running."
  (let ((buf (get-buffer bufName)))
    (and buf
         (eq gud-minor-mode 'gdbmi)
         (with-current-buffer buf
           (derived-mode-p buf 'c++-mode 'c-mode)))))

ContentLicense: CC BY-SA 4.0


问:
How to create user a service which takes JWT token and returns user object
I have 3 services

angular (frontend)

java (fapi)

java (backend, jpa)

Every user's request consists of header <Authentification> with a JWT Token(interceptor in angular) key.

How can I get user from this token, for example to create users page? Or will admin understand this is user or not?

I'm trying to save  Map(key,value) pairs (token,user) in my front, but this map deleted every time.

Do I need to create this Map in fapi? Or save token in database?

答:
When the user logs in, you can include the user's "username" along with the "token" as your response from the backend. Then you can save the {token, username} you receive from the backend into localStorage in your frontend

Sample:

```<code>// Response from backend--------------------
{
    "token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9",
    "username": "tester"
}

// Login service from frontend--------------------
login(user: User): Observable<User> {
    return this.http.post<User>('/login', user)
        .pipe(
            map(response => {
                localStorage.setItem('currentUser', JSON.stringify(response));
                return response;
            })
        );
}
</code>```

Then if you want to retrieve the {token, username} from your frontend:

```<code>const currentUser = JSON.parse(localStorage.getItem('currentUser'));
</code>```

Body:
When the user logs in, you can include the user's "username" along with the "token" as your response from the backend. Then you can save the {token, username} you receive from the backend into localStorage in your frontend

Sample:

// Response from backend--------------------
{
    "token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9",
    "username": "tester"
}

// Login service from frontend--------------------
login(user: User): Observable<User> {
    return this.http.post<User>('/login', user)
        .pipe(
            map(response => {
                localStorage.setItem('currentUser', JSON.stringify(response));
                return response;
            })
        );
}

Then if you want to retrieve the {token, username} from your frontend:

const currentUser = JSON.parse(localStorage.getItem('currentUser'));


问:
How to change a range of array with one value Javascript?
I have an array like below let's say

```<code>var myArray = ["1", "", "", "2","3","","","8"];
</code>```

And I want to fill each " " value with previous not null value

According to that expectation should be like below

```<code>var myArray = ["1", "2", "2", "2","3","8","8","8"];
</code>```

Here what I tried but didn't work

    var myArray = ["1", "", "", "2","3","","","8"];

    function myFunction() {
      let currentEl=myArray [0];
      let prevIndex=0;
      fruits.map((e,a)=>{
      if(e!="" && myArray[a-1]==""){
       currentEl=e;
       let interval=arrayGenerate(a-currentIndex-1,currentEl);
       fruits.splice(currentIndex-1, currentEl+1, interval);
       currentIndex=a;
      }
      })
    }
    function arrayGenerate(iteration,value){
      let arr=[];
      for(var i=0;i<iteration;i++){
      arr.push(value);
      }
      return arr;
    }

console.log(myArray)```

答:
I have done it like this. I loop over and awlays check the next element if its falsy and not the last element.

var myArray = ["1", "", "", "2","3","","","8"];

function fillArr(arr){
   for(let i = arr.length - 1; i >= 0; i--){
      if(!arr[i - 1] && i != arr.length){
         arr[i - 1] = arr[i];
      }
   }
   return arr;
}

let result = fillArr(myArray);

console.log(result);```

Body:
I have an array like below let's say

var myArray = ["1", "", "", "2","3","","","8"];

And I want to fill each " " value with previous not null value

According to that expectation should be like below

var myArray = ["1", "2", "2", "2","3","8","8","8"];

Here what I tried but didn't work

    var myArray = ["1", "", "", "2","3","","","8"];

    function myFunction() {
      let currentEl=myArray [0];
      let prevIndex=0;
      fruits.map((e,a)=>{
      if(e!="" && myArray[a-1]==""){
       currentEl=e;
       let interval=arrayGenerate(a-currentIndex-1,currentEl);
       fruits.splice(currentIndex-1, currentEl+1, interval);
       currentIndex=a;
      }
      })
    }
    function arrayGenerate(iteration,value){
      let arr=[];
      for(var i=0;i<iteration;i++){
      arr.push(value);
      }
      return arr;
    }

console.log(myArray)


问:
Salesforce number field default value to (highest number in a record) + 1
I'm new to Salesforce and I'm trying to make a field for an account number. It will be a unique number that increases. But I would like its default value to be an increment from the highest number of current records since I'm going to import data and those data have some unused account numbers in between.
For example, I have a data with account numbers: 1, 4, 10, 13, 14 -> then the next one's default value would be 14 + 1 = 15.

What's the simplest solution to this? I tried MAX(Account_Number) + 1, but it's not allowing me to use its own value.

答:
I had this issue once and solved it by setting the field as an auto-increment and then creating and deleting large quantities of records to reach my starting number.

If you are importing and want to retain the previous values, this will not work, unfortunately.

You can use a trigger or flow to populate the account number after a record is created.

For the quick and dirty, make a flow and call it from a process builder. If you have the ability to use sandbox and create a trigger, by all means.

Essentially, you would query the sObject with SORT BY AccountNumber__c DESC LIMIT 1 (or whatever the field is named) and access that highest value and increment it and use that to set the value of the record you are creating.

Makes sense?


问:
SSH: what is the difference between user:~ and user:#
I have come across someone who when using ssh after logging in uses the command 'cd /' as soon as they log in. I'm trying to find out what the difference is and cannot really find an answer anywhere. I have added a picture to hopefully clear up the exact thing I am looking for:
example

Sorry if this is a stupid question but it has been on my mind for a while now and I would like to know the difference.

Thank you

答:
cd / refers to change directory to root whereas cd ~ refers to change directory to the home directory, typically its path is /home/$USER/.

The Home directory can be understood as the files or directories which have read, write permission (755) to normal users whereas the root directory consists of files and directories which don't have access to normal users, however you can access them through super-user access (sudo privileges).


问:
Kotlin Channels usage difference between Send and Offer
Channels have two functions that allow us to send events into it.
Send and offer.

I would like to understand better the difference between both.

I have some statements I wanna check are true.

Send is a suspend function. What will make my code(not the thread) wait for it to finish. So it keep running after the event inside send was complete/cancelled. OR it will be suspend only until I can queue the event/receive it?

This means that, if I use send from one channel to another, the first channel will be block until the second can receive/queue?

If I have a Rendezvous Channel and it is already running something (on suspend for example, waiting API) and I offer a new even. This will make offer throws exception? Cause the channel is not receiving?

If you know any other main difference I would be glad to know.

Thanks in advance

答:
send suspends the coroutine it is invoked from while the channel being sent to is full.

send does not send from one channel to another one. When you invoke send you are sending an element to the channel. The channel then expects another block of code to invoke receive from a different coroutine.

In a RendezvousChannel the capacity is 0. This means that send always suspends waiting for a receive invocation from another coroutine. If you have invoked send on a RendezvousChannel and then use offer, offer will not throw an exception (it only does if the channel is closed), but rather it will return false if no balancing receive has been invoked on the RendezvousChannel after your initial send. This is because offer tries to immediately add the element to the channel if it doesn't violate its capacity restrictions.


问:
Rescale image and rotate image with only numpy array manipulation
I would like to rescale and rotate image which I transform to numpy array with Pillow library (Image.open(..))
But i can use only numpy array manipulation.
Any tip or article how to do that? Without use of cv etc.. </p>

答:
You can use PIL to resize and rotate like this</p>

```<code>from PIL import Image

img = Image.open('Your/image/path')
img_120 = img.rotate(120)
img_re = img.resize((width, hight), Image.ANTIALIAS)
</code>```

Body:
You can use PIL to resize and rotate like this

from PIL import Image

img = Image.open('Your/image/path')
img_120 = img.rotate(120)
img_re = img.resize((width, hight), Image.ANTIALIAS)


问:
iPhone 4 camera opacity
I was wondering if it is possible to set the opacity of the camera input? For example if I have layers underneath the camera I want to be shown through the camera layer..

I work with the camera like this:

```<code>- (void)addVideoPreviewLayer {
    [self setPreviewLayer:[[[AVCaptureVideoPreviewLayer alloc] initWithSession:[self captureSession]] autorelease]];
    [[self previewLayer] setVideoGravity:AVLayerVideoGravityResizeAspectFill];

}

- (void)addVideoInput {
    AVCaptureDevice *videoDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if (videoDevice) {
        NSError *error;
        AVCaptureDeviceInput *videoIn = [AVCaptureDeviceInput deviceInputWithDevice:videoDevice error:&error];
        if (!error) {
            if ([[self captureSession] canAddInput:videoIn])
                [[self captureSession] addInput:videoIn];
            else
                NSLog(@"Couldn't add video input");
        }
        else
            NSLog(@"Couldn't create video input");
    }
    else
        NSLog(@"Couldn't create video capture device");
}
</code>```

And fire it up by:

```<code>[self setCaptureManager:[[CaptureSessionManager alloc] init]];
[[self captureManager] addVideoInput];
[[self captureManager] addVideoPreviewLayer];
CGRect layerRect = [[[self view] layer] bounds];
[[[self captureManager] previewLayer] setBounds:layerRect];
[[[self captureManager] previewLayer] setPosition:CGPointMake(CGRectGetMidX(layerRect),
    CGRectGetMidY(layerRect))];
[[[self view] layer] addSublayer:[[self captureManager] previewLayer]];
</code>```

It is possible? And if yes, how can it be done?

答:
The previewLayer isn't composited like ordinary CALayers, so it's not surprising that changing its opacity doesn't work.

What you can try to do is use this code (http://developer.apple.com/library/ios/#qa/qa1702/_index.html) to capture the input from the camera in real-time, convert it to a UIImage, and stick that image into a UIImageView. I've found that with a session setting of AVCaptureSessionPresetMedium, you should be able to update your UIImageView at 20-30 fps, which may be sufficient for what you are trying to accomplish.

Title: iPhone 4 camera opacity

Body:
I was wondering if it is possible to set the opacity of the camera input? For example if I have layers underneath the camera I want to be shown through the camera layer..

I work with the camera like this:

- (void)addVideoPreviewLayer {
    [self setPreviewLayer:[[[AVCaptureVideoPreviewLayer alloc] initWithSession:[self captureSession]] autorelease]];
    [[self previewLayer] setVideoGravity:AVLayerVideoGravityResizeAspectFill];

}

- (void)addVideoInput {
    AVCaptureDevice *videoDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if (videoDevice) {
        NSError *error;
        AVCaptureDeviceInput *videoIn = [AVCaptureDeviceInput deviceInputWithDevice:videoDevice error:&error];
        if (!error) {
            if ([[self captureSession] canAddInput:videoIn])
                [[self captureSession] addInput:videoIn];
            else
                NSLog(@"Couldn't add video input");
        }
        else
            NSLog(@"Couldn't create video input");
    }
    else
        NSLog(@"Couldn't create video capture device");
}

And fire it up by:

[self setCaptureManager:[[CaptureSessionManager alloc] init]];
[[self captureManager] addVideoInput];
[[self captureManager] addVideoPreviewLayer];
CGRect layerRect = [[[self view] layer] bounds];
[[[self captureManager] previewLayer] setBounds:layerRect];
[[[self captureManager] previewLayer] setPosition:CGPointMake(CGRectGetMidX(layerRect),
    CGRectGetMidY(layerRect))];
[[[self view] layer] addSublayer:[[self captureManager] previewLayer]];

It is possible? And if yes, how can it be done?


问:
Have a problem on how to set a default class
In the shape.cpp I need set a default constructor for class Point, But I don't know how to do that.

Thanks

```<code>Point::Point(double _f, double _g){
    f = 1;
    g = 1;

}
Rectangle::Rectangle():Point(1, 1) {
    x = 1;
    y = 1;

}
Rectangle::Rectangle( Point q, double l, double w):x(l),y(w),Point(q) {
}

</code>```

答:
```<code>class Point{
    int f,g;
    public:
    Point();
};

Point::Point(){
    f = 1;
    g = 1;
}

int main(){
    Point *p = new Point() ;
}
</code>```

Body:
In the shape.cpp I need set a default constructor for class Point, But I don't know how to do that.

Thanks

Point::Point(double _f, double _g){
    f = 1;
    g = 1;

}
Rectangle::Rectangle():Point(1, 1) {
    x = 1;
    y = 1;

}
Rectangle::Rectangle( Point q, double l, double w):x(l),y(w),Point(q) {
}


问:
Fast nonzero indices per row/column for (sparse) 2D numpy array
I am looking for the fastest way to obtain a list of the nonzero indices of a 2D array per row and per column. The following is a working piece of code:

```<code>preds = [matrix[:,v].nonzero()[0] for v in range(matrix.shape[1])]
descs = [matrix[v].nonzero()[0] for v in range(matrix.shape[0])]
</code>```

Example input:

```<code>matrix = np.array([[0,0,0,0],[1,0,0,0],[1,1,0,0],[1,1,1,0]])
</code>```

Example output

```<code>preds = [array([1, 2, 3]), array([2, 3]), array([3]), array([], dtype=int64)]
descs = [array([], dtype=int64), array([0]), array([0, 1]), array([0, 1, 2])]
</code>```

(The lists are called preds and descs because they refer to the predecessors and descendants in a DAG when the matrix is interpreted as an adjacency matrix but this is not essential to the question.)

Timing example:
For timing purposes, the following matrix is a good representative:

```<code>test_matrix = np.zeros(shape=(4096,4096),dtype=np.float32)
for k in range(16):
    test_matrix[256*(k+1):256*(k+2),256*k:256*(k+1)]=1
</code>```

Background: In my code, these two lines take 75% of the time for a 4000x4000 matrix whereas the ensuing topological sort and DP algorithm take only the rest of the quarter. Roughly 5% of the values in the matrix are nonzero so a sparse-matrix solution may be applicable.

Thank you.

(On suggestion posted here as well: https://scicomp.stackexchange.com/questions/35242/fast-nonzero-indices-per-row-column-for-sparse-2d-numpy-array
There are also answers there to which I will provide timings in the comments. This link contains an accepted answer that is twice as fast.)

答:
If you have enough motivation, Numba can do amazing things.
Here is a quick implementation of the logic you need.
Briefly, it computes the equivalent of np.nonzero() but it includes along the way the information to later dispatch the indices into the format you require.
The information is inspired by sparse.csr.indptr and sparse.csc.indptr.

```<code>import numpy as np
import numba as nb

@nb.jit
def cumsum(arr):
    result = np.empty_like(arr)
    cumsum = result[0] = arr[0]
    for i in range(1, len(arr)):
        cumsum += arr[i]
        result[i] = cumsum
    return result

@nb.jit
def count_nonzero(arr):
    arr = arr.ravel()
    n = 0
    for x in arr:
        if x != 0:
            n += 1
    return n

@nb.jit
def row_col_nonzero_nb(arr):
    n, m = arr.shape
    max_k = count_nonzero(arr)
    indices = np.empty((2, max_k), dtype=np.uint32)
    i_offset = np.zeros(n + 1, dtype=np.uint32)
    j_offset = np.zeros(m + 1, dtype=np.uint32)
    n, m = arr.shape
    k = 0
    for i in range(n):
        for j in range(m):
            if arr[i, j] != 0:
                indices[:, k] = i, j
                i_offset[i + 1] += 1
                j_offset[j + 1] += 1
                k += 1
    return indices, cumsum(i_offset), cumsum(j_offset)

def row_col_idx_nonzero_nb(arr):
    (ii, jj), jj_split, ii_split = row_col_nonzero_nb(arr)
    ii_ = np.argsort(jj)
    ii = ii[ii_]
    return np.split(ii, ii_split[1:-1]), np.split(jj, jj_split[1:-1])
</code>```

Compared to your approach (row_col_idx_sep() below), and a bunch of others, as per @hpaulj answer (row_col_idx_sparse_lil()) and @knl answer from scicomp.stackexchange.com (row_col_idx_sparse_coo()):

```<code>def row_col_idx_sep(arr):
    return (
        [arr[:, j].nonzero()[0] for j in range(arr.shape[1])],
        [arr[i, :].nonzero()[0] for i in range(arr.shape[0])],)
</code>```

```<code>def row_col_idx_zip(arr):
    n, m = arr.shape
    ii = [[] for _ in range(n)]
    jj = [[] for _ in range(m)]
    x, y = np.nonzero(arr)
    for i, j in zip(x, y):
        ii[i].append(j)
        jj[j].append(i)
    return jj, ii
</code>```

```<code>import scipy as sp
import scipy.sparse

def row_col_idx_sparse_coo(arr):
    coo_mat = sp.sparse.coo_matrix(arr)
    csr_mat = coo_mat.tocsr()
    csc_mat = coo_mat.tocsc()
    return (
        np.split(csc_mat.indices, csc_mat.indptr)[1:-1],
        np.split(csr_mat.indices, csr_mat.indptr)[1:-1],)
</code>```

```<code>def row_col_idx_sparse_lil(arr):
    lil_mat = sp.sparse.lil_matrix(arr)
    return lil_mat.T.rows, lil_mat.rows
</code>```

For inputs generated using:

```<code>def gen_input(n, density=0.1, dtype=np.float32):
    arr = np.zeros(shape=(n, n), dtype=dtype)
    indices = tuple(np.random.randint(0, n, (2, int(n * n * density))).tolist())
    arr[indices] = 1.0
    return arr
</code>```

One would get (your test_matrix had approximately 0.06 non-zero density):

```<code>m = gen_input(4096, density=0.06)
%timeit row_col_idx_sep(m)
# 1 loop, best of 3: 767 ms per loop
%timeit row_col_idx_zip(m)
# 1 loop, best of 3: 660 ms per loop
%timeit row_col_idx_sparse_coo(m)
# 1 loop, best of 3: 205 ms per loop
%timeit row_col_idx_sparse_lil(m)
# 1 loop, best of 3: 498 ms per loop
%timeit row_col_idx_nonzero_nb(m)
# 10 loops, best of 3: 130 ms per loop
</code>```

Indicating this to be close to twice as fast as the fastest scipy.sparse-based approach.

Body:
I am looking for the fastest way to obtain a list of the nonzero indices of a 2D array per row and per column. The following is a working piece of code:

preds = [matrix[:,v].nonzero()[0] for v in range(matrix.shape[1])]
descs = [matrix[v].nonzero()[0] for v in range(matrix.shape[0])]

Example input:

matrix = np.array([[0,0,0,0],[1,0,0,0],[1,1,0,0],[1,1,1,0]])

Example output

preds = [array([1, 2, 3]), array([2, 3]), array([3]), array([], dtype=int64)]
descs = [array([], dtype=int64), array([0]), array([0, 1]), array([0, 1, 2])]

(The lists are called preds and descs because they refer to the predecessors and descendants in a DAG when the matrix is interpreted as an adjacency matrix but this is not essential to the question.)

Timing example:
For timing purposes, the following matrix is a good representative:

test_matrix = np.zeros(shape=(4096,4096),dtype=np.float32)
for k in range(16):
    test_matrix[256*(k+1):256*(k+2),256*k:256*(k+1)]=1

Background: In my code, these two lines take 75% of the time for a 4000x4000 matrix whereas the ensuing topological sort and DP algorithm take only the rest of the quarter. Roughly 5% of the values in the matrix are nonzero so a sparse-matrix solution may be applicable.

Thank you.

(On suggestion posted here as well: https://scicomp.stackexchange.com/questions/35242/fast-nonzero-indices-per-row-column-for-sparse-2d-numpy-array
There are also answers there to which I will provide timings in the comments. This link contains an accepted answer that is twice as fast.)

Body:
If you have enough motivation, Numba can do amazing things.
Here is a quick implementation of the logic you need.
Briefly, it computes the equivalent of np.nonzero() but it includes along the way the information to later dispatch the indices into the format you require.
The information is inspired by sparse.csr.indptr and sparse.csc.indptr.

import numpy as np
import numba as nb

@nb.jit
def cumsum(arr):
    result = np.empty_like(arr)
    cumsum = result[0] = arr[0]
    for i in range(1, len(arr)):
        cumsum += arr[i]
        result[i] = cumsum
    return result

@nb.jit
def count_nonzero(arr):
    arr = arr.ravel()
    n = 0
    for x in arr:
        if x != 0:
            n += 1
    return n

@nb.jit
def row_col_nonzero_nb(arr):
    n, m = arr.shape
    max_k = count_nonzero(arr)
    indices = np.empty((2, max_k), dtype=np.uint32)
    i_offset = np.zeros(n + 1, dtype=np.uint32)
    j_offset = np.zeros(m + 1, dtype=np.uint32)
    n, m = arr.shape
    k = 0
    for i in range(n):
        for j in range(m):
            if arr[i, j] != 0:
                indices[:, k] = i, j
                i_offset[i + 1] += 1
                j_offset[j + 1] += 1
                k += 1
    return indices, cumsum(i_offset), cumsum(j_offset)

def row_col_idx_nonzero_nb(arr):
    (ii, jj), jj_split, ii_split = row_col_nonzero_nb(arr)
    ii_ = np.argsort(jj)
    ii = ii[ii_]
    return np.split(ii, ii_split[1:-1]), np.split(jj, jj_split[1:-1])

Compared to your approach (row_col_idx_sep() below), and a bunch of others, as per @hpaulj answer (row_col_idx_sparse_lil()) and @knl answer from scicomp.stackexchange.com (row_col_idx_sparse_coo()):

def row_col_idx_sep(arr):
    return (
        [arr[:, j].nonzero()[0] for j in range(arr.shape[1])],
        [arr[i, :].nonzero()[0] for i in range(arr.shape[0])],)

def row_col_idx_zip(arr):
    n, m = arr.shape
    ii = [[] for _ in range(n)]
    jj = [[] for _ in range(m)]
    x, y = np.nonzero(arr)
    for i, j in zip(x, y):
        ii[i].append(j)
        jj[j].append(i)
    return jj, ii

import scipy as sp
import scipy.sparse

def row_col_idx_sparse_coo(arr):
    coo_mat = sp.sparse.coo_matrix(arr)
    csr_mat = coo_mat.tocsr()
    csc_mat = coo_mat.tocsc()
    return (
        np.split(csc_mat.indices, csc_mat.indptr)[1:-1],
        np.split(csr_mat.indices, csr_mat.indptr)[1:-1],)

def row_col_idx_sparse_lil(arr):
    lil_mat = sp.sparse.lil_matrix(arr)
    return lil_mat.T.rows, lil_mat.rows

For inputs generated using:

def gen_input(n, density=0.1, dtype=np.float32):
    arr = np.zeros(shape=(n, n), dtype=dtype)
    indices = tuple(np.random.randint(0, n, (2, int(n * n * density))).tolist())
    arr[indices] = 1.0
    return arr

One would get (your test_matrix had approximately 0.06 non-zero density):

m = gen_input(4096, density=0.06)
%timeit row_col_idx_sep(m)
# 1 loop, best of 3: 767 ms per loop
%timeit row_col_idx_zip(m)
# 1 loop, best of 3: 660 ms per loop
%timeit row_col_idx_sparse_coo(m)
# 1 loop, best of 3: 205 ms per loop
%timeit row_col_idx_sparse_lil(m)
# 1 loop, best of 3: 498 ms per loop
%timeit row_col_idx_nonzero_nb(m)
# 10 loops, best of 3: 130 ms per loop

Indicating this to be close to twice as fast as the fastest scipy.sparse-based approach.


问:
Need to pull out Json Data (nested array) from a single column dataframe - Table is coming out as Null with schema read -Scala
I am trying to pull out data as below from data frame. The Json data which has nested arrays is completely in one column(_c1). I want to pull it out and create it as separate data frame with valid column names. One sample record would be as below.

```<code>|_c1                                                                                |
+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|{"Id":"31279605299","Type":"12121212","client":"Checklist _API","eventTime":"2020-03-17T15:50:30.640Z","eventType":"Event","payload":{"sourceApp":"ios","questionnaire":{"version":"1.0","question":"How to resolve ? ","fb":"Na"}}}
</code>```

I am reading it to a schema as,

```<code>val schema=StructType(Array(
      StructField("Id", StringType, false),
      StructField("Type", StringType, false),
      StructField("client", StringType, false),
      StructField("eventTime", StringType, false),
      StructField("eventType", StringType, false),
      StructField("payload", ArrayType(StructType(Array(
        StructField("sourceApp", StringType, false),
        StructField("questionnaire", ArrayType(StructType(Array(
          StructField("version", StringType, false),
          StructField("question", StringType, false),
          StructField("fb", StringType, false)))))
      ))))
    ))

      val json_paral = DF.select(from_json(col("_c1"),schema))
`
Structure comes out as below,
`

 |-- jsontostructs(_c1): struct (nullable = true)
 |    |-- Id: string (nullable = true)
 |    |-- Type: string (nullable = true)
 |    |-- client: string (nullable = true)
 |    |-- eventTime: string (nullable = true)
 |    |-- eventType: string (nullable = true)
 |    |-- payload: array (nullable = true)
 |    |    |-- element: struct (containsNull = true)
 |    |    |    |-- sourceApp: string (nullable = true)
 |    |    |    |-- questionnaire: array (nullable = true)
 |    |    |    |    |-- element: struct (containsNull = true)
 |    |    |    |    |    |-- version: string (nullable = true)
 |    |    |    |    |    |-- question: string (nullable = true)
 |    |    |    |    |    |-- fb: string (nullable = true)

</code>```

The structure is good but when I check the dataframe all data is coming out as NULL. Is the read fine ? Not getting any parsing issues either.

答:
Instead of reading it to schema I tried making it to a value as

```<code>
val Df = json_DF.map(r => r.getString(0))
</code>```

This will pull the data as a string on which the below would pull it out with the keys as column names.

```<code>val g1DF=spark.read.json(Df)
</code>```

Did some lateral view explode nested to pull out nested array values.

Body:
I am trying to pull out data as below from data frame. The Json data which has nested arrays is completely in one column(_c1). I want to pull it out and create it as separate data frame with valid column names. One sample record would be as below.

|_c1                                                                                |
+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|{"Id":"31279605299","Type":"12121212","client":"Checklist _API","eventTime":"2020-03-17T15:50:30.640Z","eventType":"Event","payload":{"sourceApp":"ios","questionnaire":{"version":"1.0","question":"How to resolve ? ","fb":"Na"}}}

I am reading it to a schema as,

val schema=StructType(Array(
      StructField("Id", StringType, false),
      StructField("Type", StringType, false),
      StructField("client", StringType, false),
      StructField("eventTime", StringType, false),
      StructField("eventType", StringType, false),
      StructField("payload", ArrayType(StructType(Array(
        StructField("sourceApp", StringType, false),
        StructField("questionnaire", ArrayType(StructType(Array(
          StructField("version", StringType, false),
          StructField("question", StringType, false),
          StructField("fb", StringType, false)))))
      ))))
    ))

      val json_paral = DF.select(from_json(col("_c1"),schema))
`
Structure comes out as below,
`

 |-- jsontostructs(_c1): struct (nullable = true)
 |    |-- Id: string (nullable = true)
 |    |-- Type: string (nullable = true)
 |    |-- client: string (nullable = true)
 |    |-- eventTime: string (nullable = true)
 |    |-- eventType: string (nullable = true)
 |    |-- payload: array (nullable = true)
 |    |    |-- element: struct (containsNull = true)
 |    |    |    |-- sourceApp: string (nullable = true)
 |    |    |    |-- questionnaire: array (nullable = true)
 |    |    |    |    |-- element: struct (containsNull = true)
 |    |    |    |    |    |-- version: string (nullable = true)
 |    |    |    |    |    |-- question: string (nullable = true)
 |    |    |    |    |    |-- fb: string (nullable = true)

The structure is good but when I check the dataframe all data is coming out as NULL. Is the read fine ? Not getting any parsing issues either.

Body:
Instead of reading it to schema I tried making it to a value as

val Df = json_DF.map(r => r.getString(0))

This will pull the data as a string on which the below would pull it out with the keys as column names.

val g1DF=spark.read.json(Df)

Did some lateral view explode nested to pull out nested array values.


问:
Use Angular service to login using cypress
I am using cypress to test our Angular application. After reading a lot on cypress' best practices I now would like to refactor our custom cypress login command. Currently it uses the UI for logging in.

I found the example on how to login using application code (https://github.com/cypress-io/cypress-example-recipes/tree/master/examples/logging-in__using-app-code) but with this I am running into troubles with our Angular app. Obviously we are using an Angular service to handle the login. Now trying to replicate the code from the example does not work using an Angular service:

```<code>// test.spec
import { AuthService } from 'src/app/core/http/auth.service'

describe('Landing Page Test', () => {
  it('should log the user in running app code', () => {
    // I cannot run it like this, coz service is a class
    AuthService.login('username','password');

    // I also cannot instantiate the AuthService because it has injected dependencies
    // so this does not compile:
    const authService = new AuthService();
  });
});

// AuthService (shortend ...)
@Injectable({
  providedIn: 'root'
})
export class AuthService {
  constructor(private apiHttpService: ApiHttpService) {}

  login(username, password) {
    // do login stuff
  }
}
</code>```

Is there any way to tap into that service and run the login from there? Or is this not possible with Angular?

答:
Oh I found the answer but it seems pretty hacky, you add the following to your service:

constructor() {
    if (window['Cypress']) window['AuthService'] = this
}

myFunctionName() {
    console.log("Oh I hope I'll get called from Cypress!")
}
```

<p>And in Cypress you'll be able to do this:</p>

<pre class="lang-js prettyprint-override"><code>it.only('Dev', () => {
    cy.window().then((w) => {
        w.AuthService.myFunctionName()
    })
})
</code>```

Body:
I am using cypress to test our Angular application. After reading a lot on cypress' best practices I now would like to refactor our custom cypress login command. Currently it uses the UI for logging in.

I found the example on how to login using application code (https://github.com/cypress-io/cypress-example-recipes/tree/master/examples/logging-in__using-app-code) but with this I am running into troubles with our Angular app. Obviously we are using an Angular service to handle the login. Now trying to replicate the code from the example does not work using an Angular service:

// test.spec
import { AuthService } from 'src/app/core/http/auth.service'

describe('Landing Page Test', () => {
  it('should log the user in running app code', () => {
    // I cannot run it like this, coz service is a class
    AuthService.login('username','password');

    // I also cannot instantiate the AuthService because it has injected dependencies
    // so this does not compile:
    const authService = new AuthService();
  });
});

// AuthService (shortend ...)
@Injectable({
  providedIn: 'root'
})
export class AuthService {
  constructor(private apiHttpService: ApiHttpService) {}

  login(username, password) {
    // do login stuff
  }
}

Is there any way to tap into that service and run the login from there? Or is this not possible with Angular?

Body:
Oh I found the answer but it seems pretty hacky, you add the following to your service:

constructor() {
    if (window['Cypress']) window['AuthService'] = this
}

myFunctionName() {
    console.log("Oh I hope I'll get called from Cypress!")
}

And in Cypress you'll be able to do this:

it.only('Dev', () => {
    cy.window().then((w) => {
        w.AuthService.myFunctionName()
    })
})


问:
UseMethod("type") error; no applicable method for 'type" applied to an object of class "c('double', 'numeric')"
In a dataframe, I have a column that has numeric values and some mixed in character data for some rows. I want to remove all rows with the character data and keep those rows with a number value. The df I have is 6 million rows, so I simply made a small object to try to solve my issue and then implement at a larger scale.

Here is what I did:

```<code>a <- c("fruit", "love", 53)

b <- str_replace_all("^[:alpha:]", 0)
</code>```

Reading answers to other UseMethod errors on here (about factors), I tried to change "a" to as.character(a) and attempt "b" again. But, I get the same error. I'm trying to simply make any alphabetic value into the number zero and I'm fairly new at all this.

答:
There's probably a more efficient way of doing this on a large data frame (e.g. something column-wise, instead of row-wise), but to answer your specific question about each row a:

```<code>as.numeric(stringr::str_replace_all(a, "[a-z]+", "0"))
</code>```

Note that the replacing value must be a character (the last argument in the function call, "0"). (You can look up the documentation from your R-console by: ?stringr::str_replace_all)

Body:
In a dataframe, I have a column that has numeric values and some mixed in character data for some rows. I want to remove all rows with the character data and keep those rows with a number value. The df I have is 6 million rows, so I simply made a small object to try to solve my issue and then implement at a larger scale.

Here is what I did:

a <- c("fruit", "love", 53)

b <- str_replace_all("^[:alpha:]", 0)

Reading answers to other UseMethod errors on here (about factors), I tried to change "a" to as.character(a) and attempt "b" again. But, I get the same error. I'm trying to simply make any alphabetic value into the number zero and I'm fairly new at all this.

Body:
There's probably a more efficient way of doing this on a large data frame (e.g. something column-wise, instead of row-wise), but to answer your specific question about each row a:

as.numeric(stringr::str_replace_all(a, "[a-z]+", "0"))

Note that the replacing value must be a character (the last argument in the function call, "0"). (You can look up the documentation from your R-console by: ?stringr::str_replace_all)


问:
No sound when running ffmpeg on youtube live
Despite my limited knowledge in ffmpeg, I've managed to livestream my birdbox camera to youtube using ffmpeg running on a raspberry pi. The camera has also audio and by using local vlc in windows with rtsp, the audio is ok.

However, on youtube there is no sound (same rtsp command as used locally in windows), and I see this "warning" in youtube studio: "The current bitrate (0) of the audio stream is lower than the recommended bitrate. We recommend using a 128 Kbps bitrate for the audio stream."

How can I get the sound through youtube?
This is the command I run. The command was found on the net, and I adopted it for my usage, and got video working straight away:

```<code>pi@raspberrypi:~ $ ffmpeg -f lavfi -i anullsrc -thread_queue_size 512 -rtsp_transport udp -i "rtsp://10.x.x.x:554/user=user&password=password&channel=1&stream=0.sdp?real_stream" -tune zerolatency -vcodec libx264 -use_wallclock_as_timestamps 1 -pix_fmt + -c:v copy -c:a aac -strict experimental -f flv rtmp://a.rtmp.youtube.com/live2/mykey
ffmpeg version git-2020-05-01-3c740f2 Copyright (c) 2000-2020 the FFmpeg developers
  built with gcc 6.3.0 (Raspbian 6.3.0-18+rpi1+deb9u1) 20170516
  configuration: --arch=armel --target-os=linux --enable-gpl --enable-libx264 --enable-nonfree
  libavutil      56. 43.100 / 56. 43.100
  libavcodec     58. 82.100 / 58. 82.100
  libavformat    58. 42.102 / 58. 42.102
  libavdevice    58.  9.103 / 58.  9.103
  libavfilter     7. 80.100 /  7. 80.100
  libswscale      5.  6.101 /  5.  6.101
  libswresample   3.  6.100 /  3.  6.100
  libpostproc    55.  6.100 / 55.  6.100
Input #0, lavfi, from 'anullsrc':
  Duration: N/A, start: 0.000000, bitrate: 705 kb/s
    Stream #0:0: Audio: pcm_u8, 44100 Hz, stereo, u8, 705 kb/s
Guessed Channel Layout for Input Stream #1.1 : mono
Input #1, rtsp, from 'rtsp://10.x.x.x:554/user=user&password=password&channel=1&stream=0.sdp?real_stream':
  Metadata:
    title           : RTSP Session
  Duration: N/A, start: 0.000000, bitrate: N/A
    Stream #1:0: Video: h264 (Main), yuvj420p(pc, bt709, progressive), 1920x1080, 20 fps, 20 tbr, 90k tbn, 180k tbc
    Stream #1:1: Audio: pcm_alaw, 8000 Hz, mono, s16, 64 kb/s
Multiple -c, -codec, -acodec, -vcodec, -scodec or -dcodec options specified for stream 0, only the last option '-c:v copy' will be used.
Stream mapping:
  Stream #1:0 -> #0:0 (copy)
  Stream #0:0 -> #0:1 (pcm_u8 (native) -> aac (native))
Press [q] to stop, [?] for help
Output #0, flv, to 'rtmp://a.rtmp.youtube.com/live2/mykey':
  Metadata:
    encoder         : Lavf58.42.102
    Stream #0:0: Video: h264 (Main) ([7][0][0][0] / 0x0007), yuvj420p(pc, bt709, progressive), 1920x1080, q=2-31, 20 fps, 20 tbr, 1k tbn, 90k tbc
    Stream #0:1: Audio: aac (LC) ([10][0][0][0] / 0x000A), 44100 Hz, stereo, fltp, 128 kb/s
    Metadata:
      encoder         : Lavc58.82.100 aac
[flv @ 0x2c43750] Timestamps are unset in a packet for stream 0. This is deprecated and will stop working in the future. Fix your code to set the timestamps properly
</code>```

答:
Your command is using the anullsrc filter to generate silent audio. YouTube requires an audio stream. So users often use anullsrc to make silent audio to fulfill this requirement if their input has no audio. ffmpeg is using this silent audio instead of your camera's audio. Remove anullsrc because you don't need it.

Use:

```<code>ffmpeg -thread_queue_size 512 -rtsp_transport udp -i "rtsp://10.x.x.x:554/user=user&password=password&channel=1&stream=0.sdp?real_stream" -c:v copy -c:a aac -f flv rtmp://a.rtmp.youtube.com/live2/mykey
</code>```

Because you are stream copying the video with -c:v copy I removed the unnecessary encoding options that are being ignored anyway (-tune zerolatency -vcodec libx264 -use_wallclock_as_timestamps 1 -pix_fmt).

I removed -strict experimental. It used to be required when the FFmpeg AAC encoder was considered experimental, but that has not been the case since 2015. However, it is very often still copied and pasted from outdated answers.

Body:
Despite my limited knowledge in ffmpeg, I've managed to livestream my birdbox camera to youtube using ffmpeg running on a raspberry pi. The camera has also audio and by using local vlc in windows with rtsp, the audio is ok.

However, on youtube there is no sound (same rtsp command as used locally in windows), and I see this "warning" in youtube studio: "The current bitrate (0) of the audio stream is lower than the recommended bitrate. We recommend using a 128 Kbps bitrate for the audio stream."

How can I get the sound through youtube?
This is the command I run. The command was found on the net, and I adopted it for my usage, and got video working straight away:

pi@raspberrypi:~ $ ffmpeg -f lavfi -i anullsrc -thread_queue_size 512 -rtsp_transport udp -i "rtsp://10.x.x.x:554/user=user&password=password&channel=1&stream=0.sdp?real_stream" -tune zerolatency -vcodec libx264 -use_wallclock_as_timestamps 1 -pix_fmt + -c:v copy -c:a aac -strict experimental -f flv rtmp://a.rtmp.youtube.com/live2/mykey
ffmpeg version git-2020-05-01-3c740f2 Copyright (c) 2000-2020 the FFmpeg developers
  built with gcc 6.3.0 (Raspbian 6.3.0-18+rpi1+deb9u1) 20170516
  configuration: --arch=armel --target-os=linux --enable-gpl --enable-libx264 --enable-nonfree
  libavutil      56. 43.100 / 56. 43.100
  libavcodec     58. 82.100 / 58. 82.100
  libavformat    58. 42.102 / 58. 42.102
  libavdevice    58.  9.103 / 58.  9.103
  libavfilter     7. 80.100 /  7. 80.100
  libswscale      5.  6.101 /  5.  6.101
  libswresample   3.  6.100 /  3.  6.100
  libpostproc    55.  6.100 / 55.  6.100
Input #0, lavfi, from 'anullsrc':
  Duration: N/A, start: 0.000000, bitrate: 705 kb/s
    Stream #0:0: Audio: pcm_u8, 44100 Hz, stereo, u8, 705 kb/s
Guessed Channel Layout for Input Stream #1.1 : mono
Input #1, rtsp, from 'rtsp://10.x.x.x:554/user=user&password=password&channel=1&stream=0.sdp?real_stream':
  Metadata:
    title           : RTSP Session
  Duration: N/A, start: 0.000000, bitrate: N/A
    Stream #1:0: Video: h264 (Main), yuvj420p(pc, bt709, progressive), 1920x1080, 20 fps, 20 tbr, 90k tbn, 180k tbc
    Stream #1:1: Audio: pcm_alaw, 8000 Hz, mono, s16, 64 kb/s
Multiple -c, -codec, -acodec, -vcodec, -scodec or -dcodec options specified for stream 0, only the last option '-c:v copy' will be used.
Stream mapping:
  Stream #1:0 -> #0:0 (copy)
  Stream #0:0 -> #0:1 (pcm_u8 (native) -> aac (native))
Press [q] to stop, [?] for help
Output #0, flv, to 'rtmp://a.rtmp.youtube.com/live2/mykey':
  Metadata:
    encoder         : Lavf58.42.102
    Stream #0:0: Video: h264 (Main) ([7][0][0][0] / 0x0007), yuvj420p(pc, bt709, progressive), 1920x1080, q=2-31, 20 fps, 20 tbr, 1k tbn, 90k tbc
    Stream #0:1: Audio: aac (LC) ([10][0][0][0] / 0x000A), 44100 Hz, stereo, fltp, 128 kb/s
    Metadata:
      encoder         : Lavc58.82.100 aac
[flv @ 0x2c43750] Timestamps are unset in a packet for stream 0. This is deprecated and will stop working in the future. Fix your code to set the timestamps properly

Body:
Your command is using the anullsrc filter to generate silent audio. YouTube requires an audio stream. So users often use anullsrc to make silent audio to fulfill this requirement if their input has no audio. ffmpeg is using this silent audio instead of your camera's audio. Remove anullsrc because you don't need it.

Use:

ffmpeg -thread_queue_size 512 -rtsp_transport udp -i "rtsp://10.x.x.x:554/user=user&password=password&channel=1&stream=0.sdp?real_stream" -c:v copy -c:a aac -f flv rtmp://a.rtmp.youtube.com/live2/mykey

Because you are stream copying the video with -c:v copy I removed the unnecessary encoding options that are being ignored anyway (-tune zerolatency -vcodec libx264 -use_wallclock_as_timestamps 1 -pix_fmt).

I removed -strict experimental. It used to be required when the FFmpeg AAC encoder was considered experimental, but that has not been the case since 2015. However, it is very often still copied and pasted from outdated answers.


问:
How can I get started with Apache, MySQL, and (PHP, Perl, Python) on a Mac?
What do you recommend for setting the MAMP development stack?

I've seen the quickstart thing at http://www.mamp.info, but I don't really like that approach. I'd rather have a full-fledged Apache that I can install any number of modules into. I remember seeing in the OS X v10.5 (Leopard) Server demo a really slick GUI that allows you to set up all this stuff, add virtual hosts, etc., and I was wondering if anything similar is available for the non-server Leopard.

答: Avoid heavy MacPorts usage. It is a lousy source-based distribution. Avalanche rebuilds, unnecessary default dependencies (xorg for imagemagick). Use binary whenever possible.</p>

OwnerDisplayName: Abdullah Jibaly

LastEditorDisplayName: brian d foy


问:
Place ImageButton in top left corner
I have a very simple fragment layout (fragment_search.xml):

```<code><?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".ui.review.SearchFragment">

        <ImageButton
            android:id="@+id/search_bar_button"
            android:layout_width="48dp"
            android:layout_height="48dp"
            android:contentDescription="@string/switch_to_search_bar"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:srcCompat="@drawable/ic_search_bar" />

        <TextView
            android:id="@+id/text_search"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_marginStart="8dp"
            android:layout_marginTop="8dp"
            android:layout_marginEnd="8dp"
            android:textAlignment="center"
            android:textSize="20sp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>
</code>```

The fragment is hosted by activity_main.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingTop="?attr/actionBarSize">

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/nav_view"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="0dp"
        android:layout_marginEnd="0dp"
        android:background="?android:attr/windowBackground"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:menu="@menu/bottom_nav_menu" />

    <fragment
        android:id="@+id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:layout_constraintBottom_toTopOf="@id/nav_view"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="1.0"
        app:navGraph="@navigation/mobile_navigation" />

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

My intention is for the ImageButton in fragment_search.xml to appear in the top-left corner with no gaps.  For some reason, when I run the app, the icon appears with a large gap above and a small gap to the left:

In Design view, the button appears in the top-left corner but with a 1mm gap between the button and the edge of the screen.

Why is the button not appearing in the top-left corner when I run the app, and how do I fix it?

答:
I'm not sure what the cause of your problem is, but I think it's because your activity layout not fragment layout, try to edit your activity layout and let me know what is the result.

or you can edit your question with showing activity layout where your fragments lies there.

Title: Place ImageButton in top left corner

Body:
I have a very simple fragment layout (fragment_search.xml):

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".ui.review.SearchFragment">

        <ImageButton
            android:id="@+id/search_bar_button"
            android:layout_width="48dp"
            android:layout_height="48dp"
            android:contentDescription="@string/switch_to_search_bar"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:srcCompat="@drawable/ic_search_bar" />

        <TextView
            android:id="@+id/text_search"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_marginStart="8dp"
            android:layout_marginTop="8dp"
            android:layout_marginEnd="8dp"
            android:textAlignment="center"
            android:textSize="20sp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

The fragment is hosted by activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingTop="?attr/actionBarSize">

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/nav_view"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="0dp"
        android:layout_marginEnd="0dp"
        android:background="?android:attr/windowBackground"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:menu="@menu/bottom_nav_menu" />

    <fragment
        android:id="@+id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:layout_constraintBottom_toTopOf="@id/nav_view"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="1.0"
        app:navGraph="@navigation/mobile_navigation" />

</androidx.constraintlayout.widget.ConstraintLayout>

My intention is for the ImageButton in fragment_search.xml to appear in the top-left corner with no gaps.  For some reason, when I run the app, the icon appears with a large gap above and a small gap to the left:

In Design view, the button appears in the top-left corner but with a 1mm gap between the button and the edge of the screen.

Why is the button not appearing in the top-left corner when I run the app, and how do I fix it?


问:
C: Pipe: How to pass a dynamic int array using pipe correctly
I tried to write a dynamic allocated int array in several child processes, and read them in parent process using pipe, but the result is like [-15236548, 37526, -15236548, 37526,0,0,0,0,0,0], it looks like the addresses are read instead of the real values[1,1,1,1,0,2,1,1,1,1]. I am really struggling in it for the whole day, any help would be greatly appreciated!!!

The child process are 10, they would first write an array each, and after all of them are done, parent process reads the 10 array.

```<code>int *getArr(){
    int * arr1 = malloc(sizeof(int) *100);
    //do something
    return arr1;
}

//write values to pipe
void write_check(int fd, void *buffer, size_t len){
    char *p = buffer;
    while(len>0){
        size_t wlen = write(fd, p, len);
        if(wlen <= 0)
            exit(0);
        p += wlen;
        len -= wlen;
    }
}

// read values from pipe
void read_check(int fd, void *buffer, size_t len){
    char *p = buffer;
    while(len>0){
        size_t rlen = read(fd, p, len);
        if(rlen <= 0)
            exit(0);
        p += rlen;
        len -= rlen;
    }
}

// pass values, and get it ready to be wrote
void write_ints(int fd, int *p, int len){
    write_check(fd, p, len * sizeof(*p));
}

// allocate memory for fetching values
void read_ints(int fd, int *p, int len){
    p = malloc(len * sizeof(*p));
    read_check(fd, p, len* sizeof(*p));
}

int main(){
    int len = 100;
    int *arr1 = malloc(sizeof(int) * 100);
    int *fds = malloc(sizeof(int) * 10 * 2);

    // child processes write values to pipe
    for(int i=0; i<10; i++){
        child_pid = fork();
        if (child_pid == 0){
            // do something
            arr1 = getArr();
            write_ints(fd[i*2+1], &arr1, len);
        }
    }
    // parent process reads values
    for(int i=0; i<10; i++){
        // do something
        read_ints(fd[i*2], &arr1, len);
    }
}
</code>```

答:
```<code>void read_ints(int fd, int *p, int len){
    p = malloc(len * sizeof(*p));
    read_check(fd, p, len* sizeof(*p));
}
</code>```

This function is unusable. You pass it a pointer, which it ignores. It then allocates some memory, reads some integers into that memory, and does nothing with the pointer to that memory leaving the caller no way to access the read values.

If this function is going to allocate memory, it needs to return a pointer to the memory it allocated. If this function is going to receive a pointer to the memory it's going to read the integers into, then it should read the integers into the supplied buffer and not allocate its own.

Your code would be much easier to debug if it had comments. Looking at this function, I cannot tell what it's supposed to do and I see conflicting information in the code. Is it supposed to allocate a buffer to read integers into or is it supposed to be supplied a pointer to the buffer to read into? A comment would clear that up.

You cannot count on your code to document your intentions yet because your code isn't yet good enough to do that. So you need to use comments so that other people can tell what you meant to do, not just what you actually did.

Body:
I tried to write a dynamic allocated int array in several child processes, and read them in parent process using pipe, but the result is like [-15236548, 37526, -15236548, 37526,0,0,0,0,0,0], it looks like the addresses are read instead of the real values[1,1,1,1,0,2,1,1,1,1]. I am really struggling in it for the whole day, any help would be greatly appreciated!!!

The child process are 10, they would first write an array each, and after all of them are done, parent process reads the 10 array.

int *getArr(){
    int * arr1 = malloc(sizeof(int) *100);
    //do something
    return arr1;
}

//write values to pipe
void write_check(int fd, void *buffer, size_t len){
    char *p = buffer;
    while(len>0){
        size_t wlen = write(fd, p, len);
        if(wlen <= 0)
            exit(0);
        p += wlen;
        len -= wlen;
    }
}

// read values from pipe
void read_check(int fd, void *buffer, size_t len){
    char *p = buffer;
    while(len>0){
        size_t rlen = read(fd, p, len);
        if(rlen <= 0)
            exit(0);
        p += rlen;
        len -= rlen;
    }
}

// pass values, and get it ready to be wrote
void write_ints(int fd, int *p, int len){
    write_check(fd, p, len * sizeof(*p));
}

// allocate memory for fetching values
void read_ints(int fd, int *p, int len){
    p = malloc(len * sizeof(*p));
    read_check(fd, p, len* sizeof(*p));
}

int main(){
    int len = 100;
    int *arr1 = malloc(sizeof(int) * 100);
    int *fds = malloc(sizeof(int) * 10 * 2);

    // child processes write values to pipe
    for(int i=0; i<10; i++){
        child_pid = fork();
        if (child_pid == 0){
            // do something
            arr1 = getArr();
            write_ints(fd[i*2+1], &arr1, len);
        }
    }
    // parent process reads values
    for(int i=0; i<10; i++){
        // do something
        read_ints(fd[i*2], &arr1, len);
    }
}

Body:
void read_ints(int fd, int *p, int len){
    p = malloc(len * sizeof(*p));
    read_check(fd, p, len* sizeof(*p));
}

This function is unusable. You pass it a pointer, which it ignores. It then allocates some memory, reads some integers into that memory, and does nothing with the pointer to that memory leaving the caller no way to access the read values.

If this function is going to allocate memory, it needs to return a pointer to the memory it allocated. If this function is going to receive a pointer to the memory it's going to read the integers into, then it should read the integers into the supplied buffer and not allocate its own.

Your code would be much easier to debug if it had comments. Looking at this function, I cannot tell what it's supposed to do and I see conflicting information in the code. Is it supposed to allocate a buffer to read integers into or is it supposed to be supplied a pointer to the buffer to read into? A comment would clear that up.

You cannot count on your code to document your intentions yet because your code isn't yet good enough to do that. So you need to use comments so that other people can tell what you meant to do, not just what you actually did.


问:
KIVY: How can I get the scroll direction in kivy?
I found this piece of code:

```<code>from kivy.app import App
from kivy.lang import Builder
from kivy.core.window import Window
from kivy.uix.boxlayout import BoxLayout

class Test(BoxLayout):
    def __init__(self, **kwargs):
        super(Test, self).__init__(**kwargs)
        Window.bind(on_touch_down=self.window_on_touch_down)

    def window_on_touch_down(self, *args):
        print(args)
        # scrolling the wheel down will give <MouseMotionEvent button="scrollup"

        if '<MouseMotionEvent button="scrollup"' in args:
            print('hello')

class TestApp(App):
    def build(self):
        return Test()

if __name__ == '__main__':
    TestApp().run()
</code>```

and while it prints the scrollup motion I can't use it... args has the string in it but the if doesn't work and "hello" isn't printed... anybody know why?

答:
What you see in the prints are python objects not strings.

So you can't just check for a string.

A better way to get what you want is to check what button produces the MouseMotionEvent

    def window_on_touch_down(self, window, mouse_event):
        # scrolling the wheel down will give <MouseMotionEvent button="scrollup"
        if mouse_event.button == "scrollup":
            print('hello')
```

Body:
I found this piece of code:

from kivy.app import App
from kivy.lang import Builder
from kivy.core.window import Window
from kivy.uix.boxlayout import BoxLayout

class Test(BoxLayout):
    def __init__(self, **kwargs):
        super(Test, self).__init__(**kwargs)
        Window.bind(on_touch_down=self.window_on_touch_down)

    def window_on_touch_down(self, *args):
        print(args)
        # scrolling the wheel down will give <MouseMotionEvent button="scrollup"

        if '<MouseMotionEvent button="scrollup"' in args:
            print('hello')

class TestApp(App):
    def build(self):
        return Test()

if __name__ == '__main__':
    TestApp().run()

and while it prints the scrollup motion I can't use it... args has the string in it but the if doesn't work and "hello" isn't printed... anybody know why?


问:
Unable to start ACTION_VIDEO_CAPTURE from onCreate of MainActivity
I am new to Android. I need to write a simple application which will open back camera and should display video from the camera and also some Wifi parameters (RSSI). To get the stream from camera, I am trying to use ACTION_VIDEO_CAPTURE from onCreate() method of MainActivity. I am trying this on Emulator from Android Studio on MAC as I don't have Android mobile. But the application is crashing. Below is the code (I didn't type all the imports in below code)

MainActivity.java :

```<code>package com.example.myapplication;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    private static final int VIDEO_CAPTURE = 1;

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

        TextView wifiTextView = (TextView) findViewById(R.id.wifi_text);

        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        int rssi = wifiManager.getConnectionInfo().getRssi();
        wifiTextView.setTextColor(Color.WHITE);
        wifiTextView.setText(Integer.toString(rssi));

        Log.d(TAG, "Has Camera : " + hasCamera());

        Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
        startActivityForResult(intent, VIDEO_CAPTURE);
    }

    private boolean hasCamera() {
        if(getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FRONT)) {
            return true;
        }
        else {
            return false;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data){
        super.onActivityResult(requestCode, resultCode, data);

        if(requestCode == VIDEO_CAPTURE) {
            if(resultCode == RESULT_OK) {
                Log.d(TAG, "Got data here from Camera");
            }
        }
    }
}
</code>```

Layout :

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <VideoView
        android:id="@+id/videoView"
        android:layout_height="match_parent"
        android:layout_width="match_parent" />

    <TextView
        android:id="@+id/wifi_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

I used below permissions in Manifest.

```<code><uses-permission android:name="android.permission.CAMERA" />
    <uses-feature android:name="android.hardware.camera" android:required="false" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
</code>```

The application is crashing if I start the intent. Below are the crash details

```<code>2020-05-28 13:48:03.782 6531-6531/? E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.myapplication, PID: 6531
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapplication/com.example.myapplication.MainActivity}: java.lang.SecurityException: Permission Denial: starting Intent { act=android.media.action.VIDEO_CAPTURE cmp=com.android.camera2/com.android.camera.VideoCamera } from ProcessRecord{ad7c2be 6531:com.example.myapplication/u0a149} (pid=6531, uid=10149) with revoked permission android.permission.CAMERA
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3341)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3485)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2045)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7478)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:549)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:941)
     Caused by: java.lang.SecurityException: Permission Denial: starting Intent { act=android.media.action.VIDEO_CAPTURE cmp=com.android.camera2/com.android.camera.VideoCamera } from ProcessRecord{ad7c2be 6531:com.example.myapplication/u0a149} (pid=6531, uid=10149) with revoked permission android.permission.CAMERA
        at android.os.Parcel.createExceptionOrNull(Parcel.java:2285)
        at android.os.Parcel.createException(Parcel.java:2269)
        at android.os.Parcel.readException(Parcel.java:2252)
        at android.os.Parcel.readException(Parcel.java:2194)
        at android.app.IActivityTaskManager$Stub$Proxy.startActivity(IActivityTaskManager.java:3722)
        at android.app.Instrumentation.execStartActivity(Instrumentation.java:1723)
        at android.app.Activity.startActivityForResult(Activity.java:5323)
        at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:676)
        at android.app.Activity.startActivityForResult(Activity.java:5281)
        at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:663)
        at com.example.myapplication.MainActivity.onCreate(MainActivity.java:45)
        at android.app.Activity.performCreate(Activity.java:7989)
        at android.app.Activity.performCreate(Activity.java:7978)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3316)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3485)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2045)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7478)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:549)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:941)
     Caused by: android.os.RemoteException: Remote stack trace:
        at com.android.server.wm.ActivityStackSupervisor.checkStartAnyActivityPermission(ActivityStackSupervisor.java:1034)
        at com.android.server.wm.ActivityStarter.executeRequest(ActivityStarter.java:969)
        at com.android.server.wm.ActivityStarter.execute(ActivityStarter.java:640)
        at com.android.server.wm.ActivityTaskManagerService.startActivityAsUser(ActivityTaskManagerService.java:1095)
        at com.android.server.wm.ActivityTaskManagerService.startActivityAsUser(ActivityTaskManagerService.java:1067)
</code>```

Can some one please help me to fix this issue.

答:
It seems that you did include the permission but forgot to ask for them. Dangerous permissions including camera access require a user allowance at run-time to be accessed.

The error clearly states the reason : `java.lang.SecurityException: Permission Denial

First check if your app has the required permission:Check permission

Then if you don't have the required permissions: Ask for permission

Also, don't forget to give it a good read: Permissions.

Body:
I am new to Android. I need to write a simple application which will open back camera and should display video from the camera and also some Wifi parameters (RSSI). To get the stream from camera, I am trying to use ACTION_VIDEO_CAPTURE from onCreate() method of MainActivity. I am trying this on Emulator from Android Studio on MAC as I don't have Android mobile. But the application is crashing. Below is the code (I didn't type all the imports in below code)

MainActivity.java :

package com.example.myapplication;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    private static final int VIDEO_CAPTURE = 1;

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

        TextView wifiTextView = (TextView) findViewById(R.id.wifi_text);

        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        int rssi = wifiManager.getConnectionInfo().getRssi();
        wifiTextView.setTextColor(Color.WHITE);
        wifiTextView.setText(Integer.toString(rssi));

        Log.d(TAG, "Has Camera : " + hasCamera());

        Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
        startActivityForResult(intent, VIDEO_CAPTURE);
    }

    private boolean hasCamera() {
        if(getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FRONT)) {
            return true;
        }
        else {
            return false;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data){
        super.onActivityResult(requestCode, resultCode, data);

        if(requestCode == VIDEO_CAPTURE) {
            if(resultCode == RESULT_OK) {
                Log.d(TAG, "Got data here from Camera");
            }
        }
    }
}

Layout :

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <VideoView
        android:id="@+id/videoView"
        android:layout_height="match_parent"
        android:layout_width="match_parent" />

    <TextView
        android:id="@+id/wifi_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

I used below permissions in Manifest.

<uses-permission android:name="android.permission.CAMERA" />
    <uses-feature android:name="android.hardware.camera" android:required="false" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />

The application is crashing if I start the intent. Below are the crash details

2020-05-28 13:48:03.782 6531-6531/? E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.myapplication, PID: 6531
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapplication/com.example.myapplication.MainActivity}: java.lang.SecurityException: Permission Denial: starting Intent { act=android.media.action.VIDEO_CAPTURE cmp=com.android.camera2/com.android.camera.VideoCamera } from ProcessRecord{ad7c2be 6531:com.example.myapplication/u0a149} (pid=6531, uid=10149) with revoked permission android.permission.CAMERA
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3341)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3485)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2045)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7478)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:549)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:941)
     Caused by: java.lang.SecurityException: Permission Denial: starting Intent { act=android.media.action.VIDEO_CAPTURE cmp=com.android.camera2/com.android.camera.VideoCamera } from ProcessRecord{ad7c2be 6531:com.example.myapplication/u0a149} (pid=6531, uid=10149) with revoked permission android.permission.CAMERA
        at android.os.Parcel.createExceptionOrNull(Parcel.java:2285)
        at android.os.Parcel.createException(Parcel.java:2269)
        at android.os.Parcel.readException(Parcel.java:2252)
        at android.os.Parcel.readException(Parcel.java:2194)
        at android.app.IActivityTaskManager$Stub$Proxy.startActivity(IActivityTaskManager.java:3722)
        at android.app.Instrumentation.execStartActivity(Instrumentation.java:1723)
        at android.app.Activity.startActivityForResult(Activity.java:5323)
        at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:676)
        at android.app.Activity.startActivityForResult(Activity.java:5281)
        at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:663)
        at com.example.myapplication.MainActivity.onCreate(MainActivity.java:45)
        at android.app.Activity.performCreate(Activity.java:7989)
        at android.app.Activity.performCreate(Activity.java:7978)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3316)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3485)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2045)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7478)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:549)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:941)
     Caused by: android.os.RemoteException: Remote stack trace:
        at com.android.server.wm.ActivityStackSupervisor.checkStartAnyActivityPermission(ActivityStackSupervisor.java:1034)
        at com.android.server.wm.ActivityStarter.executeRequest(ActivityStarter.java:969)
        at com.android.server.wm.ActivityStarter.execute(ActivityStarter.java:640)
        at com.android.server.wm.ActivityTaskManagerService.startActivityAsUser(ActivityTaskManagerService.java:1095)
        at com.android.server.wm.ActivityTaskManagerService.startActivityAsUser(ActivityTaskManagerService.java:1067)

Can some one please help me to fix this issue.


问:
Getting raw data from a QuickFIX/J Message
I want to grab the raw message data from QuickFIX/J. That is not the string representation of the Message object but the actual FIX message data. They might very well differ due to the message dictionary that is being supplied to QuickFIX/J.

Now looking at the Message type we have

private String messageData;
```

<p>This is private however and is not accessible. On the other hand the toString() method looks like: </p>

<pre class="lang-java prettyprint-override"><code>public String toString() {
    this.header.setField(new BodyLength(this.bodyLength()));
    this.trailer.setField(new CheckSum(this.checkSum()));
    StringBuffer sb = new StringBuffer();
    this.header.calculateString(sb, (int[])null, (int[])null);
    this.calculateString(sb, (int[])null, (int[])null);
    this.trailer.calculateString(sb, (int[])null, (int[])null);
    return sb.toString();
}
</code>```

That being said, is there a way to get the raw data from the message? I can't seem to find a way.

答:
Not sure if this was available to you in your QuickFIX/J version when you tried, but I can see it is available in 2.1.0 version.

In Message.java:

public String toRawString() {
    return messageData;
}
```

Although, this method doesn't calculate body length & checksum after any modifications are done to the Message object. For that purpose, you have to use the toString() method.

Body:
I want to grab the raw message data from QuickFIX/J. That is not the string representation of the Message object but the actual FIX message data. They might very well differ due to the message dictionary that is being supplied to QuickFIX/J.

Now looking at the Message type we have

private String messageData;

This is private however and is not accessible. On the other hand the toString() method looks like:

public String toString() {
    this.header.setField(new BodyLength(this.bodyLength()));
    this.trailer.setField(new CheckSum(this.checkSum()));
    StringBuffer sb = new StringBuffer();
    this.header.calculateString(sb, (int[])null, (int[])null);
    this.calculateString(sb, (int[])null, (int[])null);
    this.trailer.calculateString(sb, (int[])null, (int[])null);
    return sb.toString();
}

That being said, is there a way to get the raw data from the message? I can't seem to find a way.

Body:
Not sure if this was available to you in your QuickFIX/J version when you tried, but I can see it is available in 2.1.0 version.

In Message.java:

public String toRawString() {
    return messageData;
}

Although, this method doesn't calculate body length & checksum after any modifications are done to the Message object. For that purpose, you have to use the toString() method.


问:
Convert Ruby String to utf-16be | Ruby Equivalent Code of Python
I'm trying to send Bengali text using an SMS Gateway. However it doesn't normally support Bengali text. Their documentation says I need to convert the SMS string to utf-16be; without any other details. However I found a Python implementation of what I'm looking for here .

```<code>>>> message = 'আমার সোনার বাংলা'
>>> message
'আমার সোনার বাংলা'

>>> message.encode('utf-16-be')
b'\t\x86\t\xae\t\xbe\t\xb0\x00 \t\xb8\t\xcb\t\xa8\t\xbe\t\xb0\x00 \t\xac\t\xbe\t\x82\t\xb2\t\xbe'

>>> message.encode('utf-16-be').hex()
'098609ae09be09b0002009b809cb09a809be09b0002009ac09be098209b209be'

>>> message.encode('utf-16-be').hex().upper()
'098609AE09BE09B0002009B809CB09A809BE09B0002009AC09BE098209B209BE'
</code>```

I am trying to accomplish two things here:

Understand the Python Implementation

Replicate the same procedure in Ruby 2.6

So far I've come up with following

```<code>text = 'আমার সোনার বাংলা'.encode("UTF-16BE")
p text
#output-> "\u0986\u09AE\u09BE\u09B0 \u09B8\u09CB\u09A8\u09BE\u09B0 \u09AC\u09BE\u0982\u09B2\u09BE"
</code>```

答:
Typically converting from a string to bytes is accomplished with the unpack method:

```<code># ref unpack documentation for specifics, but I use 'H*' here for hex
message.encode('utf-16-be').unpack('H*')
</code>```

Body:
I'm trying to send Bengali text using an SMS Gateway. However it doesn't normally support Bengali text. Their documentation says I need to convert the SMS string to utf-16be; without any other details. However I found a Python implementation of what I'm looking for here .

>>> message = 'আমার সোনার বাংলা'
>>> message
'আমার সোনার বাংলা'

>>> message.encode('utf-16-be')
b'\t\x86\t\xae\t\xbe\t\xb0\x00 \t\xb8\t\xcb\t\xa8\t\xbe\t\xb0\x00 \t\xac\t\xbe\t\x82\t\xb2\t\xbe'

>>> message.encode('utf-16-be').hex()
'098609ae09be09b0002009b809cb09a809be09b0002009ac09be098209b209be'

>>> message.encode('utf-16-be').hex().upper()
'098609AE09BE09B0002009B809CB09A809BE09B0002009AC09BE098209B209BE'

I am trying to accomplish two things here:

Understand the Python Implementation

Replicate the same procedure in Ruby 2.6

So far I've come up with following

text = 'আমার সোনার বাংলা'.encode("UTF-16BE")
p text
#output-> "\u0986\u09AE\u09BE\u09B0 \u09B8\u09CB\u09A8\u09BE\u09B0 \u09AC\u09BE\u0982\u09B2\u09BE"

Body:
Typically converting from a string to bytes is accomplished with the unpack method:

# ref unpack documentation for specifics, but I use 'H*' here for hex
message.encode('utf-16-be').unpack('H*')


问:
Simple html dom parser
I use simple php dom parser. I have a link in my loaded dom which looks like this (in html):

```<code><a href="...">Some const tesxt</a>
</code>```

How can I select this object using find function? Maybe I can pass regular expression which looks at a container text? Btw, it's static(constant) text and I want to search need link refer to that text.

答:
Reading through the Manual it should give you all you need to know.

```<code>$ret = $html->find('a');

foreach ($ret as $link) {
    if ($link->innertext == 'Someconst tesxt') {
          // do what you must.
    }
}
</code>```

Not sure what else you are looking for, but I am not able to test the above, just put it together from reading the manual.

Title: Simple html dom parser

Body:
I use simple php dom parser. I have a link in my loaded dom which looks like this (in html):

Some const tesxt

How can I select this object using find function? Maybe I can pass regular expression which looks at a container text? Btw, it's static(constant) text and I want to search need link refer to that text.

Body:
Reading through the Manual it should give you all you need to know.

$ret = $html->find('a');

foreach ($ret as $link) {
    if ($link->innertext == 'Someconst tesxt') {
          // do what you must.
    }
}

Not sure what else you are looking for, but I am not able to test the above, just put it together from reading the manual.


问:
Calculate just based on normal candlestick (pinescript)
Could somebody help me? I want to calculate based on "normal candlestick" opens (although you change to HA, renko, etc. plots must be the same: based in normal candlestick).

Instead of: myopen = security(heikinashi(syminfo.tickerid), "D", open), which one should I use?

Thanks, everyone!

答:
You will need to use:

```<code>ticker      = tickerid(syminfo.prefix, syminfo.ticker)
realOpen    = security(ticker, timeframe.period, open,   lookahead = barmerge.lookahead_on)
</code>```

See how it's used in Backtesting on Non-Standard Charts: Caution! - PineCoders FAQ.

Warning: This should NOT be used on normal charts, as it will return future values.

Body:
You will need to use:

ticker      = tickerid(syminfo.prefix, syminfo.ticker)
realOpen    = security(ticker, timeframe.period, open,   lookahead = barmerge.lookahead_on)

See how it's used in Backtesting on Non-Standard Charts: Caution! - PineCoders FAQ.

Warning: This should NOT be used on normal charts, as it will return future values.


问:
Single column dataframe containing 1D lists using a numpy 2D array
I want to create a new single column pandas dataframe using a 2D numpy array. Apparently, each row should contain 1D lists. Following is a simplified reproducible example.

```<code>import pandas as pd
import numpy as np

arr = np.ones((4,3)) # could be any 2D array
</code>```

What I want is,

```<code>       lists
0  [1, 1, 1]
1  [1, 1, 1]
2  [1, 1, 1]
3  [1, 1, 1]
</code>```

Now, df  = pd.DataFrame(arr, columns=['lists']) gives the error,

```<code>ValueError: Shape of passed values is (4, 3), indices imply (4, 1)
</code>```

And df = pd.DataFrame(list(arr), columns=['lists']) gives the error,

```<code>ValueError: 1 columns passed, passed data had 3 columns
</code>```

Finally, df = pd.DataFrame(arr.flatten(), columns=['lists']) gives a wrong dataframe with all cells having a scalar 1.

How do I get what I want?

答:
From each row of the 2d array (i.e. a 1d array), construct a singleton tuple that contains that row, and build the DataFrame from that. We can elegantly do this using a generator expression:

```<code>>>> df = pd.DataFrame(((x,) for x in arr), columns=['lists'])
>>> df
             lists
0  [1.0, 1.0, 1.0]
1  [1.0, 1.0, 1.0]
2  [1.0, 1.0, 1.0]
3  [1.0, 1.0, 1.0]
</code>```

The constructor iterates over the tuple, rather than the underlying array, in order to determine the column values in a given row. There is one such value - the 1d array - so that gets stored for that row in the single available column.

The cell values are indeed Numpy arrays:

```<code>>>> df['lists'][0]
array([1., 1., 1.])
</code>```

Body:
I want to create a new single column pandas dataframe using a 2D numpy array. Apparently, each row should contain 1D lists. Following is a simplified reproducible example.

import pandas as pd
import numpy as np

arr = np.ones((4,3)) # could be any 2D array

What I want is,

       lists
0  [1, 1, 1]
1  [1, 1, 1]
2  [1, 1, 1]
3  [1, 1, 1]

Now, df  = pd.DataFrame(arr, columns=['lists']) gives the error,

ValueError: Shape of passed values is (4, 3), indices imply (4, 1)

And df = pd.DataFrame(list(arr), columns=['lists']) gives the error,

ValueError: 1 columns passed, passed data had 3 columns

Finally, df = pd.DataFrame(arr.flatten(), columns=['lists']) gives a wrong dataframe with all cells having a scalar 1.

How do I get what I want?

Body:
From each row of the 2d array (i.e. a 1d array), construct a singleton tuple that contains that row, and build the DataFrame from that. We can elegantly do this using a generator expression:

>>> df = pd.DataFrame(((x,) for x in arr), columns=['lists'])
>>> df
             lists
0  [1.0, 1.0, 1.0]
1  [1.0, 1.0, 1.0]
2  [1.0, 1.0, 1.0]
3  [1.0, 1.0, 1.0]

The constructor iterates over the tuple, rather than the underlying array, in order to determine the column values in a given row. There is one such value - the 1d array - so that gets stored for that row in the single available column.

The cell values are indeed Numpy arrays:

>>> df['lists'][0]
array([1., 1., 1.])


问:
getting the output Optional("test")
I tried the following code

```<code>if let shortURL = shortURL {
     var url = "\(shortURL.absoluteString)"
     MUser.sharedInstance.setMobileReferralId(url)
     self.referralLink.text = url self.copyToClipboard()
}
</code>```

For the url variable, I get the output Optional("Test"). How do I remove the "Optional" part?

答:
To remove the Optional part, you only need to unwrap optional right. example:

if let shortURL = shortURL,
    let url = shortURL.absoluteString {
    print(url)
}
```

Title: getting the output Optional("test")

Body:
I tried the following code

if let shortURL = shortURL {
     var url = "\(shortURL.absoluteString)"
     MUser.sharedInstance.setMobileReferralId(url)
     self.referralLink.text = url self.copyToClipboard()
}

For the url variable, I get the output Optional("Test"). How do I remove the "Optional" part?