问:
Fix broken python opencv installation
Seems I have broken opencv python installation:
pip3 freeze | grep opencv shows nothing, on import cv2 I get error:

```<code>python3
Python 3.7.6 (default, Dec 30 2019, 19:38:26)
[Clang 11.0.0 (clang-1100.0.33.16)] on darwin
Type "help", "copyright", "credits" or "license" for more information.

>>> import cv2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: dlopen(/usr/local/lib/python3.7/site-packages/cv2.cpython-37m-darwin.so, 2): Library not loaded: /usr/local/opt/tbb/lib/libtbbmalloc.dylib
  Referenced from: /usr/local/opt/ceres-solver/lib/libceres.1.dylib
  Reason: image not found

otool -L /usr/local/lib/python3.7/site-packages/cv2.cpython-37m-darwin.so
/usr/local/lib/python3.7/site-packages/cv2.cpython-37m-darwin.so:
    @rpath/libopencv_reg.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_surface_matching.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_xphoto.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_freetype.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_fuzzy.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_hfs.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_img_hash.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_xobjdetect.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_superres.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_bioinspired.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_dpm.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_face.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_line_descriptor.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_saliency.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_ccalib.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_cvv.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_rgbd.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_structured_light.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_videostab.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_aruco.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_bgsegm.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_optflow.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_sfm.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_stitching.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_objdetect.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_tracking.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_plot.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_dnn.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_datasets.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_phase_unwrapping.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_photo.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_ximgproc.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_xfeatures2d.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_ml.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_shape.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_video.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_calib3d.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_features2d.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_flann.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_highgui.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_videoio.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_imgcodecs.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_imgproc.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_core.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    /usr/lib/libc++.1.dylib (compatibility version 1.0.0, current version 800.7.0)
    /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1281.0.0)
</code>```

Is it safe just to remove /usr/local/lib/python3.7/site-packages/cv2.cpython-37m-darwin.so ?

答:
```<code>rm -f /usr/local/lib/python3.7/site-packages/cv2.cpython-37m-darwin.so

# reinstall opencv from source with python support

# Installing tbb via brew fixed the problem:

brew install tbb
</code>```

Title: Fix broken python opencv installation

Body:
Seems I have broken opencv python installation:
pip3 freeze | grep opencv shows nothing, on import cv2 I get error:

python3
Python 3.7.6 (default, Dec 30 2019, 19:38:26)
[Clang 11.0.0 (clang-1100.0.33.16)] on darwin
Type "help", "copyright", "credits" or "license" for more information.

>>> import cv2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: dlopen(/usr/local/lib/python3.7/site-packages/cv2.cpython-37m-darwin.so, 2): Library not loaded: /usr/local/opt/tbb/lib/libtbbmalloc.dylib
  Referenced from: /usr/local/opt/ceres-solver/lib/libceres.1.dylib
  Reason: image not found

otool -L /usr/local/lib/python3.7/site-packages/cv2.cpython-37m-darwin.so
/usr/local/lib/python3.7/site-packages/cv2.cpython-37m-darwin.so:
    @rpath/libopencv_reg.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_surface_matching.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_xphoto.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_freetype.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_fuzzy.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_hfs.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_img_hash.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_xobjdetect.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_superres.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_bioinspired.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_dpm.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_face.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_line_descriptor.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_saliency.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_ccalib.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_cvv.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_rgbd.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_structured_light.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_videostab.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_aruco.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_bgsegm.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_optflow.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_sfm.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_stitching.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_objdetect.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_tracking.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_plot.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_dnn.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_datasets.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_phase_unwrapping.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_photo.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_ximgproc.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_xfeatures2d.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_ml.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_shape.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_video.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_calib3d.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_features2d.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_flann.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_highgui.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_videoio.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_imgcodecs.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_imgproc.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    @rpath/libopencv_core.3.4.dylib (compatibility version 3.4.0, current version 3.4.1)
    /usr/lib/libc++.1.dylib (compatibility version 1.0.0, current version 800.7.0)
    /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1281.0.0)

Is it safe just to remove /usr/local/lib/python3.7/site-packages/cv2.cpython-37m-darwin.so ?


来源: stackexchange

问:
SetWindowsHookEx failing with google chrome. Error code 87 invalid parameter
I am making a tutorial based program and want to be able to hook my code into certain apps to get the tutorial interacting with the app.

My hook code works for most apps except google chrome. I have stripped my code down to the following so you can see it going wrong.

Main.cpp

```<code>#include <Windows.h>
#include <iostream>
#include <psapi.h>
#include <Tlhelp32.h>

unsigned long GetProcId( const std::string& name )
{
    unsigned long res = 0 ;

    HANDLE hSnapShot=CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);
    PROCESSENTRY32 processInfo ;
    processInfo.dwSize=sizeof(PROCESSENTRY32W);

    if( !Process32First( hSnapShot, &processInfo ) )
    {
        CloseHandle( hSnapShot );
        return res ;
    }

    do
    {
        if( NULL != ( strstr ( strlwr ( processInfo.szExeFile ), name.c_str() ) ) )
        {
            res = processInfo.th32ProcessID ;
            break ;
        }
    } while(Process32Next( hSnapShot,&processInfo ));

    CloseHandle( hSnapShot ) ;
    return res ;
}

typedef LRESULT (CALLBACK *DllHookProc)(int nCode, WPARAM wParam, LPARAM lParam);

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
               LPSTR lpCmdLine, int nCmdShow)
{
    unsigned int processid = GetProcId( "chrome.exe" ) ;

    if (processid == 0)
    {
        return 0 ;
    }

    HINSTANCE dllInstance = LoadLibrary("mydll.dll") ;

    if (dllInstance == NULL)
    {
        return 0 ;
    }

    DllHookProc hookProc = (DllHookProc)::GetProcAddress(dllInstance, "HookProc");

    if ( hookProc == NULL)
    {
        FreeLibrary(dllInstance);
        return 0 ;
    }

    HHOOK hook = SetWindowsHookEx(WH_CALLWNDPROC,(HOOKPROC)hookProc,
        dllInstance, processid );

    if (hook == NULL)
    {
        FreeLibrary(dllInstance);
        return 0 ;
    }

    return 0 ;
}
</code>```

Test Dll (mydll.dll)

```<code>LRESULT CALLBACK HookProc (int nCode, WPARAM wParam, LPARAM lParam )
{
    //Pass to the next chain in the process list
    return CallNextHookEx( 0, nCode, wParam, lParam);
}

BOOL APIENTRY DllMain(HANDLE hModule, DWORD dwReason, LPVOID lpReserved)
{
    return TRUE;
}
</code>```

Definition file

```<code>LIBRARY "MYDLL"
EXPORTS
HookProc @1
</code>```

Everything works fine (including getting processId and loading library and getprocaddress) up to the SetWindowsHookEx which returns NULL with error code 87 (invalid parameter).

Both chrome.exe and my code are 32 bit.

Does this work for anyone else or does anyone know what it doesnt work?

Thanks

答:
One possible problem would be if you're building 64bit code, but chrome.exe is 32bit (or the other way around). [See comment & update, this is not the case.]

One suspicious thing in your code is that you're not calling Process32First, and that seems to be required. See for ex: Taking a Snapshot and Viewing Processes.

Last suggestion: you're passing in a process id to SetWindowsHookEx, but that expects a thread id.

ContentLicense: CC BY-SA 3.0

Body:
I am making a tutorial based program and want to be able to hook my code into certain apps to get the tutorial interacting with the app.

My hook code works for most apps except google chrome. I have stripped my code down to the following so you can see it going wrong.

Main.cpp

#include <Windows.h>
#include <iostream>
#include <psapi.h>
#include <Tlhelp32.h>

unsigned long GetProcId( const std::string& name )
{
    unsigned long res = 0 ;

    HANDLE hSnapShot=CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);
    PROCESSENTRY32 processInfo ;
    processInfo.dwSize=sizeof(PROCESSENTRY32W);

    if( !Process32First( hSnapShot, &processInfo ) )
    {
        CloseHandle( hSnapShot );
        return res ;
    }

    do
    {
        if( NULL != ( strstr ( strlwr ( processInfo.szExeFile ), name.c_str() ) ) )
        {
            res = processInfo.th32ProcessID ;
            break ;
        }
    } while(Process32Next( hSnapShot,&processInfo ));

    CloseHandle( hSnapShot ) ;
    return res ;
}

typedef LRESULT (CALLBACK *DllHookProc)(int nCode, WPARAM wParam, LPARAM lParam);

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
               LPSTR lpCmdLine, int nCmdShow)
{
    unsigned int processid = GetProcId( "chrome.exe" ) ;

    if (processid == 0)
    {
        return 0 ;
    }

    HINSTANCE dllInstance = LoadLibrary("mydll.dll") ;

    if (dllInstance == NULL)
    {
        return 0 ;
    }

    DllHookProc hookProc = (DllHookProc)::GetProcAddress(dllInstance, "HookProc");

    if ( hookProc == NULL)
    {
        FreeLibrary(dllInstance);
        return 0 ;
    }

    HHOOK hook = SetWindowsHookEx(WH_CALLWNDPROC,(HOOKPROC)hookProc,
        dllInstance, processid );

    if (hook == NULL)
    {
        FreeLibrary(dllInstance);
        return 0 ;
    }

    return 0 ;
}

Test Dll (mydll.dll)

LRESULT CALLBACK HookProc (int nCode, WPARAM wParam, LPARAM lParam )
{
    //Pass to the next chain in the process list
    return CallNextHookEx( 0, nCode, wParam, lParam);
}

BOOL APIENTRY DllMain(HANDLE hModule, DWORD dwReason, LPVOID lpReserved)
{
    return TRUE;
}

Definition file

LIBRARY "MYDLL"
EXPORTS
HookProc @1

Everything works fine (including getting processId and loading library and getprocaddress) up to the SetWindowsHookEx which returns NULL with error code 87 (invalid parameter).

Both chrome.exe and my code are 32 bit.

Does this work for anyone else or does anyone know what it doesnt work?

Thanks


问:
Bash exceute multuple commands after || if non 0
I have a line of code in my scripts to make sure a conda environment exists and then if not install the environment and download the database for a programme in the environment. I have this code:

```<code>   test -d ~/miniconda3/envs/antismash_v5 || echo "Conda environment does not exist. Initialising conda environment......" && conda env create -f antismash.yml &&  conda activate antismash_v5 && download-antismash-databases
</code>```

But this just exceute everything after the first && regardless of if the test function returns non zero before ||. How can I get this to work as intended?

答:
You can negate the test by using the bang ! and enclose the rest of the commands inside an if statement, that way you don't need the { }

```<code>if ! test -d ~/miniconda3/envs/antismash_v5; then
  command_here &&
  another_command_here &&
  some_more_commands_here &&
  do_more_commands here &&
  .....
fi
</code>```

see help test

help test | grep '^[[:blank:]]*!'

output

! EXPR         True if expr is false.

ContentLicense: CC BY-SA 4.0

Body:
I have a line of code in my scripts to make sure a conda environment exists and then if not install the environment and download the database for a programme in the environment. I have this code:

   test -d ~/miniconda3/envs/antismash_v5 || echo "Conda environment does not exist. Initialising conda environment......" && conda env create -f antismash.yml &&  conda activate antismash_v5 && download-antismash-databases

But this just exceute everything after the first && regardless of if the test function returns non zero before ||. How can I get this to work as intended?

Body:
You can negate the test by using the bang ! and enclose the rest of the commands inside an if statement, that way you don't need the { }

if ! test -d ~/miniconda3/envs/antismash_v5; then
  command_here &&
  another_command_here &&
  some_more_commands_here &&
  do_more_commands here &&
  .....
fi

see help test

help test | grep '^[[:blank:]]*!'

output

! EXPR         True if expr is false.


问:
Doing Inverse of View.bringToFront() in Android
I have a lot of View in my Activity, and I want to make the View named imageView1 at the Background, the last one, exactly the inverse of imageView1.bringToFront();

Are there any method to call for this raison?

thank you.

答:
```<code>view.setOnTouchListener(new View.OnTouchListener){
    @Override
    public boolean onTouch (View v, MotionEvent event){
    if (event.getAction() == MotionEvent.ACTION_MOVE) {
        view.bringToFront()
    } else if (event.getAction() == MotionEvent.ACTION_UP) {
        ViewGroup viewGroup = (ViewGroup) view.getParent();
        sendToBack(viewGroup, view);
    }
}
});

private static void sendToBack(ViewGroup viewGroup, View view) {
    if (viewGroup != null) {
        viewGroup.removeView(child);
        viewGroup.addView(child, 0);
    }
}
</code>```


问:
Fetch Error "Promise returned from fetchData is ignored"
I created a component which is fetching data from an api.

import React, {useState, useEffect} from 'react';

const Users = () => {
    const [users, setUsers] = useState([]);
    useEffect(() => {
        fetchData();
        console.log('effect')
    }, []);

    const fetchData = async () => {
        const url = `https://jsonplaceholder.typicode.com/users`;
        const response = await fetch(url, {
                method: 'GET', // *GET, POST, PUT, DELETE, etc.
                mode: 'cors', // no-cors, *cors, same-origin
            }
        );
        const data = await response.json();
        console.log(data)
    };
    fetchData()

    return (

    );
};

export default Users;```

I created fetch function, but anyway i can't get the response from server. After passing about 2 minutes, i'm getting in console 503 error. Why the fetch doesn't work?

答:
Following changes will help you get around it:

```<code>import React, { useState, useEffect } from "react";

const Users = () => {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    fetchData();
  }, []);

  async function fetchData() {
    const url = `https://jsonplaceholder.typicode.com/users`;
    const response = await fetch(url, {
      method: "GET",
      mode: "cors"
    });
    const data = await response.json();
    setUsers(data);
  }

  return (
    <div style={{ display: "flex", flexDirection: "column" }}>
      {users.map(user => (
        <h1>{user.name}</h1>
      ))}
    </div>
  );
};

export default Users;
</code>```

Let me know if it helps.

Body:
I created a component which is fetching data from an api.

import React, {useState, useEffect} from 'react';

const Users = () => {
    const [users, setUsers] = useState([]);
    useEffect(() => {
        fetchData();
        console.log('effect')
    }, []);

    const fetchData = async () => {
        const url = `https://jsonplaceholder.typicode.com/users`;
        const response = await fetch(url, {
                method: 'GET', // *GET, POST, PUT, DELETE, etc.
                mode: 'cors', // no-cors, *cors, same-origin
            }
        );
        const data = await response.json();
        console.log(data)
    };
    fetchData()

    return (

    );
};

export default Users;

I created fetch function, but anyway i can't get the response from server. After passing about 2 minutes, i'm getting in console 503 error. Why the fetch doesn't work?

Body:
Following changes will help you get around it:

import React, { useState, useEffect } from "react";

const Users = () => {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    fetchData();
  }, []);

  async function fetchData() {
    const url = `https://jsonplaceholder.typicode.com/users`;
    const response = await fetch(url, {
      method: "GET",
      mode: "cors"
    });
    const data = await response.json();
    setUsers(data);
  }

  return (
    <div style={{ display: "flex", flexDirection: "column" }}>
      {users.map(user => (
        <h1>{user.name}</h1>
      ))}
    </div>
  );
};

export default Users;

Let me know if it helps.


问:
How to get opening balance on the first record given accumulated balance in power query
Given table below, where the starting date is variable, as it can be start from any date for a month:

Component | Type | Date   | AccumulateBalance

A         | PO   | 31 Jan | 240

A         | PO   | 1 Feb  | 240

B         | PO   | 28 Jan | 300

B         | PO   | 29 Jan | 300

A         | SO   | 31 Jan | 100

A         | SO   | 1 Feb  | 100

I need to calculate the first opening balance given only the accumulated Balance, and it is reset by Component + Type

Component | Type | Date   | OpenBalance

A         | PO   | 31 Jan | 240

A         | PO   | 1 Feb  | 0

B         | PO   | 28 Jan | 300

B         | PO   | 29 Jan | 0

A         | SO   | 31 Jan | 100

A         | SO   | 1 Feb  | 0

Any helps or advice will be very much appreciated!

Thank you
Andrea

答:
You can use a bit of custom PowerQuery code pasted into home ... advanced editor...

Assuming data is loaded into Table1, the third row will add a column that is the minimum date of all rows with matching Component and Type.  The fourth row then checks to see if the current row's date matches the minimum; if so it shows the balance, otherwise zero

```<code>let Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
#"Changed Type" = Table.TransformColumnTypes(Source,{{"Component", type text}, {"Type", type text}, {"Date", type date}, {"AccumulateBalance", Int64.Type}}),
AddMinDateColumn = Table.AddColumn(#"Changed Type", "Earliest Date", (thisrow) => List.Min(Table.SelectRows(#"Changed Type", each [Component] = thisrow[Component] and [Type] = thisrow[Type])[Date]), type date),
#"Added Custom" = Table.AddColumn(AddMinDateColumn, "OpenBalance", each if [Date]=[Earliest Date] then [AccumulateBalance] else 0)
in #"Added Custom"
</code>```

another way is to select the Component and Type columns, and Group them, using minimum of Date column and AllRows. If you expand the AccumulateBalance column and remove duplicates, that will give you a table of the minimum dates and their values. You can then merge it back into original table matching on Component, Type, and Date, and expand the Balance field. Sample below which can be pasted into Home...advanced editor...  Assumes data is loaded into Table1

```<code>let Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
#"Changed Type" = Table.TransformColumnTypes(Source,{{"Component", type text}, {"Type", type text}, {"Date", type date}, {"AccumulateBalance", Int64.Type}}),
#"Grouped Rows" = Table.Group(#"Changed Type", {"Component", "Type"}, {{"MinDate", each List.Min([Date]), type date}, {"Data", each _, type table}}),
#"Expanded Data" = Table.ExpandTableColumn(#"Grouped Rows", "Data", {"AccumulateBalance"}, {"Data.AccumulateBalance"}),
Table2= Table.Distinct(#"Expanded Data"),
#"Merged Queries" = Table.NestedJoin(#"Changed Type",{"Component", "Type", "Date"},Table2,{"Component", "Type", "MinDate"},"Table2",JoinKind.LeftOuter),
#"Expanded Table2" = Table.ExpandTableColumn(#"Merged Queries", "Table2", {"Data.AccumulateBalance"}, {"OpeningBalance"})
in #"Expanded Table2"
</code>```

Body:
You can use a bit of custom PowerQuery code pasted into home ... advanced editor...

Assuming data is loaded into Table1, the third row will add a column that is the minimum date of all rows with matching Component and Type.  The fourth row then checks to see if the current row's date matches the minimum; if so it shows the balance, otherwise zero

let Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
#"Changed Type" = Table.TransformColumnTypes(Source,{{"Component", type text}, {"Type", type text}, {"Date", type date}, {"AccumulateBalance", Int64.Type}}),
AddMinDateColumn = Table.AddColumn(#"Changed Type", "Earliest Date", (thisrow) => List.Min(Table.SelectRows(#"Changed Type", each [Component] = thisrow[Component] and [Type] = thisrow[Type])[Date]), type date),
#"Added Custom" = Table.AddColumn(AddMinDateColumn, "OpenBalance", each if [Date]=[Earliest Date] then [AccumulateBalance] else 0)
in #"Added Custom"

another way is to select the Component and Type columns, and Group them, using minimum of Date column and AllRows. If you expand the AccumulateBalance column and remove duplicates, that will give you a table of the minimum dates and their values. You can then merge it back into original table matching on Component, Type, and Date, and expand the Balance field. Sample below which can be pasted into Home...advanced editor...  Assumes data is loaded into Table1

let Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
#"Changed Type" = Table.TransformColumnTypes(Source,{{"Component", type text}, {"Type", type text}, {"Date", type date}, {"AccumulateBalance", Int64.Type}}),
#"Grouped Rows" = Table.Group(#"Changed Type", {"Component", "Type"}, {{"MinDate", each List.Min([Date]), type date}, {"Data", each _, type table}}),
#"Expanded Data" = Table.ExpandTableColumn(#"Grouped Rows", "Data", {"AccumulateBalance"}, {"Data.AccumulateBalance"}),
Table2= Table.Distinct(#"Expanded Data"),
#"Merged Queries" = Table.NestedJoin(#"Changed Type",{"Component", "Type", "Date"},Table2,{"Component", "Type", "MinDate"},"Table2",JoinKind.LeftOuter),
#"Expanded Table2" = Table.ExpandTableColumn(#"Merged Queries", "Table2", {"Data.AccumulateBalance"}, {"OpeningBalance"})
in #"Expanded Table2"


问:
Code contain error as unexpected 'if' (T_IF)
I am creating dependent dropdown in which i want stay dropdown value after page reloading. & i found above error in controller file</p>

```<code>public function get_reason_details(Request $req)
    {
        $reason_detail_id=Session::get('reason_detail_id');

        $html = '';
        $get_product_details =
                            DB::table("reason_details")->select("reason_details.*")->where('reason_id',$req->reason_id)->get();

        foreach ($get_product_details as $product) {
            $html .= '<option value="'.$product->reason_detail_id.'"'if($reason_detail_id==$product->reason_detail_id){selected="selected"} '>'.$product->reason_detail.'</option>';
        }
        return response()->json(['html' => $html]);
    }
</code>```

答:
You are writing your if condition inside a php variable that is why you are getting this error.

To solve this you can write your if condition outside K variable and use a variable to select the dropdown. For e.g

```<code>foreach ($get_product_details as $product) {
     $selected = "false";
     if($reason_detail_id==$product->reason_detail_id) {
          $selected="true";
     }

   $html .= '<option  value="'.$product->reason_detail_id.'" selected="'.$selected.'" >'.$product->reason_detail.'</option>';
}
</code>```

Body:
I am creating dependent dropdown in which i want stay dropdown value after page reloading. & i found above error in controller file

public function get_reason_details(Request $req)
    {
        $reason_detail_id=Session::get('reason_detail_id');

        $html = '';
        $get_product_details =
                            DB::table("reason_details")->select("reason_details.*")->where('reason_id',$req->reason_id)->get();

        foreach ($get_product_details as $product) {
            $html .= '<option value="'.$product->reason_detail_id.'"'if($reason_detail_id==$product->reason_detail_id){selected="selected"} '>'.$product->reason_detail.'</option>';
        }
        return response()->json(['html' => $html]);
    }

Body:
You are writing your if condition inside a php variable that is why you are getting this error.

To solve this you can write your if condition outside K variable and use a variable to select the dropdown. For e.g

foreach ($get_product_details as $product) {
     $selected = "false";
     if($reason_detail_id==$product->reason_detail_id) {
          $selected="true";
     }

   $html .= '<option  value="'.$product->reason_detail_id.'" selected="'.$selected.'" >'.$product->reason_detail.'</option>';
}


问:
Does any IDE have a vi keybindings options?
One of the reasons I usually don't use an IDE for development is that I'm so used to vi keybindings that I usually end up messing up my text and putting in lots of ":w"s, and I can't use vi's powerful regex replace mechanism.  Are there any IDEs that allow you to configure vi keybindings or use vi as the editor within the IDE?

Related:

Is it possible to use vi or vim keymap in NetBeans?

答: Try Activestate's Komodo IDE - there's a free Komodo Edit as well not sure if the bindings are included. I really like it particularly for perl and html/css work.</p>

OwnerDisplayName: Phil

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Ali


问:
EF Core strange behaviour
I'm using EF Core 3.0 code first. I have this loop:

```<code>foreach (var profileCount in quantity)
{
    //here I get the exception:
    var oldItem = dc.Stock.Items.FirstOrDefault(a => a.Profile.Id == profileCount.Key);

    if (oldItem == null)
    {
        dc.Stock.Items.Add(new Item
        {
            Price = 0,
            ProfileId = profileCount.Key,
            Quantity = profileCount.Value,
            WasChanged = false
        });
    }
}
</code>```

Stock.Items is empty(not null). First iteration works fine, on the second one I get

System.NullReferenceException: Object reference not set to an instance of an object.

I guess it's because I add and try to read from the same collection, but I'm not sure why exactly this is happening.

答:
When you insert your first item (dc.Stock.Items.Add(new Item) you don't add a Profile, so on the next iteration a.Profile.Id will be a NullReferenceException.

Either assign a Profile when you add a new item, or check for null in your FirstOrDefault.

Title: EF Core strange behaviour

Body:
I'm using EF Core 3.0 code first. I have this loop:

foreach (var profileCount in quantity)
{
    //here I get the exception:
    var oldItem = dc.Stock.Items.FirstOrDefault(a => a.Profile.Id == profileCount.Key);

    if (oldItem == null)
    {
        dc.Stock.Items.Add(new Item
        {
            Price = 0,
            ProfileId = profileCount.Key,
            Quantity = profileCount.Value,
            WasChanged = false
        });
    }
}

Stock.Items is empty(not null). First iteration works fine, on the second one I get

System.NullReferenceException: Object reference not set to an instance of an object.

I guess it's because I add and try to read from the same collection, but I'm not sure why exactly this is happening.


问:
Problem about recursive dict creation in python
I've seen this bit of code online:

```<code>class StreamChecker(object):
    def __init__(self, words):
        """
        :type words: List[str]
        """
        print(words)
        self.waitlist = []
        self.trie = dict()
        for word in words:
            temp_dict = self.trie
            for letter in word:
                temp_dict = temp_dict.setdefault(letter, dict())

            temp_dict['#'] = '#'

if __name__ == '__main__':
    a = StreamChecker(['abc', 'wef', 'ykj'])
    print(a.trie)
</code>```

After initiation, print self.trie gets {'a': {'b': {'c': {'#': '#'}}}, 'w': {'e': {'f': {'#': '#'}}}, 'y': {'k': {'j': {'#': '#'}}}}

I'm confused about this line 'temp_dict = temp_dict.setdefault(letter, dict())' in the code. As every time setdefault will return an empty dict {}, why self.trie is changed every time since setdefault is only used upon an empty dict? To my understanding, self.trie will only be changed once for every word and self.trie should be like {'a': {}, 'w': {}, 'y': {}}

Can someone explain this to me? Thanks

答:
```<code>>>> help(dict.setdefault)
setdefault(self, key, default=None, /)
    Insert key with a value of default if key is not in the dictionary.

    Return the value for key if key is in the dictionary, else default.
</code>```

One empty dict is not necessarily the same object as another empty dict. What's happening is that the line

```<code>temp_dict = temp_dict.setdefault(letter, dict())
</code>```

is first adding a new key to the current temp_dict (with the corresponding value being an empty dict), and then returning the reference to that newly-added value. When it gets run in the loop, it ends up recursively adding new dictionaries to whatever the original was (that is, self.trie).

Because the nested dict we're modifying is contained within self.trie, we can see our change reflected in self.trie.

It might help to decompose this statement:

```<code>temp_dict = temp_dict.setdefault(letter, dict())
</code>```

into this:

```<code>if letter not in temp_dict:
    temp_dict[letter] = dict()  # create a new dict, and put it inside the current dict
temp_dict = temp_dict[letter]   # jump inside the new dict that we just created,
                                # or the existing dict that was there if it already existed.
</code>```

Body:
I've seen this bit of code online:

class StreamChecker(object):
    def __init__(self, words):
        """
        :type words: List[str]
        """
        print(words)
        self.waitlist = []
        self.trie = dict()
        for word in words:
            temp_dict = self.trie
            for letter in word:
                temp_dict = temp_dict.setdefault(letter, dict())

            temp_dict['#'] = '#'

if __name__ == '__main__':
    a = StreamChecker(['abc', 'wef', 'ykj'])
    print(a.trie)

After initiation, print self.trie gets {'a': {'b': {'c': {'#': '#'}}}, 'w': {'e': {'f': {'#': '#'}}}, 'y': {'k': {'j': {'#': '#'}}}}

I'm confused about this line 'temp_dict = temp_dict.setdefault(letter, dict())' in the code. As every time setdefault will return an empty dict {}, why self.trie is changed every time since setdefault is only used upon an empty dict? To my understanding, self.trie will only be changed once for every word and self.trie should be like {'a': {}, 'w': {}, 'y': {}}

Can someone explain this to me? Thanks

Body:
>>> help(dict.setdefault)
setdefault(self, key, default=None, /)
    Insert key with a value of default if key is not in the dictionary.

    Return the value for key if key is in the dictionary, else default.

One empty dict is not necessarily the same object as another empty dict. What's happening is that the line

temp_dict = temp_dict.setdefault(letter, dict())

is first adding a new key to the current temp_dict (with the corresponding value being an empty dict), and then returning the reference to that newly-added value. When it gets run in the loop, it ends up recursively adding new dictionaries to whatever the original was (that is, self.trie).

Because the nested dict we're modifying is contained within self.trie, we can see our change reflected in self.trie.

It might help to decompose this statement:

temp_dict = temp_dict.setdefault(letter, dict())

into this:

if letter not in temp_dict:
    temp_dict[letter] = dict()  # create a new dict, and put it inside the current dict
temp_dict = temp_dict[letter]   # jump inside the new dict that we just created,
                                # or the existing dict that was there if it already existed.


问:
Problem with accessing an array from inside a promise
So I have this code which essentially sends a message with results as a string then sends a message again to ask the user to select one of the elements inside the results array and then tries to assign the array content of results inside the myObj property using this which does not work (returns undefined).

I've read that this can refer to

the global object in a function.

can that apply here?.

Here is the sample:

                        let myObj = {
                           testArray: []
                        };

                        let results = [1,2,3]´;

                        send(results.join("\n"))//sends array as message
                            .then(m => { //premise returns the same array as message
                                send(`Please type a number.`)
                                    .then(m => { //same for reply, returns `Please type a number`
                                        obj = {
                                            testArray: this.results //<---- here results is undefined
                                        };
                                    })
                                    .catch(err => console.error(err));
                            })
                            .catch(err => {
                                console.error(err);
                            })
                    })
```

Would there be anyway to use the this keyword to get access to the results array defined earlier and if yes what would be it's role in this situation?
Thanks in advance.

答:
The window object is the Global Object in the Browser. Any Global Variables or Functions can be accessed as properties of the window object. Because 'this' depends on the context.

Either assign 'this' to a variable and then reuse that variable inside the function or just say results(which may not be great option). Unless you have multiple 'results' variable defined you wont have a problem.

Body:
So I have this code which essentially sends a message with results as a string then sends a message again to ask the user to select one of the elements inside the results array and then tries to assign the array content of results inside the myObj property using this which does not work (returns undefined).

I've read that this can refer to

the global object in a function.

can that apply here?.

Here is the sample:

                        let myObj = {
                           testArray: []
                        };

                        let results = [1,2,3]´;

                        send(results.join("\n"))//sends array as message
                            .then(m => { //premise returns the same array as message
                                send(`Please type a number.`)
                                    .then(m => { //same for reply, returns `Please type a number`
                                        obj = {
                                            testArray: this.results //<---- here results is undefined
                                        };
                                    })
                                    .catch(err => console.error(err));
                            })
                            .catch(err => {
                                console.error(err);
                            })
                    })

Would there be anyway to use the this keyword to get access to the results array defined earlier and if yes what would be it's role in this situation?
Thanks in advance.


问:
Find which element of list is a key in a dictionary and what is it's value
I have a dictionary:

```<code>classes_dictionary = {'/m/09x0r': 'Speech', '/m/03qc9zr': 'Screaming'}
</code>```

and a list:

```<code>labels_list = ['/m/03k3r', '/m/04rlf', '/m/07q5rw0', '/m/09x0r', '/m/0jbk']
</code>```

labels_list will always contain at least one element which is a key of classes_dictionary. I wish to extract which classes are those with the lowest computational complexity. In this example, '/m/09x0r' will be translated into 'Speech'. my solution:

```<code>class_str = list()
for k in labels_list:
    print(k)
    if k in self.classes_dictionary:
        class_str.append(self.classes_dictionary[k])
</code>```

I do not mind if the output is a list or any other type. Also, for generality of the question I am assuming only a single element of labels_list is a key, though the best answer may consider both cases.

Is there a more efficient way to implement this? I am asking on both, implementation efficiency

答:
you could use the intersection of the dict keys with the elements from labels_list in a list comprehension:

```<code>class_str = [classes_dictionary[e] for e in set(classes_dictionary).intersection(labels_list)]
</code>```

output:

```<code>['Speech']
</code>```

Body:
I have a dictionary:

classes_dictionary = {'/m/09x0r': 'Speech', '/m/03qc9zr': 'Screaming'}

and a list:

labels_list = ['/m/03k3r', '/m/04rlf', '/m/07q5rw0', '/m/09x0r', '/m/0jbk']

labels_list will always contain at least one element which is a key of classes_dictionary. I wish to extract which classes are those with the lowest computational complexity. In this example, '/m/09x0r' will be translated into 'Speech'. my solution:

class_str = list()
for k in labels_list:
    print(k)
    if k in self.classes_dictionary:
        class_str.append(self.classes_dictionary[k])

I do not mind if the output is a list or any other type. Also, for generality of the question I am assuming only a single element of labels_list is a key, though the best answer may consider both cases.

Is there a more efficient way to implement this? I am asking on both, implementation efficiency

Body:
you could use the intersection of the dict keys with the elements from labels_list in a list comprehension:

class_str = [classes_dictionary[e] for e in set(classes_dictionary).intersection(labels_list)]

output:

['Speech']


问:
Cloud-init to configure an Ubuntu docker container?
Is it possible to use a cloud-init configuration file to define commands to be executed when a docker container is started?

I'd like to test the provisioning of an Ubuntu virtual machine using a docker container.
My idea is to provide the same cloud-init config file to an Ubuntu docker container.

答:
No.  If you want to test a VM setup, you need to use actual virtualization technology.  The VM and Docker runtime environments are extremely different and you can't just substitute one technology for the other.  A normal Linux VM startup will run a raft of daemons and startup scripts – systemd, crond, sshd, ifconfig, cloud-init, ... – but a Docker container will start none of these and will only run the single process in the container.

If your cloud-init script is ultimately running a docker run command, you can provide an alternate command to that container the same way you could docker run on your development system.  But a Docker container won't look to places like the EC2 metadata service to find its own configuration usually, and it'd be unusual for a container to run cloud-init at all.


问:
add HyperLink to  in table with javascript
How can I add an hyperlink to a  in a dynamic table?

I need the 1st  to be an hyperlink to a url + cell value.

Table dynamic creation :

for (var i = 0; i < riskData.length; i++) {
  $("#grdDemo3").append("
" + riskData[i].r_id +
    "	" + riskData[i].r_team + "
");
}
```

答:
You can always add an anchor tag to td element and make it look like a whole table cell.

table {
  border-collapse: collapse;
}

td {
  border: 1px solid #CCCCCC;
  padding: 12px;
}

table tr td a {
  display: block;
  height: 100%;
  width: 100%;
  background: #F2F2F2;
  text-decoration: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tr>
    <td>
      <span>Some Text</span>
    </td>
    <td>some content
    </td>
  </tr>
  <tr>
    <td>
      hello here </td>
    <td>some content
    </td>
  </tr>
  <tr>
    <td>
      <span>Some Text</span>
    </td>
    <td>some content
    </td>
  </tr>
  <tr>
    <td>
      <span>Some Text</span>
    </td>
    <td>some content
    </td>
  </tr>
</table></code>```

Title: add HyperLink to <td> in table with javascript

Body:
You can always add an anchor tag to td element and make it look like a whole table cell.

table {
  border-collapse: collapse;
}

td {
  border: 1px solid #CCCCCC;
  padding: 12px;
}

table tr td a {
  display: block;
  height: 100%;
  width: 100%;
  background: #F2F2F2;
  text-decoration: none;
}

<table>
  <tr>
    <td>
      <a href="https://www.google.com/"><span>Some Text</span></a>
    </td>
    <td>some content
    </td>
  </tr>
  <tr>
    <td>
      hello here </td>
    <td>some content
    </td>
  </tr>
  <tr>
    <td>
      <a href="https://www.google.com/"><span>Some Text</span></a>
    </td>
    <td>some content
    </td>
  </tr>
  <tr>
    <td>
      <a href="https://www.google.com/"><span>Some Text</span></a>
    </td>
    <td>some content
    </td>
  </tr>
</table>


问:
Help in specify attribute of dynamic generated table in jquery
I am facing a problem to how to add the attributes of table like width, cell spacing.

```<code>var newTable = $("<table />",{id: 'myTable'+tab_counter});
newTable.appendTo('#dialog'+tab_counter);
</code>```

if i add in table tag it still doesn't do anything.

答:
Not really sure what's hard here; your code is almost there:</p>

```<code>$('<table/>', {id: 'myTable' + tab_counter, width: '100%', cellSpacing: '12px'});
</code>```

Body:
I am facing a problem to how to add the attributes of table like width, cell spacing.

var newTable = $("
",{id: 'myTable'+tab_counter});
newTable.appendTo('#dialog'+tab_counter);

if i add in table tag it still doesn't do anything.

Body:
Not really sure what's hard here; your code is almost there:

$('<table/>', {id: 'myTable' + tab_counter, width: '100%', cellSpacing: '12px'});


问:
Stash the difference between current branch and master to apply it to an old commit
how can I stash the difference between current branch and master to apply it to an old commit, in other words I should apply a new feature in current version(Master) and old version(old Master commit 1 year ago).</p>

答:
There are few ways to apply a new feature to any branch on your master:

1.Cherry-pick all commits one by one using

```<code>git cherry-pick hash_of_commit
</code>```

But it will take some time to do if you have a lot of commits.

Squash your commits you would like to apply into one commit and then cherry-pick this one (already squashed commit) to any branch you would like to.

To squash you can use git rebase -i hash_of_the_commit - this command would do an interactive rebase to hash_of_the_commit, which should be one commit before you started developing feature. Then in interactive mode you mark all commits to squash. Might lead to conflicts while squashing.

3.Create patch

```<code>git diff from-commit to-commit > output-file
</code>```

and then apply patch to your other branch:

```<code>git apply output-file
</code>```

Body:
There are few ways to apply a new feature to any branch on your master:

1.Cherry-pick all commits one by one using

git cherry-pick hash_of_commit

But it will take some time to do if you have a lot of commits.

Squash your commits you would like to apply into one commit and then cherry-pick this one (already squashed commit) to any branch you would like to.

To squash you can use git rebase -i hash_of_the_commit - this command would do an interactive rebase to hash_of_the_commit, which should be one commit before you started developing feature. Then in interactive mode you mark all commits to squash. Might lead to conflicts while squashing.

3.Create patch

git diff from-commit to-commit > output-file

and then apply patch to your other branch:

git apply output-file


问:
Find the location nearest to the current location from an array of three locations and compare that which one is nearest to the current location
```<code>ArrayList<LatLng> arrayList= new ArrayList<LatLng>();
LatLng near = new LatLng(33.549232, 73.125256);
LatLng pass = new LatLng(33.549844, 73.125849);
LatLng qareeb = new LatLng(33.549603, 73.124201);

public void onMapReady(GoogleMap googleMap) {
    mMap= googleMap;
    for (int i =0; i<arrayList.size();i++){
        mMap.addMarker(new MarkerOptions().position(arrayList.get(i)).title("Marker").snippet("and snippet")
                .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE)));
        LatLng latLng = new LatLng(currentLocation.getLatitude(),currentLocation.getLongitude());
        MarkerOptions markerOptions = new MarkerOptions().position(latLng).title("Main Yahan hn");
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(arrayList.get(i),15));
        mMap.animateCamera(CameraUpdateFactory.zoomIn());
        mMap.animateCamera(CameraUpdateFactory.zoomTo(15), 2000, null);
        /*mMap.animateCamera(CameraUpdateFactory.zoomTo(15.0f));*/
        mMap.moveCamera(CameraUpdateFactory.newLatLng(arrayList.get(i)));
        googleMap.addMarker(markerOptions);

    }
}
</code>```

Above is my code and I want to create 3 points which compare to my current location that which one is near to the current location.

答:
The question which you are asking and the code which you have posted are not complete. The code simply enables GoogleMaps on the Activity. Instead of coding the entire solution to you, I would explain you the logic and expect you try it out at your end and repost the updated answer here if required.

Steps:

Fetch the current location of the device using FusedLocationProviderClient and store the value in a variable (say currentLocation). (Get the last known location)

Use Location class to find the distance between point1 and currentLocation. (say d1). (distanceBetween)

Use the same process to find the distances between point2 and point3 from the currentLocation.

Now you will have 3 distance variables, d1, d2 and d3. I guess you'll be able to find the shortest of these easily.

Body:
ArrayList<LatLng> arrayList= new ArrayList<LatLng>();
LatLng near = new LatLng(33.549232, 73.125256);
LatLng pass = new LatLng(33.549844, 73.125849);
LatLng qareeb = new LatLng(33.549603, 73.124201);

public void onMapReady(GoogleMap googleMap) {
    mMap= googleMap;
    for (int i =0; i<arrayList.size();i++){
        mMap.addMarker(new MarkerOptions().position(arrayList.get(i)).title("Marker").snippet("and snippet")
                .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE)));
        LatLng latLng = new LatLng(currentLocation.getLatitude(),currentLocation.getLongitude());
        MarkerOptions markerOptions = new MarkerOptions().position(latLng).title("Main Yahan hn");
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(arrayList.get(i),15));
        mMap.animateCamera(CameraUpdateFactory.zoomIn());
        mMap.animateCamera(CameraUpdateFactory.zoomTo(15), 2000, null);
        /*mMap.animateCamera(CameraUpdateFactory.zoomTo(15.0f));*/
        mMap.moveCamera(CameraUpdateFactory.newLatLng(arrayList.get(i)));
        googleMap.addMarker(markerOptions);

    }
}

Above is my code and I want to create 3 points which compare to my current location that which one is near to the current location.


问:
Word2Vec compare vectors from different models with different sizes
I have trained several word2vec models using gensim for different languages, but the size is different for each of them.

vectors are obtained like this:

```<code>vec_sp = word_vectors_sp.get_vector("uno")
</code>```

How to use vec_sp as input for different model with different vector size:

```<code>word_vectors_en.most_similar(positive=[vec_sp], topn=1)
</code>```

to obtain the corresponding word in the second model

答:
The systematic approach to the problem of being able to compare across n different embedded vector spaces with different dimensions d_1,...d_n is to reduce the dimensionality of the vectors in each space to a value m where m < min(d_1,...d_n).

There are many ways of doing it. By Johnson Lindenstrauss lemma, you could do it by applying random projections in each space separately, i.e.,
choose a random projection matrix Ri of size m x d_i for each set of vectors Xi_{d_i} x N (assuming each space has N vectors) and then compute

Xi' _{m x N} = Ri _{m x d_i} x Xi _{d_i x N} (dimensions of the matrix are shown alongside).

After applying this transformation for each space, you will end up with i such spaces... the dimension of each will be m, which means that you will be able to compute dot products between them.

One more approach for dimensionality reduction is to use PCA. Python's sklearn provides implementations for both random projections and PCA.

In terms of a concrete example, if you have two vector spaces of 100 and 200 dimensions each with 100,000 vectors then reduce each to 20 dimensions (arbitrarily chosen) by PCA or random projection. You would then be able to compare these 20 dimensional vectors by computing distances or inner products.

Body:
I have trained several word2vec models using gensim for different languages, but the size is different for each of them.

vectors are obtained like this:

vec_sp = word_vectors_sp.get_vector("uno")

How to use vec_sp as input for different model with different vector size:

word_vectors_en.most_similar(positive=[vec_sp], topn=1)

to obtain the corresponding word in the second model


问:
How I can set JSON serialization rules for validation messages?
I have the following configuration of JSON policy in my Startup.cs:

```<code>services.AddControllers().ConfigureApiBehaviorOptions(options =>
    {
        options.SuppressInferBindingSourcesForParameters = true;
        options.SuppressModelStateInvalidFilter = true;
        // options.SuppressMapClientErrors = true;
    })
    .AddJsonOptions(options =>
    {
        options.JsonSerializerOptions.PropertyNamingPolicy =
            SnakeCaseNamingPolicy.Instance;
    });
</code>```

And policy:

```<code>public class SnakeCaseNamingPolicy : JsonNamingPolicy
{
    public static SnakeCaseNamingPolicy Instance { get; } = new SnakeCaseNamingPolicy();

    public override string ConvertName(string name)
    {
        // Conversion to other naming conventaion goes here. Like SnakeCase, KebabCase etc.
        return name.ToSnakeCase();
    }
}
</code>```

And ToSnakeCase:

```<code>public static class StringUtils
{
    public static string ToSnakeCase(this string str)
    {
        return string.Concat(str.Select((x, i) => i > 0 && char.IsUpper(x) ? "_" + x.ToString()
            : x.ToString())).ToLower();
    }
}
</code>```

I use it to have ability of getting JSON in snake_case.

Here is my model:

```<code>public class CategoryViewModelCreate
{
    [Required(ErrorMessage = "Inner id is required")]
    [JsonPropertyName("inner_id")]
    public int? InnerId { get; set; }

    [Required(ErrorMessage = "Name is required")]
    [JsonPropertyName("name")]
    public string Name { get; set; }
}
</code>```

My controller is:

```<code>public async Task<IActionResult> Create([FromBody] CategoryViewModelCreate viewModel)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }
</code>```

And now it works fine if I have the following JSON:

```<code>{
    "name": "testing",
    "inner_id": 123
}
</code>```

But if my JSON is (without name):

```<code>{
    "inner_id": 123
}
</code>```

I have the following validation message:

```<code>{
  "Name": [
    "Name is required"
  ]
}
</code>```

But it's wrong. I would like to have (name instead of Name and snake_case for the other keys):

```<code>{
  "name": [
    "Name is required"
  ]
}
</code>```

How to set up it? Where? As you can see I'm trying to use [JsonPropertyName("name")],
but without any success(

I appreciate any help.

答:
You can create your base inherited controller and ovveride BadRequest(ModelStateDictionary m) method

```<code>BadRequest(ModelStateDictionary model)
{
    var newModel = model.ToDictionary(
            x => x.Key.ToCamelCase(),
            x => kvp.Value
        );
    base.BadRequest(newModel);
}
</code>```

Something like this

Body:
I have the following configuration of JSON policy in my Startup.cs:

services.AddControllers().ConfigureApiBehaviorOptions(options =>
    {
        options.SuppressInferBindingSourcesForParameters = true;
        options.SuppressModelStateInvalidFilter = true;
        // options.SuppressMapClientErrors = true;
    })
    .AddJsonOptions(options =>
    {
        options.JsonSerializerOptions.PropertyNamingPolicy =
            SnakeCaseNamingPolicy.Instance;
    });

And policy:

public class SnakeCaseNamingPolicy : JsonNamingPolicy
{
    public static SnakeCaseNamingPolicy Instance { get; } = new SnakeCaseNamingPolicy();

    public override string ConvertName(string name)
    {
        // Conversion to other naming conventaion goes here. Like SnakeCase, KebabCase etc.
        return name.ToSnakeCase();
    }
}

And ToSnakeCase:

public static class StringUtils
{
    public static string ToSnakeCase(this string str)
    {
        return string.Concat(str.Select((x, i) => i > 0 && char.IsUpper(x) ? "_" + x.ToString()
            : x.ToString())).ToLower();
    }
}

I use it to have ability of getting JSON in snake_case.

Here is my model:

public class CategoryViewModelCreate
{
    [Required(ErrorMessage = "Inner id is required")]
    [JsonPropertyName("inner_id")]
    public int? InnerId { get; set; }

    [Required(ErrorMessage = "Name is required")]
    [JsonPropertyName("name")]
    public string Name { get; set; }
}

My controller is:

public async Task<IActionResult> Create([FromBody] CategoryViewModelCreate viewModel)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

And now it works fine if I have the following JSON:

{
    "name": "testing",
    "inner_id": 123
}

But if my JSON is (without name):

{
    "inner_id": 123
}

I have the following validation message:

{
  "Name": [
    "Name is required"
  ]
}

But it's wrong. I would like to have (name instead of Name and snake_case for the other keys):

{
  "name": [
    "Name is required"
  ]
}

How to set up it? Where? As you can see I'm trying to use [JsonPropertyName("name")],
but without any success(

I appreciate any help.

Body:
You can create your base inherited controller and ovveride BadRequest(ModelStateDictionary m) method

BadRequest(ModelStateDictionary model)
{
    var newModel = model.ToDictionary(
            x => x.Key.ToCamelCase(),
            x => kvp.Value
        );
    base.BadRequest(newModel);
}

Something like this


问:
What does mean of "return (int, int);" in c language?
I am found below example and I can't understand the calculation of the return statement (return (kk, ll);).

Is there anybody who explain to me about the calculation of the return statement?

```<code>#include<stdio.h>

int addmult(int ii, int jj)
{
    int kk, ll;
    kk = ii + jj;
    ll = ii * jj;
    return (kk, ll);
}

int main()
{
    int i=3, j=4, k, l;
    k = addmult(i, j);
    l = addmult(i, j);
    printf("%d %d\n", k, l);
    return 0;
}
</code>```

答:
Whoever wrote this seems to be under the impression that C allows returning multiple values in a list like Python does, or that this syntax dictates the values that get returns on the first and second calls to the function.  That is not the case.

What you see here is an example of the comma operator.  The left operand is evaluated and its value discarded, then the right operand is evaluated and its value becomes the value of the expression.

So the effect of this:

```<code>return (kk, ll);
</code>```

Is to return the value of ll.

Body:
I am found below example and I can't understand the calculation of the return statement (return (kk, ll);).

Is there anybody who explain to me about the calculation of the return statement?

#include<stdio.h>

int addmult(int ii, int jj)
{
    int kk, ll;
    kk = ii + jj;
    ll = ii * jj;
    return (kk, ll);
}

int main()
{
    int i=3, j=4, k, l;
    k = addmult(i, j);
    l = addmult(i, j);
    printf("%d %d\n", k, l);
    return 0;
}

Body:
Whoever wrote this seems to be under the impression that C allows returning multiple values in a list like Python does, or that this syntax dictates the values that get returns on the first and second calls to the function.  That is not the case.

What you see here is an example of the comma operator.  The left operand is evaluated and its value discarded, then the right operand is evaluated and its value becomes the value of the expression.

So the effect of this:

return (kk, ll);

Is to return the value of ll.


问:
ApiPlatform Regex property filter with Postgresql
I'm trying to add a custom filter to an entity in my ApiPlatform project that allows me to filter on specific property given a regex pattern.

Following the ApiPlatform documentation I came up with the following class (this is a near copy of the their example, only the where-clause is different):

<?php

namespace App\Filter;

use ApiPlatform\Core\Bridge\Doctrine\Orm\Filter\AbstractContextAwareFilter;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Util\QueryNameGeneratorInterface;
use Doctrine\ORM\QueryBuilder;

final class RegexFilter extends AbstractContextAwareFilter
{
    protected function filterProperty(
        string $property,
        $value,
        QueryBuilder $queryBuilder,
        QueryNameGeneratorInterface $queryNameGenerator,
        string $resourceClass,
        string $operationName = null
    ) {
        // otherwise filter is applied to order and page as well
        if (
            !$this->isPropertyEnabled($property, $resourceClass) ||
            !$this->isPropertyMapped($property, $resourceClass)
        ) {
            return;
        }

        $parameterName = $queryNameGenerator->generateParameterName($property); // Generate a unique parameter name to avoid collisions with other filters
        $queryBuilder
            ->andWhere(sprintf('(o.%s ~ :%s) = true', $property, $parameterName))
            ->setParameter($parameterName, $value);
    }

    // This function is only used to hook in documentation generators (supported by Swagger and Hydra)
    public function getDescription(string $resourceClass): array
    {
        if (!$this->properties) {
            return [];
        }

        $description = [];
        foreach ($this->properties as $property => $strategy) {
            $description["regexp_$property"] = [
                'property' => $property,
                'type' => 'string',
                'required' => false,
                'swagger' => [
                    'description' => 'Filter using a regex. This will appear in the Swagger documentation!',
                    'name' => 'Custom name to use in the Swagger documentation',
                    'type' => 'Will appear below the name in the Swagger documentation',
                ],
            ];
        }

        return $description;
    }
}

```

<p>When I run my code this results in the following DQL: </p>

```SELECT o FROM App\Entity\Vehicle o WHERE (o.licensePlate ~ :licensePlate_p1) = true ORDER BY o.id ASC
```

<p>However I cannot get the Lexer to understand the tilde ~ character:</p>

```Doctrine\ORM\Query\QueryException
[Syntax Error] line 0, col 56: Error: Expected Doctrine\ORM\Query\Lexer::T_CLOSE_PARENTHESIS, got '~'
```

How can I make Doctrine understand the tilde?

答:
Turns out I was pretty close, simPod's answer helped me fill the gaps.

I copied his custom DQL function and added it in my Doctrine yaml configuration

In my RegexFilter I had to slightly modify the where-clause:

```<code>->andWhere(sprintf('REGEX(o.%s, :%s) = true', $property, $parameterName))
</code>```

Body:
I'm trying to add a custom filter to an entity in my ApiPlatform project that allows me to filter on specific property given a regex pattern.

Following the ApiPlatform documentation I came up with the following class (this is a near copy of the their example, only the where-clause is different):

<?php

namespace App\Filter;

use ApiPlatform\Core\Bridge\Doctrine\Orm\Filter\AbstractContextAwareFilter;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Util\QueryNameGeneratorInterface;
use Doctrine\ORM\QueryBuilder;

final class RegexFilter extends AbstractContextAwareFilter
{
    protected function filterProperty(
        string $property,
        $value,
        QueryBuilder $queryBuilder,
        QueryNameGeneratorInterface $queryNameGenerator,
        string $resourceClass,
        string $operationName = null
    ) {
        // otherwise filter is applied to order and page as well
        if (
            !$this->isPropertyEnabled($property, $resourceClass) ||
            !$this->isPropertyMapped($property, $resourceClass)
        ) {
            return;
        }

        $parameterName = $queryNameGenerator->generateParameterName($property); // Generate a unique parameter name to avoid collisions with other filters
        $queryBuilder
            ->andWhere(sprintf('(o.%s ~ :%s) = true', $property, $parameterName))
            ->setParameter($parameterName, $value);
    }

    // This function is only used to hook in documentation generators (supported by Swagger and Hydra)
    public function getDescription(string $resourceClass): array
    {
        if (!$this->properties) {
            return [];
        }

        $description = [];
        foreach ($this->properties as $property => $strategy) {
            $description["regexp_$property"] = [
                'property' => $property,
                'type' => 'string',
                'required' => false,
                'swagger' => [
                    'description' => 'Filter using a regex. This will appear in the Swagger documentation!',
                    'name' => 'Custom name to use in the Swagger documentation',
                    'type' => 'Will appear below the name in the Swagger documentation',
                ],
            ];
        }

        return $description;
    }
}

When I run my code this results in the following DQL:

SELECT o FROM App\Entity\Vehicle o WHERE (o.licensePlate ~ :licensePlate_p1) = true ORDER BY o.id ASC

However I cannot get the Lexer to understand the tilde ~ character:

Doctrine\ORM\Query\QueryException
[Syntax Error] line 0, col 56: Error: Expected Doctrine\ORM\Query\Lexer::T_CLOSE_PARENTHESIS, got '~'

How can I make Doctrine understand the tilde?

Body:
Turns out I was pretty close, simPod's answer helped me fill the gaps.

I copied his custom DQL function and added it in my Doctrine yaml configuration

In my RegexFilter I had to slightly modify the where-clause:

->andWhere(sprintf('REGEX(o.%s, :%s) = true', $property, $parameterName))


问:
how to compare type of an object's instance to a generic type?
how can i write this code in java?

```<code>public class ComponentsManager
    {
        private List<IComponent> list = new ArrayList<IComponent>();

        public <U extends IComponent> U GetComponent() {

            for (IComponent component : list) {

                if(component instanceof U)
                {
                    return component;
                }
            }
        }
}
</code>```

but i cant perform instanceof on generic types. how should i do it?
thanks.

答:
You could try adding a couple of 'test' methods:

```<code>private static <U extends IComponent> boolean testComponent(U u) {
  return true;
}

private static boolean testComponent(Object o) {
  return false;
}
</code>```

Then, use testComponent(component) instead of component instanceof U.

Example code:

```<code>import java.util.*;

class IComponent {
}

class T1 extends IComponent {
}

public class Test {

  public static <U extends IComponent> boolean testComponent(U u) {
    return true;
  }

  public static boolean testComponent(Object o) {
    return false;
  }

  public static void main(String[] args) {
    T1 t = new T1();
    System.out.println("hm? " + (testComponent(t) ? "true" : "false"));
  }
}
</code>```

Output:

hm? true

Body:
how can i write this code in java?

public class ComponentsManager
    {
        private List<IComponent> list = new ArrayList<IComponent>();

        public  U GetComponent() {

            for (IComponent component : list) {

                if(component instanceof U)
                {
                    return component;
                }
            }
        }
}

but i cant perform instanceof on generic types. how should i do it?
thanks.

Body:
You could try adding a couple of 'test' methods:

private static <U extends IComponent> boolean testComponent(U u) {
  return true;
}

private static boolean testComponent(Object o) {
  return false;
}

Then, use testComponent(component) instead of component instanceof U.

Example code:

import java.util.*;

class IComponent {
}

class T1 extends IComponent {
}

public class Test {

  public static <U extends IComponent> boolean testComponent(U u) {
    return true;
  }

  public static boolean testComponent(Object o) {
    return false;
  }

  public static void main(String[] args) {
    T1 t = new T1();
    System.out.println("hm? " + (testComponent(t) ? "true" : "false"));
  }
}

Output:

hm? true


问:
error binding 'matMenuTriggerFor' to button in simple component
I am trying to add a menu material to a simple project see:

https://stackblitz.com/edit/angular-11cjdg?file=src/app/header/header.component.ts

But I keep getting Can't bind to 'matMenuTriggerFor' since it isn't a known property of 'button'.

I have tryed to follow https://run.stackblitz.com/api/angular/v1?file=src%2Fapp%2Fmenu-icons-example.ts and https://stackblitz.com/edit/add-angular-material?file=src%2Fangular-material%2Fangular-material.module.ts but this error will not go away. Can anyone see what I am doing wrong here?

答:
You have to import you angular material modules in app.module, not in the component
So your app.module should look like this.

```<code>@NgModule({
  imports:      [ BrowserModule, FormsModule,  MatButtonModule,
    MatInputModule,    MatCardModule,    MatToolbarModule ],
  declarations: [ AppComponent, HelloComponent, HeaderComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }
</code>```

and you header component like this

```<code>@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css'],
})
export class HeaderComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}
</code>```

Body:
You have to import you angular material modules in app.module, not in the component
So your app.module should look like this.

@NgModule({
  imports:      [ BrowserModule, FormsModule,  MatButtonModule,
    MatInputModule,    MatCardModule,    MatToolbarModule ],
  declarations: [ AppComponent, HelloComponent, HeaderComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

and you header component like this

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css'],
})
export class HeaderComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}


问:
Creating multiple consumers for a Single kafka topic
I have a spring boot application. I wish to implement a functionaly that consumes from a Kafka topic and for every consumed message it calls another method that does some processing on the message and then stores it in a database. The source kafka topic has 12 partitions. I want to create 6 or 12 kafka consumers under the same consumer group. All of the consumers will consume messages from Kafka and call the function. I am not able to get to a good design for this. Can someone help me ? </p>

答:
We have pretty the same need for a topic with 4 partitions, we created a consumer group with 2 members, and we assigned each member ( instance of our consumer) two partitions.
  If you are using spring you can select how many members will be created by instances with this parameter:

```<code># For Kafka concurrency
spring.kafka.listener.concurrency=2
</code>```

If you are using the Kafka library this parameters should be in the parameters of your consumer.
  Be aware to not exceed you number of threads availables.

Body:
We have pretty the same need for a topic with 4 partitions, we created a consumer group with 2 members, and we assigned each member ( instance of our consumer) two partitions.
  If you are using spring you can select how many members will be created by instances with this parameter:

# For Kafka concurrency
spring.kafka.listener.concurrency=2

If you are using the Kafka library this parameters should be in the parameters of your consumer.
  Be aware to not exceed you number of threads availables.


问:
How can i create an autocomplete with Jquery?
I'm creating a Django site, on a certain template i added an Ajax form and i would like to add an autocomplete feature, in order to make navigation easier.

My main problem is that the data i should search is a JSON array of objects, while most of the solutions i found work with normal arrays.

Here is what i have now:

```<code><script>
    $(document).ready(function(){
        // Defining the local dataset
        $.getJSON('http://127.0.0.1:8000/myapi/', function(data) {
          console.log(data)
          //Autocomplete
        });
    });
</script>

<input type="text" id='firstfield' name='input_val'>
</code>```

This is what the data looks like, it's around 700 records; here are the first three:

```<code>"results": [
        {
            "item": "First",
            "id": "1847",
        },
        {
            "item": "Second",
            "id": "4442",
        },
        {
            "item": "Third",
            "id": "3847",
        }]
</code>```

I need this to be as fast as possible. Is there a JQuery/Ajax native solution for this? Or is there a specific library to do this? Any advice or solution is appreciated, thanks in advance!

答:
You can use Jquery autocomplete() function

Here is the link
https://jqueryui.com/autocomplete/

```<code>$( "#tags" ).autocomplete({
      source: availableTags
    });
  } );

var availableTags = [
      "ActionScript",
      "AppleScript",
      "Asp",
      "BASIC",
      "C",
      "C++",
      "Clojure"}

</code>```

Body:
I'm creating a Django site, on a certain template i added an Ajax form and i would like to add an autocomplete feature, in order to make navigation easier.

My main problem is that the data i should search is a JSON array of objects, while most of the solutions i found work with normal arrays.

Here is what i have now:

<input type="text" id='firstfield' name='input_val'>

This is what the data looks like, it's around 700 records; here are the first three:

"results": [
        {
            "item": "First",
            "id": "1847",
        },
        {
            "item": "Second",
            "id": "4442",
        },
        {
            "item": "Third",
            "id": "3847",
        }]

I need this to be as fast as possible. Is there a JQuery/Ajax native solution for this? Or is there a specific library to do this? Any advice or solution is appreciated, thanks in advance!

Body:
You can use Jquery autocomplete() function

Here is the link
https://jqueryui.com/autocomplete/

$( "#tags" ).autocomplete({
      source: availableTags
    });
  } );

var availableTags = [
      "ActionScript",
      "AppleScript",
      "Asp",
      "BASIC",
      "C",
      "C++",
      "Clojure"}


问:
Cell formating based on other cell value google sheets
I have 2 sheets the first one is Orders and second one is the ShippingDoc.

At Shipping doc, I have Cell C2. In that cell I choose/write  ID from range of A7:A from Orders.

Is there a way if I choose example ID 1 at C2 then automatically A7 at Orders to change background to green. Also if I change the ID to 2 the A8 to be green and to not delete the A7 color.

答:
try:

```<code>=(REGEXMATCH(""&INDIRECT("ShippingDoc!C2"), ""&A1))*(A1<>"")
</code>```

Body:
try:

=(REGEXMATCH(""&INDIRECT("ShippingDoc!C2"), ""&A1))*(A1<>"")


问:
Delete character in a string
I want to delete the penultimate number in the string

Example

initial database

```<code>num
23001
662001
11001
</code>```

I want to

```<code>num
2301
66201
1101
</code>```

答:
Here is a quick answer, where I use gsub to change 00 to 0.

```<code>num <- c(23001,662001,11001)
as.numeric(gsub('00','0',as.character(num)))
# [1]  2301 66201  1101
</code>```

Title: Delete character in a string

Body:
I want to delete the penultimate number in the string

Example

initial database

num
23001
662001
11001

I want to

num
2301
66201
1101

Body:
Here is a quick answer, where I use gsub to change 00 to 0.

num <- c(23001,662001,11001)
as.numeric(gsub('00','0',as.character(num)))
# [1]  2301 66201  1101


问:
firebase -> date order reverse
I am currently making an app using Firebase.

It is one of those bulletin boards that can be seen anywhere on the web.

But there was one problem.

This is a matter of date sorting.

I want to look at the recent date first, but I always see only the data I created first.

```<code>postRef.orderByChild('createData').startAt(reverseDate).limitToFirst(1).on('child_added',(data)=>{
    console.log(data.val().name + data.val().createData);
})
</code>```

result - >hello1496941142093

My firebase tree

My code is the same as above.

How can I check my recent posts first?

How Do I order reverse of firebase database?

答:
Far more easier is just use Swift's reversed():
https://developer.apple.com/documentation/swift/array/1690025-reversed
https://developer.apple.com/documentation/swift/reversedcollection

```<code>let decodedIds = try DTDecoder().decode([String].self, from: value)
// we reverse it, because we want most recent orders at the top
let reversedDecodedIds = decodedIds.reversed().map {$0}
</code>```

Title: firebase -> date order reverse

Body:
I am currently making an app using Firebase.

It is one of those bulletin boards that can be seen anywhere on the web.

But there was one problem.

This is a matter of date sorting.

I want to look at the recent date first, but I always see only the data I created first.

postRef.orderByChild('createData').startAt(reverseDate).limitToFirst(1).on('child_added',(data)=>{
    console.log(data.val().name + data.val().createData);
})

result - >hello1496941142093

My firebase tree

My code is the same as above.

How can I check my recent posts first?

How Do I order reverse of firebase database?

Body:
Far more easier is just use Swift's reversed():
https://developer.apple.com/documentation/swift/array/1690025-reversed
https://developer.apple.com/documentation/swift/reversedcollection

let decodedIds = try DTDecoder().decode([String].self, from: value)
// we reverse it, because we want most recent orders at the top
let reversedDecodedIds = decodedIds.reversed().map {$0}


问:
VideoJS centered play button
I thought I'd share a piece of code that might come in handy to someone. This is a function that center's the play button inside the video-js player, it works for me. You just need to call it on the pause event and when the player is initialized and not being autoplayed.

Enjoy!

```<code>function CenterPlayBT() {
   var playBT = $(".vjs-big-play-button");
   playBT.css({
      left:( (playBT.parent().outerWidth()-playBT.outerWidth())/2 )+"px",
      top:( (playBT.parent().outerHeight()-playBT.outerHeight())/2 )+"px"
   });
}
</code>```

答:
In all the devices (Mobiles and PC) you can center align play-button using below css style

```<code>.vjs-default-skin .vjs-big-play-button {
            left: 50% !important;
            top: 50% !important;
            transform: translate(-50%, -50%);
            width: 80px!important;
            height: 80px!important;
            -webkit-border-radius: 0.8em!important;
            -moz-border-radius: 0.8em!important;
            border-radius: 1.9em!important;
        }
</code>```

Title: VideoJS centered play button

Body:
I thought I'd share a piece of code that might come in handy to someone. This is a function that center's the play button inside the video-js player, it works for me. You just need to call it on the pause event and when the player is initialized and not being autoplayed.

Enjoy!

function CenterPlayBT() {
   var playBT = $(".vjs-big-play-button");
   playBT.css({
      left:( (playBT.parent().outerWidth()-playBT.outerWidth())/2 )+"px",
      top:( (playBT.parent().outerHeight()-playBT.outerHeight())/2 )+"px"
   });
}

Body:
In all the devices (Mobiles and PC) you can center align play-button using below css style

.vjs-default-skin .vjs-big-play-button {
            left: 50% !important;
            top: 50% !important;
            transform: translate(-50%, -50%);
            width: 80px!important;
            height: 80px!important;
            -webkit-border-radius: 0.8em!important;
            -moz-border-radius: 0.8em!important;
            border-radius: 1.9em!important;
        }


问:
White space at the bottom of button?
I've been struggling with this piece of code, I can't remove the white space that appears in the button(sometimes is on the top, and sometimes in the bottom) here is the css code that isnt working

#filter {
  position: relative;
  overflow: hidden;
  padding: 10px 15px;
  border-radius: 5px;
  outline: none;
  border: 1px solid rgb(37, 101, 135);
  background-color: transparent;
  transform: scale(4) translate(50%, 50%);
}

#filter::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: skyblue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button id="filter">Filter: Off</button></code>```

Thanks in advance.

答:
The issue is when we zoom a little bit on browser the extra space shown in button, here is a solution that worked for me:

I use border: thin solid rgb(37, 101, 135); rather then border: 1px solid rgb(37, 101, 135); on button id #filter

I found this solution across this link: https://productforums.google.com/forum/#!topic/chrome/r1neUxqo5Gc

Title: White space at the bottom of button?

Body:
I've been struggling with this piece of code, I can't remove the white space that appears in the button(sometimes is on the top, and sometimes in the bottom) here is the css code that isnt working

#filter {
  position: relative;
  overflow: hidden;
  padding: 10px 15px;
  border-radius: 5px;
  outline: none;
  border: 1px solid rgb(37, 101, 135);
  background-color: transparent;
  transform: scale(4) translate(50%, 50%);
}

#filter::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: skyblue;
}

<button id="filter">Filter: Off</button>

Thanks in advance.


问:
How "ORDER BY" ordered if they are same value?
Let's say there's table:

```<code>name | score
A      100
B      98
C      99
D      99
E      99
F      98
</code>```

and request sql = 'select * from table order by score desc'

I know order's gonna be 100, 99, 99, 99, 98, 98 but there are several values in 99 and 98.

I'm using MyIsam and want to make sure the order in the 99 and 98 is not changed even though I delete some element.
 For example, if the order was C->D->E and I delete D, then I expect to be C->E but no E->C.
Is there any logic it works when there's same order value?

答:
SQL tables represent unordered sets.  So, there is no "default" ordering when order by keys have the same value.

Technically, this means that sorting in SQL is unstable.  The fix is to add one or more additional keys so each combination is unique.

For your sample data, this can presumably be handled using name:

```<code>order by score desc, name
</code>```

You can also use any other column(s) if available that uniquely identify each row.  These keys go after the score.

Body:
Let's say there's table:

name | score
A      100
B      98
C      99
D      99
E      99
F      98

and request sql = 'select * from table order by score desc'

I know order's gonna be 100, 99, 99, 99, 98, 98 but there are several values in 99 and 98.

I'm using MyIsam and want to make sure the order in the 99 and 98 is not changed even though I delete some element.
 For example, if the order was C->D->E and I delete D, then I expect to be C->E but no E->C.
Is there any logic it works when there's same order value?

Body:
SQL tables represent unordered sets.  So, there is no "default" ordering when order by keys have the same value.

Technically, this means that sorting in SQL is unstable.  The fix is to add one or more additional keys so each combination is unique.

For your sample data, this can presumably be handled using name:

order by score desc, name

You can also use any other column(s) if available that uniquely identify each row.  These keys go after the score.


问:
How to get a specific attribute in a core data entity swift
I know there are similiar questions but I have spent hours of trying to find relevant result to my situation without success.

I have got one entity: EntityDate.

The entity has got 2 attributes:  date and time

I have a variable "date" that I save as a String to core data like this:

```<code>

addToCoreData(name: getDateFormatted(), entityName: "EntityDate", key: "date")

func addToCoreData(name: String, entityName: String, key: String)  {
    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    let entity = NSEntityDescription.entity(forEntityName: entityName, in: context)
    let newEntity = NSManagedObject(entity: entity!, insertInto: context)

    newEntity.setValue(name, forKey: key)

    do {

        try context.save()
        print("saved")

    } catch {
        print("Failed saving")
    }

}

</code>```

Later in my code I retrieve the data like this:

```<code>
var dateFromCD = getCoreData(Entity: "EntityDate")

func getCoreData(Entity: String) -> Array<NSManagedObject>{

    var coreData= [NSManagedObject]()
    coreData= []

    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    let request = NSFetchRequest<NSFetchRequestResult>(entityName: Entity)
    request.returnsObjectsAsFaults = false

    do {
        let result = try context.fetch(request)
        for data in result as! [NSManagedObject]
        {

            coreData.append(data)

        }
    } catch {
        print("Failed")
    }

    return coreData

}

</code>```

Now I thought I would add a variable time to the seperate attribute "time", and naturally I proceeded by doing like this:

```<code>addToCoreData(name: getFormattedTime(), entityName: "EntityDate", key: "time")

</code>```

The problem I have is that when I call the function
"getCoreData(Entity: "EntityDate")" it gives me this output

```<code>[<EntityDate: 0x6000034fc2d0> (entity: EntityDate; id: 0xc229f3dcff76efb1 <x-coredata://2E6F1D46-F49D-436C-9608-FEC59EEB21E6/EntityDate/p18>; data: {
    date = "2/21/20";
    time = nil;
}), <EntityDate: 0x6000034fc320> (entity: EntityDate; id: 0xc229f3dcff72efb1 <x-coredata://2E6F1D46-F49D-436C-9608-FEC59EEB21E6/EntityDate/p19>; data: {
    date = nil;
    time = "13:46";
})]
</code>```

I dont understand the output and I would like to be able to retrieve only date and only time as two seperate variables from the array.

答:
The problem is that you are creating two records, one with the date and the other with the time information instead of one with both date and time.

If you have only one entity anyway take advantage of the generic behavior and write the method more specific like

```<code>func createEntityDate(date: String, time: String)  {
    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    let newEntity = EntityDate(context: context)
    newEntity.date = date
    newEntity.time = time

    do {
        try context.save()
        print("saved")

    } catch {
        print("Failed saving", error)
    }

}
</code>```

If you need to modify attributes of an existing record you have to fetch it, modify and save it back.

In any case it's highly recommended to save the whole date as Date and use computed properties to extract the date and time portion.

Body:
I know there are similiar questions but I have spent hours of trying to find relevant result to my situation without success.

I have got one entity: EntityDate.

The entity has got 2 attributes:  date and time

I have a variable "date" that I save as a String to core data like this:

addToCoreData(name: getDateFormatted(), entityName: "EntityDate", key: "date")

func addToCoreData(name: String, entityName: String, key: String)  {
    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    let entity = NSEntityDescription.entity(forEntityName: entityName, in: context)
    let newEntity = NSManagedObject(entity: entity!, insertInto: context)

    newEntity.setValue(name, forKey: key)

    do {

        try context.save()
        print("saved")

    } catch {
        print("Failed saving")
    }

}

Later in my code I retrieve the data like this:

var dateFromCD = getCoreData(Entity: "EntityDate")

func getCoreData(Entity: String) -> Array<NSManagedObject>{

    var coreData= [NSManagedObject]()
    coreData= []

    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    let request = NSFetchRequest<NSFetchRequestResult>(entityName: Entity)
    request.returnsObjectsAsFaults = false

    do {
        let result = try context.fetch(request)
        for data in result as! [NSManagedObject]
        {

            coreData.append(data)

        }
    } catch {
        print("Failed")
    }

    return coreData

}

Now I thought I would add a variable time to the seperate attribute "time", and naturally I proceeded by doing like this:

addToCoreData(name: getFormattedTime(), entityName: "EntityDate", key: "time")

The problem I have is that when I call the function
"getCoreData(Entity: "EntityDate")" it gives me this output

[<EntityDate: 0x6000034fc2d0> (entity: EntityDate; id: 0xc229f3dcff76efb1 <x-coredata://2E6F1D46-F49D-436C-9608-FEC59EEB21E6/EntityDate/p18>; data: {
    date = "2/21/20";
    time = nil;
}), <EntityDate: 0x6000034fc320> (entity: EntityDate; id: 0xc229f3dcff72efb1 <x-coredata://2E6F1D46-F49D-436C-9608-FEC59EEB21E6/EntityDate/p19>; data: {
    date = nil;
    time = "13:46";
})]

I dont understand the output and I would like to be able to retrieve only date and only time as two seperate variables from the array.

Body:
The problem is that you are creating two records, one with the date and the other with the time information instead of one with both date and time.

If you have only one entity anyway take advantage of the generic behavior and write the method more specific like

func createEntityDate(date: String, time: String)  {
    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    let newEntity = EntityDate(context: context)
    newEntity.date = date
    newEntity.time = time

    do {
        try context.save()
        print("saved")

    } catch {
        print("Failed saving", error)
    }

}

If you need to modify attributes of an existing record you have to fetch it, modify and save it back.

In any case it's highly recommended to save the whole date as Date and use computed properties to extract the date and time portion.


问:
Set the font line height of a Xamarin.Forms Label
I have a Xamarin.Forms label showing several lines of text and I would like to increase the line height to make the text more readable.

The font properties available on the Label and Span controls seem limited to font face, size and style.

How can I change the line height?

答:
I tried the above solutions without succeed. The behaviours are different in Android and iOS, so I worked on a similar solution achieving the same behaviour in both platforms.

```<code>// Put this your forms project
public class CustomLabel : Label
{
    public static readonly BindableProperty LineHeightProperty =
        BindableProperty.Create("LineHeight", typeof(double), typeof(CustomLabel));

    public double LineHeight
    {
        get { return (double)GetValue(LineHeightProperty); }
        set { SetValue(LineHeightProperty, value); }
    }
}
</code>```

Then, the iOS renderer:

```<code>// Put this in your iOS project
[assembly: ExportRenderer(typeof(CustomLabel), typeof(CustomLabelRenderer))]
namespace App.iOS.Components
{
    public class CustomLabelRenderer : LabelRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
        {
            base.OnElementChanged(e);
            var label = (CustomLabel)Element;
            if (label == null || Control == null)
            {
                return;
            }
            double fontSize = label.FontSize;

            //iOS LineSpacing is measured in dp, as the FontSize. So, if we need a LineSpacing of 2,
            //this LineSpacing must be set to the same value of the FontSize
            nfloat lineSpacing = ((nfloat)label.LineHeight * (nfloat)fontSize) - (nfloat)fontSize;
            if (lineSpacing > 0)
            {
                var labelString = new NSMutableAttributedString(label.Text);
                var paragraphStyle = new NSMutableParagraphStyle { LineSpacing = lineSpacing };
                var style = UIStringAttributeKey.ParagraphStyle;
                var range = new NSRange(0, labelString.Length);

                labelString.AddAttribute(style, paragraphStyle, range);
                Control.AttributedText = labelString;
            }
        }
    }
}
</code>```

Note that, in iOS the LineSpacing property is different from Android:
LineSpacing = 2 in Android is the equivalent to LineSpacing = FontSize in iOS

Finally, the AndroidRenderer:

```<code>// Put this in your Android project
[assembly: ExportRenderer(typeof(CustomLabel), typeof(CustomLabelRenderer))]
namespace App.Droid.Components
{
    public class CustomLabelRenderer : LabelRenderer
    {
        protected CustomLabel CustomLabel { get; private set; }
        public CustomLabelRenderer(Context context) : base(context)
        {
        }

        protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
        {
            base.OnElementChanged(e);

            if (e.OldElement == null)
            {
                this.CustomLabel = (CustomLabel)this.Element;
            }
            double lineSpacing = this.CustomLabel.LineHeight;
            if (lineSpacing > 0)
            {
                this.Control.SetLineSpacing(1f, (float)lineSpacing);
                this.UpdateLayout();
            }
        }
    }
}
</code>```

Hope it works

Body:
I tried the above solutions without succeed. The behaviours are different in Android and iOS, so I worked on a similar solution achieving the same behaviour in both platforms.

// Put this your forms project
public class CustomLabel : Label
{
    public static readonly BindableProperty LineHeightProperty =
        BindableProperty.Create("LineHeight", typeof(double), typeof(CustomLabel));

    public double LineHeight
    {
        get { return (double)GetValue(LineHeightProperty); }
        set { SetValue(LineHeightProperty, value); }
    }
}

Then, the iOS renderer:

// Put this in your iOS project
[assembly: ExportRenderer(typeof(CustomLabel), typeof(CustomLabelRenderer))]
namespace App.iOS.Components
{
    public class CustomLabelRenderer : LabelRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
        {
            base.OnElementChanged(e);
            var label = (CustomLabel)Element;
            if (label == null || Control == null)
            {
                return;
            }
            double fontSize = label.FontSize;

            //iOS LineSpacing is measured in dp, as the FontSize. So, if we need a LineSpacing of 2,
            //this LineSpacing must be set to the same value of the FontSize
            nfloat lineSpacing = ((nfloat)label.LineHeight * (nfloat)fontSize) - (nfloat)fontSize;
            if (lineSpacing > 0)
            {
                var labelString = new NSMutableAttributedString(label.Text);
                var paragraphStyle = new NSMutableParagraphStyle { LineSpacing = lineSpacing };
                var style = UIStringAttributeKey.ParagraphStyle;
                var range = new NSRange(0, labelString.Length);

                labelString.AddAttribute(style, paragraphStyle, range);
                Control.AttributedText = labelString;
            }
        }
    }
}

Note that, in iOS the LineSpacing property is different from Android:
LineSpacing = 2 in Android is the equivalent to LineSpacing = FontSize in iOS

Finally, the AndroidRenderer:

// Put this in your Android project
[assembly: ExportRenderer(typeof(CustomLabel), typeof(CustomLabelRenderer))]
namespace App.Droid.Components
{
    public class CustomLabelRenderer : LabelRenderer
    {
        protected CustomLabel CustomLabel { get; private set; }
        public CustomLabelRenderer(Context context) : base(context)
        {
        }

        protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
        {
            base.OnElementChanged(e);

            if (e.OldElement == null)
            {
                this.CustomLabel = (CustomLabel)this.Element;
            }
            double lineSpacing = this.CustomLabel.LineHeight;
            if (lineSpacing > 0)
            {
                this.Control.SetLineSpacing(1f, (float)lineSpacing);
                this.UpdateLayout();
            }
        }
    }
}

Hope it works