text:
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//

/*++

Module Name:

    module.c

Abstract:

    Implementation of module related functions in the Win32 API

--*/

#include "pal/thread.hpp"
#include "pal/malloc.hpp"
#include "pal/file.hpp"
#include "pal/palinternal.h"
#include "pal/dbgmsg.h"
#include "pal/module.h"
#include "pal/cs.hpp"
#include "pal/process.h"
#include "pal/file.h"
#include "pal/utils.h"
#include "pal/init.h"
#include "pal/modulename.h"
#include "pal/misc.h"
#include "pal/virtual.h"
#include "pal/map.hpp"
#include "pal/stackstring.hpp"

#include <sys/param.h>
#include <errno.h>
#include <string.h>
#include <limits.h>
#if NEED_DLCOMPAT
#include "dlcompat.h"
#else   // NEED_DLCOMPAT
#include <dlfcn.h>
#endif  // NEED_DLCOMPAT
#if HAVE_ALLOCA_H
#include <alloca.h>
#endif  // HAVE_ALLOCA_H

#ifdef __APPLE__
#include <mach-o/dyld.h>
#include <mach-o/loader.h>
#endif // __APPLE__

#include <sys/types.h>
#include <sys/mman.h>

#if defined(__LINUX__)
#include <gnu/lib-names.h>
#endif

using namespace CorUnix;

SET_DEFAULT_DEBUG_CHANNEL(LOADER);

// In safemath.h, Template SafeInt uses macro _ASSERTE, which need to use variable
// defdbgchan defined by SET_DEFAULT_DEBUG_CHANNEL. Therefore, the include statement
// should be placed after the SET_DEFAULT_DEBUG_CHANNEL(LOADER)
#include <safemath.h>

/* macro definitions **********************************************************/

/* get the full name of a module if available, and the short name otherwise*/
#define MODNAME(x) ((x)->lib_name)

/* Which path should FindLibrary search? */
#if defined(__APPLE__)
#define LIBSEARCHPATH "DYLD_LIBRARY_PATH"
#else
#define LIBSEARCHPATH "LD_LIBRARY_PATH"
#endif

#define LIBC_NAME_WITHOUT_EXTENSION "libc"

/* static variables ***********************************************************/

/* critical section that regulates access to the module list */
CRITICAL_SECTION module_critsec;

/* always the first, in the in-load-order list */
MODSTRUCT exe_module;
MODSTRUCT *pal_module = NULL;

char * g_szCoreCLRPath = NULL;
size_t g_cbszCoreCLRPath = MAX_LONGPATH * sizeof(char);

int MaxWCharToAcpLength = 3;
/* static function declarations ***********************************************/

template<class TChar> bool LOADVerifyLibraryPath(const TChar *libraryPath);
bool LOADConvertLibraryPathWideStringToMultibyteString(
    LPCWSTR wideLibraryPath,
    LPSTR multibyteLibraryPath,
    INT *multibyteLibraryPathLengthRef);

static BOOL LOADValidateModule(MODSTRUCT *module);
static LPWSTR LOADGetModuleFileName(MODSTRUCT *module);
static HMODULE LOADLoadLibraryDirect(LPCSTR libraryNameOrPath, bool setLastError);
static HMODULE LOADRegisterLibraryDirect(HMODULE dl_handle, LPCSTR libraryNameOrPath, BOOL fDynamic);
static HMODULE LOADLoadLibrary(LPCSTR shortAsciiName, BOOL fDynamic);
static void LOAD_SEH_CallDllMain(MODSTRUCT *module, DWORD dwReason, LPVOID lpReserved);
static MODSTRUCT *LOADAllocModule(void *dl_handle, LPCSTR name);

/* API function definitions ***************************************************/

/*++
Function:
  LoadLibraryA

See MSDN doc.
--*/
HMODULE
PALAPI
LoadLibraryA(
    IN LPCSTR lpLibFileName)
{
    return LoadLibraryExA(lpLibFileName, NULL, 0);
}

/*++
Function:
  LoadLibraryW

See MSDN doc.
--*/
HMODULE
PALAPI
LoadLibraryW(
    IN LPCWSTR lpLibFileName)
{
    return LoadLibraryExW(lpLibFileName, NULL, 0);
}

/*++
Function:
LoadLibraryExA

See MSDN doc.
--*/
HMODULE
PALAPI
LoadLibraryExA(
    IN LPCSTR lpLibFileName,
    IN /*Reserved*/ HANDLE hFile,
    IN DWORD dwFlags)
{
    if (dwFlags != 0)
    {
        // UNIXTODO: Implement this!
        ASSERT("Needs Implementation!!!");
        return NULL;
    }

    LPSTR lpstr = NULL;
    HMODULE hModule = NULL;

    PERF_ENTRY(LoadLibraryA);
    ENTRY("LoadLibraryExA (lpLibFileName=%p (%s)) \n",
          (lpLibFileName)?lpLibFileName:"NULL",
          (lpLibFileName)?lpLibFileName:"NULL");

    if (!LOADVerifyLibraryPath(lpLibFileName))
    {
        goto Done;
    }

    /* do the Dos/Unix conversion on our own copy of the name */
    lpstr = InternalStrdup(lpLibFileName);
    if (!lpstr)
    {
        ERROR("InternalStrdup failure!\n");
        SetLastError(ERROR_NOT_ENOUGH_MEMORY);
        goto Done;
    }
    FILEDosToUnixPathA(lpstr);

    hModule = LOADLoadLibrary(lpstr, TRUE);

    /* let LOADLoadLibrary call SetLastError */
 Done:
    if (lpstr != NULL)
    {
        InternalFree(lpstr);
    }

    LOGEXIT("LoadLibraryExA returns HMODULE %p\n", hModule);
    PERF_EXIT(LoadLibraryExA);
    return hModule;

}

/*++
Function:
LoadLibraryExW

See MSDN doc.
--*/
HMODULE
PALAPI
LoadLibraryExW(
    IN LPCWSTR lpLibFileName,
    IN /*Reserved*/ HANDLE hFile,
    IN DWORD dwFlags)
{
    if (dwFlags != 0)
    {
        // UNIXTODO: Implement this!
        ASSERT("Needs Implementation!!!");
        return NULL;
    }

    CHAR * lpstr;
    INT name_length;
    PathCharString pathstr;
    HMODULE hModule = NULL;

    PERF_ENTRY(LoadLibraryExW);
    ENTRY("LoadLibraryExW (lpLibFileName=%p (%S)) \n",
          lpLibFileName?lpLibFileName:W16_NULLSTRING,
          lpLibFileName?lpLibFileName:W16_NULLSTRING);

    if (!LOADVerifyLibraryPath(lpLibFileName))
    {
        goto done;
    }

    lpstr = pathstr.OpenStringBuffer((PAL_wcslen(lpLibFileName)+1) * MaxWCharToAcpLength);
    if (NULL == lpstr)
    {
        goto done;
    }
    if (!LOADConvertLibraryPathWideStringToMultibyteString(lpLibFileName, lpstr, &name_length))
    {
        goto done;
    }

    /* do the Dos/Unix conversion on our own copy of the name */
    FILEDosToUnixPathA(lpstr);
    pathstr.CloseBuffer(name_length);

    /* let LOADLoadLibrary call SetLastError in case of failure */
    hModule = LOADLoadLibrary(lpstr, TRUE);

done:
    LOGEXIT("LoadLibraryExW returns HMODULE %p\n", hModule);
    PERF_EXIT(LoadLibraryExW);
    return hModule;
}

/*
Function:
LoadLibraryDirect

Loads a library using a system call, without registering the library with the module list.

Returns the system handle to the loaded library, or nullptr upon failure (error is set via SetLastError()).
*/
HMODULE
PALAPI
PAL_LoadLibraryDirect(
    IN LPCWSTR lpLibFileName)
{
    PathCharString pathstr;
    CHAR * lpstr = NULL;
    INT name_length;
    HMODULE hModule = NULL;

    PERF_ENTRY(LoadLibraryDirect);
    ENTRY("LoadLibraryDirect (lpLibFileName=%p (%S)) \n",
          lpLibFileName?lpLibFileName:W16_NULLSTRING,
          lpLibFileName?lpLibFileName:W16_NULLSTRING);

    if (!LOADVerifyLibraryPath(lpLibFileName))
    {
        goto done;
    }

    lpstr = pathstr.OpenStringBuffer((PAL_wcslen(lpLibFileName)+1) * MaxWCharToAcpLength);
    if (NULL == lpstr)
    {
        goto done;
    }
    if (!LOADConvertLibraryPathWideStringToMultibyteString(lpLibFileName, lpstr, &name_length))
    {
        goto done;
    }

    /* do the Dos/Unix conversion on our own copy of the name */
    FILEDosToUnixPathA(lpstr);
    pathstr.CloseBuffer(name_length);

    /* let LOADLoadLibraryDirect call SetLastError in case of failure */
    hModule = LOADLoadLibraryDirect(lpstr, true /* setLastError */);

done:
    LOGEXIT("LoadLibraryDirect returns HMODULE %p\n", hModule);
    PERF_EXIT(LoadLibraryDirect);
    return hModule;
}

/*
Function:
RegisterLibraryDirect

Registers a system handle to a loaded library with the module list.

Returns a PAL handle to the loaded library, or nullptr upon failure (error is set via SetLastError()).
*/
HMODULE
PALAPI
PAL_RegisterLibraryDirect(
    IN HMODULE dl_handle,
    IN LPCWSTR lpLibFileName)
{
    PathCharString pathstr;
    CHAR * lpstr = NULL;
    INT name_length;
    HMODULE hModule = NULL;

    PERF_ENTRY(RegisterLibraryDirect);
    ENTRY("RegisterLibraryDirect (lpLibFileName=%p (%S)) \n",
        lpLibFileName ? lpLibFileName : W16_NULLSTRING,
        lpLibFileName ? lpLibFileName : W16_NULLSTRING);

    if (!LOADVerifyLibraryPath(lpLibFileName))
    {
        goto done;
    }

    lpstr = pathstr.OpenStringBuffer((PAL_wcslen(lpLibFileName)+1) * MaxWCharToAcpLength);
    if (NULL == lpstr)
    {
        goto done;
    }
    if (!LOADConvertLibraryPathWideStringToMultibyteString(lpLibFileName, lpstr, &name_length))
    {
        goto done;
    }

    /* do the Dos/Unix conversion on our own copy of the name */
    FILEDosToUnixPathA(lpstr);
    pathstr.CloseBuffer(name_length);

    /* let LOADRegisterLibraryDirect call SetLastError in case of failure */
    LockModuleList();
    hModule = LOADRegisterLibraryDirect(dl_handle, lpstr, true /* fDynamic */);
    UnlockModuleList();

done:
    LOGEXIT("RegisterLibraryDirect returns HMODULE %p\n", hModule);
    PERF_EXIT(RegisterLibraryDirect);
    return hModule;
}

/*++
Function:
  GetProcAddress

See MSDN doc.
--*/
FARPROC
PALAPI
GetProcAddress(
    IN HMODULE hModule,
    IN LPCSTR lpProcName)
{
    MODSTRUCT *module;
    FARPROC ProcAddress = NULL;
    LPCSTR symbolName = lpProcName;

    PERF_ENTRY(GetProcAddress);
    ENTRY("GetProcAddress (hModule=%p, lpProcName=%p (%s))\n",
          hModule, lpProcName?lpProcName:"NULL", lpProcName?lpProcName:"NULL");

    LockModuleList();

    module = (MODSTRUCT *) hModule;

    /* parameter validation */

    if ((lpProcName == NULL) || (*lpProcName == '\0'))
    {
        TRACE("No function name given\n");
        SetLastError(ERROR_INVALID_PARAMETER);
        goto done;
    }

    if (!LOADValidateModule(module))
    {
        TRACE("Invalid module handle %p\n", hModule);
        SetLastError(ERROR_INVALID_HANDLE);
        goto done;
    }

    /* try to assert on attempt to locate symbol by ordinal */
    /* this can't be an exact test for HIWORD((DWORD)lpProcName) == 0
       because of the address range reserved for ordinals contain can
       be a valid string address on non-Windows systems
    */
    if ((DWORD_PTR)lpProcName < VIRTUAL_PAGE_SIZE)
    {
        ASSERT("Attempt to locate symbol by ordinal?!\n");
    }

    // Get the symbol's address.

    // If we're looking for a symbol inside the PAL, we try the PAL_ variant
    // first because otherwise we run the risk of having the non-PAL_
    // variant preferred over the PAL's implementation.
    if (pal_module && module->dl_handle == pal_module->dl_handle)
    {
        int iLen = 4 + strlen(lpProcName) + 1;
        LPSTR lpPALProcName = (LPSTR) alloca(iLen);

        if (strcpy_s(lpPALProcName, iLen, "PAL_") != SAFECRT_SUCCESS)
        {
            ERROR("strcpy_s failed!\n");
            SetLastError(ERROR_INSUFFICIENT_BUFFER);
            goto done;
        }

        if (strcat_s(lpPALProcName, iLen, lpProcName) != SAFECRT_SUCCESS)
        {
            ERROR("strcat_s failed!\n");
            SetLastError(ERROR_INSUFFICIENT_BUFFER);
            goto done;
        }

        ProcAddress = (FARPROC) dlsym(module->dl_handle, lpPALProcName);
        symbolName = lpPALProcName;
    }

    // If we aren't looking inside the PAL or we didn't find a PAL_ variant
    // inside the PAL, fall back to a normal search.
    if (ProcAddress == NULL)
    {
            ProcAddress = (FARPROC) dlsym(module->dl_handle, lpProcName);
    }

    if (ProcAddress)
    {
        TRACE("Symbol %s found at address %p in module %p (named %S)\n",
              lpProcName, ProcAddress, module, MODNAME(module));

        /* if we don't know the module's full name yet, this is our chance to
           obtain it */
        if (!module->lib_name && module->dl_handle)
        {
            const char* libName = PAL_dladdr((LPVOID)ProcAddress);
            if (libName)
            {
                module->lib_name = UTIL_MBToWC_Alloc(libName, -1);
                if (NULL == module->lib_name)
                {
                    ERROR("MBToWC failure; can't save module's full name\n");
                }
                else
                {
                    TRACE("Saving full path of module %p as %s\n",
                          module, libName);
                }
            }
        }
    }
    else
    {
        TRACE("Symbol %s not found in module %p (named %S), dlerror message is \"%s\"\n",
              lpProcName, module, MODNAME(module), dlerror());
        SetLastError(ERROR_PROC_NOT_FOUND);
    }
done:
    UnlockModuleList();
    LOGEXIT("GetProcAddress returns FARPROC %p\n", ProcAddress);
    PERF_EXIT(GetProcAddress);
    return ProcAddress;
}

/*++
Function:
  FreeLibrary

See MSDN doc.
--*/
BOOL
PALAPI
FreeLibrary(
    IN OUT HMODULE hLibModule)
{
    MODSTRUCT *module;
    BOOL retval = FALSE;

    PERF_ENTRY(FreeLibrary);
    ENTRY("FreeLibrary (hLibModule=%p)\n", hLibModule);

    LockModuleList();

    module = (MODSTRUCT *) hLibModule;

    if (terminator)
    {
        /* PAL shutdown is in progress - ignore FreeLibrary calls */
        retval = TRUE;
        goto done;
    }

    if (!LOADValidateModule(module))
    {
        TRACE("Can't free invalid module handle %p\n", hLibModule);
        SetLastError(ERROR_INVALID_HANDLE);
        goto done;
    }

    if (module->refcount == -1)
    {
        /* special module - never released */
        retval = TRUE;
        goto done;
    }

    module->refcount--;
    TRACE("Reference count for module %p (named %S) decreases to %d\n",
            module, MODNAME(module), module->refcount);

    if (module->refcount != 0)
    {
        retval = TRUE;
        goto done;
    }

    /* Releasing the last reference : call dlclose(), remove module from the
       process-wide module list */

    TRACE("Reference count for module %p (named %S) now 0; destroying "
            "module structure.\n", module, MODNAME(module));

    /* unlink the module structure from the list */
    module->prev->next = module->next;
    module->next->prev = module->prev;

    /* remove the circular reference so that LOADValidateModule will fail */
    module->self = NULL;

    /* Call DllMain if the module contains one */
    if (module->pDllMain)
    {
        TRACE("Calling DllMain (%p) for module %S\n",
                module->pDllMain,
                module->lib_name ? module->lib_name : W16_NULLSTRING);

/* reset ENTRY nesting level back to zero while inside the callback... */
#if _ENABLE_DEBUG_MESSAGES_
    {
        int old_level;
        old_level = DBG_change_entrylevel(0);
#endif /* _ENABLE_DEBUG_MESSAGES_ */

        {
            // This module may be foreign to our PAL, so leave our PAL.
            // If it depends on us, it will re-enter.
            PAL_LeaveHolder holder;
            module->pDllMain(module->hinstance, DLL_PROCESS_DETACH, NULL);
        }

        if (module->hinstance)
        {
            PUNREGISTER_MODULE unregisterModule = (PUNREGISTER_MODULE)dlsym(module->dl_handle, "PAL_UnregisterModule");
            if (unregisterModule)
            {
                 unregisterModule(module->hinstance);
            }
        }
/* ...and set nesting level back to what it was */
#if _ENABLE_DEBUG_MESSAGES_
        DBG_change_entrylevel(old_level);
    }
#endif /* _ENABLE_DEBUG_MESSAGES_ */
    }

    if (module->dl_handle && 0 != dlclose(module->dl_handle))
    {
        /* report dlclose() failure, but proceed anyway. */
        WARN("dlclose() call failed! error message is \"%s\"\n", dlerror());
    }

    /* release all memory */
    InternalFree(module->lib_name);
    InternalFree(module);

    retval = TRUE;

done:
    UnlockModuleList();
    LOGEXIT("FreeLibrary returns BOOL %d\n", retval);
    PERF_EXIT(FreeLibrary);
    return retval;
}

/*++
Function:
  FreeLibraryAndExitThread

See MSDN doc.

--*/
PALIMPORT
VOID
PALAPI
FreeLibraryAndExitThread(
    IN HMODULE hLibModule,
    IN DWORD dwExitCode)
{
    PERF_ENTRY(FreeLibraryAndExitThread);
    ENTRY("FreeLibraryAndExitThread()\n");
    FreeLibrary(hLibModule);
    ExitThread(dwExitCode);
    LOGEXIT("FreeLibraryAndExitThread\n");
    PERF_EXIT(FreeLibraryAndExitThread);
}

/*++
Function:
  GetModuleFileNameA

See MSDN doc.

Notes :
    because of limitations in the dlopen() mechanism, this will only return the
    full path name if a relative or absolute path was given to LoadLibrary, or
    if the module was used in a GetProcAddress call. otherwise, this will return
    the short name as given to LoadLibrary. The exception is if hModule is
    NULL : in this case, the full path of the executable is always returned.
--*/
DWORD
PALAPI
GetModuleFileNameA(
    IN HMODULE hModule,
    OUT LPSTR lpFileName,
    IN DWORD nSize)
{
    INT name_length;
    DWORD retval = 0;
    LPWSTR wide_name = NULL;

    PERF_ENTRY(GetModuleFileNameA);
    ENTRY("GetModuleFileNameA (hModule=%p, lpFileName=%p, nSize=%u)\n",
          hModule, lpFileName, nSize);

    LockModuleList();
    if (hModule && !LOADValidateModule((MODSTRUCT *)hModule))
    {
        TRACE("Can't find name for invalid module handle %p\n", hModule);
        SetLastError(ERROR_INVALID_HANDLE);
        goto done;
    }
    wide_name = LOADGetModuleFileName((MODSTRUCT *)hModule);

    if (!wide_name)
    {
        ASSERT("Can't find name for valid module handle %p\n", hModule);
        SetLastError(ERROR_INTERNAL_ERROR);
        goto done;
    }

    /* Convert module name to Ascii, place it in the supplied buffer */

    name_length = WideCharToMultiByte(CP_ACP, 0, wide_name, -1, lpFileName,
                                      nSize, NULL, NULL);
    if (name_length == 0)
    {
        TRACE("Buffer too small to copy module's file name.\n");
        SetLastError(ERROR_INSUFFICIENT_BUFFER);
        goto done;
    }

    TRACE("File name of module %p is %s\n", hModule, lpFileName);
    retval = name_length;
done:
    UnlockModuleList();
    LOGEXIT("GetModuleFileNameA returns DWORD %d\n", retval);
    PERF_EXIT(GetModuleFileNameA);
    return retval;
}

/*++
Function:
  GetModuleFileNameW

See MSDN doc.

Notes :
    because of limitations in the dlopen() mechanism, this will only return the
    full path name if a relative or absolute path was given to LoadLibrary, or
    if the module was used in a GetProcAddress call. otherwise, this will return
    the short name as given to LoadLibrary. The exception is if hModule is
    NULL : in this case, the full path of the executable is always returned.
--*/
DWORD
PALAPI
GetModuleFileNameW(
    IN HMODULE hModule,
    OUT LPWSTR lpFileName,
    IN DWORD nSize)
{
    INT name_length;
    DWORD retval = 0;
    LPWSTR wide_name = NULL;

    PERF_ENTRY(GetModuleFileNameW);
    ENTRY("GetModuleFileNameW (hModule=%p, lpFileName=%p, nSize=%u)\n",
          hModule, lpFileName, nSize);

    LockModuleList();

    wcscpy_s(lpFileName, nSize, W(""));

    if (hModule && !LOADValidateModule((MODSTRUCT *)hModule))
    {
        TRACE("Can't find name for invalid module handle %p\n", hModule);
        SetLastError(ERROR_INVALID_HANDLE);
        goto done;
    }
    wide_name = LOADGetModuleFileName((MODSTRUCT *)hModule);

    if (!wide_name)
    {
        TRACE("Can't find name for valid module handle %p\n", hModule);
        SetLastError(ERROR_INTERNAL_ERROR);
        goto done;
    }

    /* Copy module name into supplied buffer */

    name_length = lstrlenW(wide_name);
    if (name_length >= (INT)nSize)
    {
        TRACE("Buffer too small (%u) to copy module's file name (%u).\n", nSize, name_length);
        SetLastError(ERROR_INSUFFICIENT_BUFFER);
        goto done;
    }

    wcscpy_s(lpFileName, nSize, wide_name);

    TRACE("file name of module %p is %S\n", hModule, lpFileName);
    retval = name_length;
done:
    UnlockModuleList();
    LOGEXIT("GetModuleFileNameW returns DWORD %u\n", retval);
    PERF_EXIT(GetModuleFileNameW);
    return retval;
}

/*++
Function:
  PAL_RegisterModule

  Register the module with the target module and return a module handle in
  the target module's context.

--*/

HINSTANCE
PALAPI
PAL_RegisterModule(
    IN LPCSTR lpLibFileName)
{
    HINSTANCE hinstance = NULL;

    int err = PAL_InitializeDLL();
    if (err == 0)
    {
        PERF_ENTRY(PAL_RegisterModule);
        ENTRY("PAL_RegisterModule(%s)\n", lpLibFileName ? lpLibFileName : "");

        hinstance = (HINSTANCE)LOADLoadLibrary(lpLibFileName, FALSE);

        LOGEXIT("PAL_RegisterModule returns HINSTANCE %p\n", hinstance);
        PERF_EXIT(PAL_RegisterModule);
    }

    return hinstance;
}

/*++
Function:
  PAL_UnregisterModule

  Used to cleanup the module HINSTANCE from PAL_RegisterModule.
--*/
VOID
PALAPI
PAL_UnregisterModule(
    IN HINSTANCE hInstance)
{
    PERF_ENTRY(PAL_UnregisterModule);
    ENTRY("PAL_UnregisterModule(hInstance=%p)\n", hInstance);

    FreeLibrary(hInstance);

    LOGEXIT("PAL_UnregisterModule returns\n");
    PERF_EXIT(PAL_UnregisterModule);
}

/*++
Function:
  PAL_RegisterLibraryW

  Same as LoadLibraryW, but with only the base name of
  the library instead of a full filename.
--*/

HMODULE
PALAPI
PAL_RegisterLibraryW(
    IN LPCWSTR lpLibFileName)
{
    HMODULE hModule = NULL;
    CHAR    lpstr[_MAX_FNAME];
    INT     cbMultiByteShortName = 0;

    static const char LIB_PREFIX[] = PAL_SHLIB_PREFIX;
    static const char LIB_SUFFIX[] = PAL_SHLIB_SUFFIX;
    static const int LIB_PREFIX_LENGTH = sizeof(LIB_PREFIX) - 1;
    static const int LIB_SUFFIX_LENGTH = sizeof(LIB_SUFFIX) - 1;

    PERF_ENTRY(PAL_RegisterLibraryW);
    ENTRY("PAL_RegisterLibraryW (lpLibFileName=%p (%S)) \n",
          lpLibFileName?lpLibFileName:W16_NULLSTRING,
          lpLibFileName?lpLibFileName:W16_NULLSTRING);

    // First, copy the prefix into the buffer
    if (strcpy_s(lpstr, sizeof(lpstr), LIB_PREFIX) != SAFECRT_SUCCESS)
    {
        ERROR("strcpy_s failed!\n");
        SetLastError(ERROR_INSUFFICIENT_BUFFER);
        goto Done;
    }

    // Second, copy the file name, converting to multibyte along the way
    cbMultiByteShortName = WideCharToMultiByte(CP_ACP, 0, lpLibFileName, -1,
                                               lpstr + LIB_PREFIX_LENGTH,
                                               _MAX_FNAME - (LIB_PREFIX_LENGTH + LIB_SUFFIX_LENGTH),
                                               NULL, NULL);

    if (cbMultiByteShortName == 0)
    {
        DWORD dwLastError = GetLastError();
        if (dwLastError == ERROR_INSUFFICIENT_BUFFER)
        {
            if (lstrlenW(lpLibFileName) + LIB_PREFIX_LENGTH + LIB_SUFFIX_LENGTH < _MAX_FNAME)
            {
                ASSERT("Insufficient buffer error returned incorrectly from WideCharToMultiByte!\n");
            }
            ERROR("lpLibFileName is larger than _MAX_FNAME (%d)!\n", _MAX_FNAME);
        }
        else
        {
            ASSERT("WideCharToMultiByte failure! error is %d\n", dwLastError);
        }
        SetLastError(ERROR_INVALID_PARAMETER);
        goto Done;
    }

    // Last, add the suffix
    if (strcat_s(lpstr, sizeof(lpstr), LIB_SUFFIX) != SAFECRT_SUCCESS)
    {
        ERROR("strcat_s failed!\n");
        SetLastError(ERROR_INSUFFICIENT_BUFFER);
        goto Done;
    }

    FILEDosToUnixPathA(lpstr);

    hModule = LOADLoadLibrary(lpstr, FALSE);

Done:
    LOGEXIT("PAL_RegisterLibraryW returns HMODULE %p\n", hModule);
    PERF_EXIT(PAL_RegisterLibraryW);
    return hModule;
}

/*++
Function:
  PAL_UnregisterLibraryW

  Same as FreeLibrary.
--*/
BOOL
PALAPI
PAL_UnregisterLibraryW(
    IN OUT HMODULE hLibModule)
{
    BOOL retval;

    PERF_ENTRY(PAL_UnregisterLibraryW);
    ENTRY("PAL_UnregisterLibraryW (hLibModule=%p)\n", hLibModule);

    retval = FreeLibrary(hLibModule);

    LOGEXIT("PAL_UnregisterLibraryW returns BOOL %d\n", retval);
    PERF_EXIT(PAL_UnregisterLibraryW);
    return retval;
}

/* Internal PAL functions *****************************************************/

/*++
Function :
    LOADInitializeModules

    Initialize the process-wide list of modules

Parameters :
    None

Return value :
    TRUE  if initialization succeedded
    FALSE otherwise

--*/
extern "C"
BOOL LOADInitializeModules()
{
    _ASSERTE(exe_module.prev == NULL);

    InternalInitializeCriticalSection(&module_critsec);

    // Initialize module for main executable
    TRACE("Initializing module for main executable\n");

    exe_module.self = (HMODULE)&exe_module;
    exe_module.dl_handle = dlopen(NULL, RTLD_LAZY);
    if (exe_module.dl_handle == NULL)
    {
        ERROR("Executable module will be broken : dlopen(NULL) failed dlerror message is \"%s\" \n", dlerror());
        return FALSE;
    }
    exe_module.lib_name = NULL;
    exe_module.refcount = -1;
    exe_module.next = &exe_module;
    exe_module.prev = &exe_module;
    exe_module.pDllMain = NULL;
    exe_module.hinstance = NULL;
    exe_module.threadLibCalls = TRUE;
    return TRUE;
}

/*++
Function :
    LOADSetExeName

    Set the exe name path

Parameters :
    LPWSTR man exe path and name

Return value :
    TRUE  if initialization succeedded
    FALSE otherwise

--*/
extern "C"
BOOL LOADSetExeName(LPWSTR name)
{
#if RETURNS_NEW_HANDLES_ON_REPEAT_DLOPEN
    LPSTR pszExeName = NULL;
#endif
    BOOL result = FALSE;

    LockModuleList();

    // Save the exe path in the exe module struct
    InternalFree(exe_module.lib_name);
    exe_module.lib_name = name;

    // For platforms where we can't trust the handle to be constant, we need to
    // store the inode/device pairs for the modules we just initialized.
#if RETURNS_NEW_HANDLES_ON_REPEAT_DLOPEN
    {
        struct stat stat_buf;
        pszExeName = UTIL_WCToMB_Alloc(name, -1);
        if (NULL == pszExeName)
        {
            ERROR("WCToMB failure, unable to get full name of exe\n");
            goto exit;
        }
        if (-1 == stat(pszExeName, &stat_buf))
        {
            SetLastError(ERROR_MOD_NOT_FOUND);
            goto exit;
        }
        TRACE("Executable has inode %d and device %d\n", stat_buf.st_ino, stat_buf.st_dev);

        exe_module.inode = stat_buf.st_ino;
        exe_module.device = stat_buf.st_dev;
    }
#endif
    result = TRUE;

#if RETURNS_NEW_HANDLES_ON_REPEAT_DLOPEN
exit:
    if (pszExeName)
    {
        InternalFree(pszExeName);
    }
#endif
    UnlockModuleList();
    return result;
}

/*++
Function :
    LOADFreeModules

    Release all resources held by the module manager (including dlopen handles)

Parameters:
    BOOL bTerminateUnconditionally: If TRUE, this will avoid calling any DllMains

    (no return value)
--*/
extern "C"
void LOADFreeModules(BOOL bTerminateUnconditionally)
{
    MODSTRUCT *module;

    if (!exe_module.prev)
    {
        ERROR("Module manager not initialized!\n");
        return;
    }

    LockModuleList();

    /* Go through the list of modules, release any references we still hold.
       The list is traversed from newest module to oldest */
    do
    {
        module = exe_module.prev;

        // Call DllMain if the module contains one and if we're supposed
        // to call DllMains.
        if (!bTerminateUnconditionally && module->pDllMain)
        {
           /* Exception-safe call to DllMain */
           LOAD_SEH_CallDllMain(module, DLL_PROCESS_DETACH, (LPVOID)-1);
        }

        /* Remove the current MODSTRUCT from the list, then free its memory */
        module->prev->next = module->next;
        module->next->prev = module->prev;
        module->self = NULL;

        if (module->dl_handle)
            dlclose( module->dl_handle );

        InternalFree( module->lib_name );
        module->lib_name = NULL;
        if (module != &exe_module)
        {
            InternalFree( module );
        }
    }
    while (module != &exe_module);

    /* Flag the module manager as uninitialized */
    exe_module.prev = NULL;

    TRACE("Module manager stopped.\n");

    UnlockModuleList();
    DeleteCriticalSection(&module_critsec);
}

/*++
Function :
    LOADCallDllMain

    Call DllMain for all modules (that have one) with the given "fwReason"

Parameters :
    DWORD dwReason : parameter to pass down to DllMain, one of DLL_PROCESS_ATTACH, DLL_PROCESS_DETACH,
        DLL_THREAD_ATTACH, DLL_THREAD_DETACH

    LPVOID lpReserved : parameter to pass down to DllMain
        If dwReason is DLL_PROCESS_ATTACH, lpvReserved is NULL for dynamic loads and non-NULL for static loads.
        If dwReason is DLL_PROCESS_DETACH, lpvReserved is NULL if DllMain has been called by using FreeLibrary
            and non-NULL if DllMain has been called during process termination.

(no return value)

Notes :
    This is used to send DLL_THREAD_*TACH messages to modules
--*/
extern "C"
void LOADCallDllMain(DWORD dwReason, LPVOID lpReserved)
{
    MODSTRUCT *module = NULL;
    BOOL InLoadOrder = TRUE; /* true if in load order, false for reverse */
    CPalThread *pThread;

    pThread = InternalGetCurrentThread();
    if (UserCreatedThread != pThread->GetThreadType())
    {
        return;
    }

    /* Validate dwReason */
    switch(dwReason)
    {
    case DLL_PROCESS_ATTACH:
        ASSERT("got called with DLL_PROCESS_ATTACH parameter! Why?\n");
        break;
    case DLL_PROCESS_DETACH:
        ASSERT("got called with DLL_PROCESS_DETACH parameter! Why?\n");
        InLoadOrder = FALSE;
        break;
    case DLL_THREAD_ATTACH:
        TRACE("Calling DllMain(DLL_THREAD_ATTACH) on all known modules.\n");
        break;
    case DLL_THREAD_DETACH:
        TRACE("Calling DllMain(DLL_THREAD_DETACH) on all known modules.\n");
        InLoadOrder = FALSE;
        break;
    default:
        ASSERT("LOADCallDllMain called with unknown parameter %d!\n", dwReason);
        return;
    }

    LockModuleList();

    module = &exe_module;
    do {
        if (!InLoadOrder)
            module = module->prev;

        if (module->threadLibCalls)
        {
            if (module->pDllMain)
            {
#if _ENABLE_DEBUG_MESSAGES_
                /* reset ENTRY nesting level back to zero while inside the callback... */
                int old_level;
                old_level = DBG_change_entrylevel(0);
#endif /* _ENABLE_DEBUG_MESSAGES_ */

                {
                    // This module may be foreign to our PAL, so leave our PAL.
                    // If it depends on us, it will re-enter.
                    PAL_LeaveHolder holder;
                    module->pDllMain(module->hinstance, dwReason, lpReserved);
                }

#if _ENABLE_DEBUG_MESSAGES_
                /* ...and set nesting level back to what it was */
                DBG_change_entrylevel(old_level);
#endif /* _ENABLE_DEBUG_MESSAGES_ */
            }
        }

        if (InLoadOrder)
            module = module->next;
    } while (module != &exe_module);

    UnlockModuleList();
}

/*++
Function:
    DisableThreadLibraryCalls

See MSDN doc.
--*/
BOOL
PALAPI
DisableThreadLibraryCalls(
    IN HMODULE hLibModule)
{
    BOOL ret = FALSE;
    MODSTRUCT *module;
    PERF_ENTRY(DisableThreadLibraryCalls);
    ENTRY("DisableThreadLibraryCalls(hLibModule=%p)\n", hLibModule);

    if (terminator)
    {
        /* PAL shutdown in progress - ignore DisableThreadLibraryCalls */
        ret = TRUE;
        goto done_nolock;
    }

    LockModuleList();
    module = (MODSTRUCT *) hLibModule;

    if (!LOADValidateModule(module))
    {
        // DisableThreadLibraryCalls() does nothing when given
        // an invalid module handle. This matches the Windows
        // behavior, though it is counter to MSDN.
        WARN("Invalid module handle %p\n", hLibModule);
        ret = TRUE;
        goto done;
    }

    module->threadLibCalls = FALSE;
    ret = TRUE;

done:
    UnlockModuleList();
done_nolock:
    LOGEXIT("DisableThreadLibraryCalls returns BOOL %d\n", ret);
    PERF_EXIT(DisableThreadLibraryCalls);
    return ret;
}

/* Static function definitions ************************************************/

// Checks the library path for null or empty string. On error, calls SetLastError() and returns false.
template<class TChar>
bool LOADVerifyLibraryPath(const TChar *libraryPath)
{
    if (libraryPath == nullptr)
    {
        ERROR("libraryPath is null\n");
        SetLastError(ERROR_MOD_NOT_FOUND);
        return false;
    }
    if (libraryPath[0] == '\0')
    {
        ERROR("libraryPath is empty\n");
        SetLastError(ERROR_INVALID_PARAMETER);
        return false;
    }
    return true;
}

// Converts the wide char library path string into a multibyte-char string. On error, calls SetLastError() and returns false.
bool LOADConvertLibraryPathWideStringToMultibyteString(
    LPCWSTR wideLibraryPath,
    LPSTR multibyteLibraryPath,
    INT *multibyteLibraryPathLengthRef)
{
    _ASSERTE(multibyteLibraryPathLengthRef != nullptr);
    _ASSERTE(wideLibraryPath != nullptr);

    size_t length = (PAL_wcslen(wideLibraryPath)+1) * MaxWCharToAcpLength;
    *multibyteLibraryPathLengthRef = WideCharToMultiByte(CP_ACP, 0, wideLibraryPath, -1, multibyteLibraryPath,
                                                        length, nullptr, nullptr);

    if (*multibyteLibraryPathLengthRef == 0)
    {
        DWORD dwLastError = GetLastError();
        if (dwLastError == ERROR_INSUFFICIENT_BUFFER)
        {
            ERROR("wideLibraryPath converted to a multibyte string is longer than MAX_LONGPATH (%d)!\n", MAX_LONGPATH);
        }
        else
        {
            ASSERT("WideCharToMultiByte failure! error is %d\n", dwLastError);
        }
        SetLastError(ERROR_INVALID_PARAMETER);
        return false;
    }
    return true;
}

/*++
Function :
    LOADValidateModule

    Check whether the given MODSTRUCT pointer is valid

Parameters :
    MODSTRUCT *module : module to check

Return value :
    TRUE if module is valid, FALSE otherwise

--*/
static BOOL LOADValidateModule(MODSTRUCT *module)
{
    MODSTRUCT *modlist_enum;

    LockModuleList();

    modlist_enum = &exe_module;

    /* enumerate through the list of modules to make sure the given handle is
       really a module (HMODULEs are actually MODSTRUCT pointers) */
    do
    {
        if (module == modlist_enum)
        {
            /* found it; check its integrity to be on the safe side */
            if (module->self != module)
            {
                ERROR("Found corrupt module %p!\n",module);
                UnlockModuleList();
                return FALSE;
            }
            UnlockModuleList();
            TRACE("Module %p is valid (name : %S)\n", module, MODNAME(module));
            return TRUE;
        }
        modlist_enum = modlist_enum->next;
    }
    while (modlist_enum != &exe_module);

    TRACE("Module %p is NOT valid.\n", module);
    UnlockModuleList();
    return FALSE;
}

/*++
Function :
    LOADGetModuleFileName [internal]

    Retrieve the module's full path if it is known, the short name given to
    LoadLibrary otherwise.

Parameters :
    MODSTRUCT *module : module to check

Return value :
    pointer to internal buffer with name of module (Unicode)

Notes :
    this function assumes that the module critical section is held, and that
    the module has already been validated.
--*/
static LPWSTR LOADGetModuleFileName(MODSTRUCT *module)
{
    LPWSTR module_name;
    /* special case : if module is NULL, we want the name of the executable */
    if (!module)
    {
        module_name = exe_module.lib_name;
        TRACE("Returning name of main executable\n");
        return module_name;
    }

    /* return "real" name of module if it is known. we have this if LoadLibrary
       was given an absolute or relative path; we can also determine it at the
       first GetProcAdress call. */
    TRACE("Returning full path name of module\n");
    return module->lib_name;
}

/*++
Function :
    LOADAllocModule

    Allocate and initialize a new MODSTRUCT structure

Parameters :
    void *dl_handle :   handle returned by dl_open, goes in MODSTRUCT::dl_handle

    char *name :        name of new module. after conversion to widechar,
                        goes in MODSTRUCT::lib_name

Return value:
    a pointer to a new, initialized MODSTRUCT strucutre, or NULL on failure.

Notes :
    'name' is used to initialize MODSTRUCT::lib_name. The other member is set to NULL
    In case of failure (in malloc or MBToWC), this function sets LastError.
--*/
static MODSTRUCT *LOADAllocModule(void *dl_handle, LPCSTR name)
{
    MODSTRUCT *module;
    LPWSTR wide_name;

    /* no match found : try to create a new module structure */
    module = (MODSTRUCT *)InternalMalloc(sizeof(MODSTRUCT));
    if (!module)
    {
        ERROR("malloc() failed! errno is %d (%s)\n", errno, strerror(errno));
        return NULL;
    }

    wide_name = UTIL_MBToWC_Alloc(name, -1);
    if (NULL == wide_name)
    {
        ERROR("couldn't convert name to a wide-character string\n");
        InternalFree(module);
        return NULL;
    }

    module->dl_handle = dl_handle;
#if NEED_DLCOMPAT
    if (isdylib(module))
    {
        module->refcount = -1;
    }
    else
    {
        module->refcount = 1;
    }
#else   // NEED_DLCOMPAT
    module->refcount = 1;
#endif  // NEED_DLCOMPAT
    module->self = module;
    module->hinstance = NULL;
    module->threadLibCalls = TRUE;
    module->next = NULL;
    module->prev = NULL;

    module->lib_name = wide_name;

    return module;
}

/*
Function:
    LOADLoadLibraryDirect [internal]

    Loads a library using a system call, without registering the library with the module list.

Parameters:
    LPCSTR libraryNameOrPath:           The library to load.
    bool setLastError:                  True to set the last error upon failure, false otherwise.

Return value:
    System handle to the loaded library, or nullptr upon failure (error is set via SetLastError() if 'setLastError' is true).
*/
static HMODULE LOADLoadLibraryDirect(LPCSTR libraryNameOrPath, bool setLastError)
{
    _ASSERTE(libraryNameOrPath != nullptr);
    _ASSERTE(libraryNameOrPath[0] != '\0');

    HMODULE dl_handle = dlopen(libraryNameOrPath, RTLD_LAZY);
    if (dl_handle != nullptr)
    {
        TRACE("dlopen() found module %s\n", libraryNameOrPath);
    }
    else if (setLastError)
    {
        WARN("dlopen() failed; dlerror says '%s'\n", dlerror());
        SetLastError(ERROR_MOD_NOT_FOUND);
    }

    return dl_handle;
}

/*
Function:
    LOADRegisterLibraryDirect [internal]

    Registers a system handle to a loaded library with the module list.

Parameters:
    HMODULE dl_handle:                  System handle to the loaded library.
    LPCSTR libraryNameOrPath:           The library that was loaded.
    BOOL fDynamic:                      TRUE if dynamic load through LoadLibrary, FALSE if static load through RegisterLibrary.

Return value:
    PAL handle to the loaded library, or nullptr upon failure (error is set via SetLastError()).
*/
static HMODULE LOADRegisterLibraryDirect(HMODULE dl_handle, LPCSTR libraryNameOrPath, BOOL fDynamic)
{
    _ASSERTE(dl_handle != nullptr);
    _ASSERTE(libraryNameOrPath != nullptr);
    _ASSERTE(libraryNameOrPath[0] != '\0');

    MODSTRUCT *module;
    DWORD dwError;

#if !RETURNS_NEW_HANDLES_ON_REPEAT_DLOPEN
    /* search module list for a match. */
    module = &exe_module;
    do
    {
        if (dl_handle == module->dl_handle)
        {
            /* found the handle. increment the refcount and return the
               existing module structure */
            TRACE("Found matching module %p for module name %s\n",
                 module, libraryNameOrPath);
            if (module->refcount != -1)
                module->refcount++;
            dlclose(dl_handle);
            return module;
        }
        module = module->next;
    } while (module != &exe_module);
#endif

    TRACE("Module doesn't exist : creating %s.\n", libraryNameOrPath);
    module = LOADAllocModule(dl_handle, libraryNameOrPath);

    if (NULL == module)
    {
        ERROR("couldn't create new module\n");
        SetLastError(ERROR_NOT_ENOUGH_MEMORY);
        dlclose(dl_handle);
        return nullptr;
    }

    /* Add the new module on to the end of the list */
    module->prev = exe_module.prev;
    module->next = &exe_module;
    exe_module.prev->next = module;
    exe_module.prev = module;

#if RETURNS_NEW_HANDLES_ON_REPEAT_DLOPEN
    module->inode = stat_buf.st_ino;
    module->device = stat_buf.st_dev;
#endif

    /* We now get the address of DllMain if the module contains one. We save
       the last error and restore it afterward, because our caller doesn't
       care about GetProcAddress failures. */
    dwError = GetLastError();

    module->pDllMain = (PDLLMAIN)GetProcAddress((HMODULE)module, "DllMain");

    SetLastError(dwError);

    /* If it did contain a DllMain, call it. */
    if (module->pDllMain)
    {
        TRACE("Calling DllMain (%p) for module %S\n",
            module->pDllMain,
            module->lib_name ? module->lib_name : W16_NULLSTRING);

        if (NULL == module->hinstance)
        {
            PREGISTER_MODULE registerModule = (PREGISTER_MODULE)dlsym(module->dl_handle, "PAL_RegisterModule");
            if (registerModule)
            {
                module->hinstance = registerModule(libraryNameOrPath);
            }
            else
            {
                // If the target module doesn't have the PAL_RegisterModule export, then use this PAL's
                // module handle assuming that the target module is referencing this PAL's exported
                // functions on said handle.
                module->hinstance = (HINSTANCE)module;
            }
        }

        BOOL dllMainRetVal;
        {
#if _ENABLE_DEBUG_MESSAGES_
            /* reset ENTRY nesting level back to zero while inside the callback... */
            int old_level;
            old_level = DBG_change_entrylevel(0);
#endif /* _ENABLE_DEBUG_MESSAGES_ */

            {
                // This module may be foreign to our PAL, so leave our PAL.
                // If it depends on us, it will re-enter.
                PAL_LeaveHolder holder;
                dllMainRetVal = module->pDllMain(module->hinstance, DLL_PROCESS_ATTACH, fDynamic ? NULL : (LPVOID)-1);
            }

#if _ENABLE_DEBUG_MESSAGES_
            /* ...and set nesting level back to what it was */
            DBG_change_entrylevel(old_level);
#endif /* _ENABLE_DEBUG_MESSAGES_ */
        }

        // If DlMain(DLL_PROCESS_ATTACH) returns FALSE, we must immediately unload the module
        if (!dllMainRetVal)
        {
            ERROR("DllMain returned FALSE; unloading module.\n");
            module->pDllMain = NULL;
            FreeLibrary((HMODULE)module);
            SetLastError(ERROR_DLL_INIT_FAILED);
            module = NULL;
            return nullptr;
        }
    }
    else
    {
        TRACE("Module does not contain a DllMain function.\n");
    }

    return module;
}

/*++
Function :
    LOADLoadLibrary [internal]

    implementation of LoadLibrary (for use by the A/W variants)

Parameters :
    LPSTR shortAsciiName : name of module as specified to LoadLibrary

    BOOL fDynamic : TRUE if dynamic load through LoadLibrary, FALSE if static load through RegisterLibrary

Return value :
    handle to loaded module

--*/
static HMODULE LOADLoadLibrary(LPCSTR shortAsciiName, BOOL fDynamic)
{
    HMODULE module = NULL;
    HMODULE dl_handle = NULL;

    // Check whether we have been requested to load 'libc'. If that's the case then use the
    // full name of the library that is defined in <gnu/lib-names.h> by the LIBC_SO constant.
    // The problem is that calling dlopen("libc.so") will fail for libc even thought it works
    // for other libraries. The reason is that libc.so is just linker script (i.e. a test file).
    // As a result, we have to use the full name (i.e. lib.so.6) that is defined by LIBC_SO.
    if (strcmp(shortAsciiName, LIBC_NAME_WITHOUT_EXTENSION) == 0)
    {
#if defined(__APPLE__)
        shortAsciiName = "libc.dylib";
#elif defined(__FreeBSD__)
        shortAsciiName = FREEBSD_LIBC;
#else
        shortAsciiName = LIBC_SO;
#endif
    }

    LockModuleList();

    // See if file can be dlopen()ed; this should work even if it's already loaded
    {
        // See GetProcAddress for an explanation why we leave the PAL.
        PAL_LeaveHolder holder;

        dl_handle = LOADLoadLibraryDirect(shortAsciiName, false /* setLastError */);
    }

    if (!dl_handle)
    {
        WARN("dlopen() failed; dlerror says '%s'\n", dlerror());
        SetLastError(ERROR_MOD_NOT_FOUND);
        goto done;
    }

    module = LOADRegisterLibraryDirect(dl_handle, shortAsciiName, fDynamic);

done:
    UnlockModuleList();
    return module;
}

/*++
Function :
    LOAD_SEH_CallDllMain

    Exception-safe call to DllMain.

Parameters :
    MODSTRUCT *module : module whose DllMain must be called

    DWORD dwReason : parameter to pass down to DllMain, one of DLL_PROCESS_ATTACH, DLL_PROCESS_DETACH,
        DLL_THREAD_ATTACH, DLL_THREAD_DETACH

    LPVOID lpvReserved : parameter to pass down to DllMain,
        If dwReason is DLL_PROCESS_ATTACH, lpvReserved is NULL for dynamic loads and non-NULL for static loads.
        If dwReason is DLL_PROCESS_DETACH, lpvReserved is NULL if DllMain has been called by using FreeLibrary
            and non-NULL if DllMain has been called during process termination.

(no return value)

Notes :
This function is called from LOADFreeModules. Since we get there from
PAL_Terminate, we can't let exceptions in DllMain go unhandled :
TerminateProcess would be called, and would have to abort uncleanly because
termination was already started. So we catch the exception and ignore it;
we're terminating anyway.
*/
static void LOAD_SEH_CallDllMain(MODSTRUCT *module, DWORD dwReason, LPVOID lpReserved)
{
#if _ENABLE_DEBUG_MESSAGES_
    /* reset ENTRY nesting level back to zero while inside the callback... */
    int old_level = DBG_change_entrylevel(0);
#endif /* _ENABLE_DEBUG_MESSAGES_ */

    struct Param
    {
        MODSTRUCT *module;
        DWORD dwReason;
        LPVOID lpReserved;
    } param;
    param.module = module;
    param.dwReason = dwReason;
    param.lpReserved = lpReserved;

    PAL_TRY(Param *, pParam, &param)
    {
        TRACE("Calling DllMain (%p) for module %S\n",
              pParam->module->pDllMain,
              pParam->module->lib_name ? pParam->module->lib_name : W16_NULLSTRING);

        {
            // This module may be foreign to our PAL, so leave our PAL.
            // If it depends on us, it will re-enter.
            PAL_LeaveHolder holder;
            pParam->module->pDllMain(pParam->module->hinstance, pParam->dwReason, pParam->lpReserved);
        }
    }
    PAL_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
    {
        WARN("Call to DllMain (%p) got an unhandled exception; "
              "ignoring.\n", module->pDllMain);
    }
    PAL_ENDTRY

#if _ENABLE_DEBUG_MESSAGES_
    /* ...and set nesting level back to what it was */
    DBG_change_entrylevel(old_level);
#endif /* _ENABLE_DEBUG_MESSAGES_ */
}

/*++
Function:
  LockModuleList

Abstract
  Enter the critical section associated to the module list

Parameter
  void

Return
  void
--*/
extern "C"
void LockModuleList()
{
    CPalThread * pThread =
        (PALIsThreadDataInitialized() ? InternalGetCurrentThread() : NULL);

    InternalEnterCriticalSection(pThread , &module_critsec);
}

/*++
Function:
  UnlockModuleList

Abstract
  Leave the critical section associated to the module list

Parameter
  void

Return
  void
--*/
extern "C"
void UnlockModuleList()
{
    CPalThread * pThread =
        (PALIsThreadDataInitialized() ? InternalGetCurrentThread() : NULL);

    InternalLeaveCriticalSection(pThread , &module_critsec);
}

/*++
    PAL_LOADLoadPEFile

    Map a PE format file into memory like Windows LoadLibrary() would do.
    Doesn't apply base relocations if the function is relocated.

Parameters:
    IN hFile - file to map

Return value:
    non-NULL - the base address of the mapped image
    NULL - error, with last error set.
--*/

void * PAL_LOADLoadPEFile(HANDLE hFile)
{
    ENTRY("PAL_LOADLoadPEFile (hFile=%p)\n", hFile);

    void * loadedBase = MAPMapPEFile(hFile);

#ifdef _DEBUG
    if (loadedBase != NULL)
    {
        char* envVar = getenv("PAL_ForcePEMapFailure");
        if (envVar && strlen(envVar) > 0)
        {
            TRACE("Forcing failure of PE file map, and retry\n");
            PAL_LOADUnloadPEFile(loadedBase); // unload it
            loadedBase = MAPMapPEFile(hFile); // load it again
        }
    }
#endif // _DEBUG

    LOGEXIT("PAL_LOADLoadPEFile returns %p\n", loadedBase);
    return loadedBase;
}

/*++
    PAL_LOADUnloadPEFile

    Unload a PE file that was loaded by PAL_LOADLoadPEFile().

Parameters:
    IN ptr - the file pointer returned by PAL_LOADLoadPEFile()

Return value:
    TRUE - success
    FALSE - failure (incorrect ptr, etc.)
--*/

BOOL PAL_LOADUnloadPEFile(void * ptr)
{
    BOOL retval = FALSE;

    ENTRY("PAL_LOADUnloadPEFile (ptr=%p)\n", ptr);

    if (NULL == ptr)
    {
        ERROR( "Invalid pointer value\n" );
    }
    else
    {
        retval = MAPUnmapPEFile(ptr);
    }

    LOGEXIT("PAL_LOADUnloadPEFile returns %d\n", retval);
    return retval;
}

/*++
    LOADInitializeCoreCLRModule

    Run the initialization methods for CoreCLR module (the module containing this PAL).

Parameters:
    None

Return value:
    TRUE if successful
    FALSE if failure
--*/
BOOL LOADInitializeCoreCLRModule()
{
    MODSTRUCT *module = LOADGetPalLibrary();
    if (!module)
    {
        ERROR("Can not load the PAL module\n");
        return FALSE;
    }
    PDLLMAIN pRuntimeDllMain = (PDLLMAIN)dlsym(module->dl_handle, "CoreDllMain");
    if (!pRuntimeDllMain)
    {
        ERROR("Can not find the CoreDllMain entry point\n");
        return FALSE;
    }
    return pRuntimeDllMain(module->hinstance, DLL_PROCESS_ATTACH, NULL);
}

/*++
Function :
    LOADGetPalLibrary

    Load and initialize the PAL module.

Parameters :
    None

Return value :
    pointer to module struct

--*/
MODSTRUCT *LOADGetPalLibrary()
{
    if (pal_module == NULL)
    {
        // Initialize the pal module (the module containing LOADPalLibrary). Assumes that
        // the PAL is linked into the coreclr module because we use the module name containing
        // this function for the coreclr path.
        TRACE("Loading module for PAL library\n");

        Dl_info info;
        if (dladdr((PVOID)&LOADGetPalLibrary, &info) == 0)
        {
            ERROR("LOADGetPalLibrary: dladdr() failed. dlerror message is \"%s\"\n", dlerror());
            goto exit;
        }
        // Stash a copy of the CoreCLR installation path in a global variable.
        // Make sure it's terminated with a slash.
        if (g_szCoreCLRPath == NULL)
        {
            g_szCoreCLRPath = (char*) InternalMalloc(g_cbszCoreCLRPath);

            if (g_szCoreCLRPath == NULL)
            {
                ERROR("LOADGetPalLibrary: InternalMalloc failed!");
                goto exit;
            }
        }

        if (strcpy_s(g_szCoreCLRPath, g_cbszCoreCLRPath, info.dli_fname) != SAFECRT_SUCCESS)
        {
            ERROR("LOADGetPalLibrary: strcpy_s failed!");
            goto exit;
        }
        pal_module = (MODSTRUCT *)LOADLoadLibrary(info.dli_fname, FALSE);
    }

exit:
    return pal_module;
}

// Get base address of the module containing a given symbol
PALAPI
LPCVOID
PAL_GetSymbolModuleBase(void *symbol)
{
    LPCVOID retval = NULL;

    PERF_ENTRY(PAL_GetPalModuleBase);
    ENTRY("PAL_GetPalModuleBase\n");

    if (symbol == NULL)
    {
        TRACE("Can't get base address. Argument symbol == NULL\n");
        SetLastError(ERROR_INVALID_DATA);
    }
    else
    {
        Dl_info info;
        if (dladdr(symbol, &info) != 0)
        {
            retval = info.dli_fbase;
        }
        else
        {
            TRACE("Can't get base address of the current module\n");
            SetLastError(ERROR_INVALID_DATA);
        }
    }

    LOGEXIT("PAL_GetPalModuleBase returns %p\n", retval);
    PERF_EXIT(PAL_GetPalModuleBase);
    return retval;
}


text:
import * as tl from "azure-pipelines-task-lib/task";

export class SecureFileHelpers {
    private static fileExtension: string = ".filename";

    constructor(retryCount?: number) {
        tl.debug('Mock SecureFileHelpers constructor');

        if (retryCount) {
            tl.debug('Mock SecureFileHelpers retry count set to: ' + retryCount);
        } else {
            tl.debug('Mock SecureFileHelpers retry count not set.');
        }
    }

    async downloadSecureFile(secureFileId: string) {
        tl.debug('Mock downloadSecureFile with id = ' + secureFileId);
        const fileName: string = `${secureFileId}${SecureFileHelpers.fileExtension}`;
        const tempDownloadPath: string = `/build/temp/${fileName}`;
        return tempDownloadPath;
    }

    deleteSecureFile(secureFileId: string) {
        tl.debug('Mock deleteSecureFile with id = ' + secureFileId);
    }

    static setFileExtension(extension: string): void {
        this.fileExtension = extension;
    }
}

redpajama_set_name: RedPajamaGithub


text:
import { Queue } from '../queue'
import { BitcoinBlockMetadata } from '../events'

export async function publish(id: string) {
  const queue = new Queue()

  const bitcoinBlock: BitcoinBlockMetadata = {
    blockHeight: 1000,
    blockHash: 'bitcoin block hash',
    timestamp: 3543,
    parentHash: '',
    poet: [{
      torrentHash: id,
      transactionHash: 'transaction hash',
      outputIndex: 0,
      transactionOrder: 2
    }]
  }

  await queue.announceBitcoinBlock(bitcoinBlock)

}

export default async function create() {
  return await publish(process.argv[2])
}

if (!module.parent) {
  create().catch(error => {
    console.log(error, error.stack)
  })
}


text:
package com.netflix.spinnaker.clouddriver.kubernetes.description.manifest;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.google.common.base.Strings;
import com.netflix.spinnaker.clouddriver.kubernetes.description.KubernetesAtomicOperationDescription;
import com.netflix.spinnaker.clouddriver.kubernetes.description.KubernetesCoordinates;
import com.netflix.spinnaker.clouddriver.kubernetes.security.KubernetesSelectorList;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import lombok.Data;
import lombok.EqualsAndHashCode;

@EqualsAndHashCode(callSuper = true)
@Data
public class KubernetesDeleteManifestDescription extends KubernetesAtomicOperationDescription {
  private Map<String, String> options;
  private String manifestName;
  private String location;
  private List<String> kinds = new ArrayList<>();
  private KubernetesSelectorList labelSelectors = new KubernetesSelectorList();

  @JsonIgnore
  public boolean isDynamic() {
    return Strings.isNullOrEmpty(manifestName);
  }

  public List<KubernetesCoordinates> getAllCoordinates() {
    return kinds.stream()
        .map(
            k ->
                KubernetesCoordinates.builder()
                    .namespace(location)
                    .kind(KubernetesKind.fromString(k))
                    .build())
        .collect(Collectors.toList());
  }

  @JsonIgnore
  public KubernetesCoordinates getPointCoordinates() {
    return KubernetesCoordinates.builder()
        .namespace(location)
        .fullResourceName(manifestName)
        .build();
  }
}


text:
<?php $cfg = array(
  'title'             => $lang->get('System settings', 'console.common') . ' » ' . $lang->get('Check for updates', 'console.common'),
  'menu_active'       => 'opt',
  'sub_active'        => 'chkver',
  'baigoSubmit'       => 'true',
);

include($tpl_include . 'console_head' . GK_EXT_TPL); ?>

  <form name="opt_form" id="opt_form" action="<?php echo $hrefRow['chkver-submit']; ?>" class="mb-3">
    <input type="hidden" name="<?php echo $token['name']; ?>" value="<?php echo $token['value']; ?>">

    <button type="submit" class="btn btn-primary">
      <?php echo $lang->get('Check for updates', 'console.common'); ?>
    </button>
  </form>

  <?php if (isset($latest['prd_pub']) && $installed['prd_installed_pub'] < $latest['prd_pub']) { ?>

      <?php include($tpl_icon . 'exclamation-triangle' . BG_EXT_SVG); ?>
      <?php echo $lang->get('There are new versions, this is the latest version of the issues and help.'); ?>

  <?php } else { ?>

      <?php include($tpl_icon . 'heart' . BG_EXT_SVG); ?>
      <?php echo $lang->get('Your version is the latest!'); ?>

  <?php } ?>

  <?php if (isset($latest['prd_pub_datetime']) && $installed['prd_installed_pub'] < $latest['prd_pub']) { ?>

        <?php echo $lang->get('Latest version'); ?>

            <?php echo $lang->get('Version'); ?>
            <?php echo $latest['prd_ver']; ?>

            <?php echo $lang->get('Issues time'); ?>
            <?php echo $latest['prd_pub_datetime']; ?>

            <?php echo $lang->get('Announcement'); ?>
            <a href="<?php echo $latest['prd_announcement']; ?>" target="_blank"><?php echo $latest['prd_announcement']; ?>

            <?php echo $lang->get('Download'); ?>
            <a href="<?php echo $latest['prd_download']; ?>" target="_blank"><?php echo $latest['prd_download']; ?>

  <?php } ?>

      <?php echo $lang->get('Current version'); ?>

          <?php echo $lang->get('Version'); ?>
          <?php echo $installed['prd_installed_ver']; ?>

          <?php echo $lang->get('Issues time'); ?>
          <?php echo $installed['prd_installed_pub_datetime']; ?>

          <?php echo $lang->get('Installation time'); ?>
          <?php echo $installed['prd_installed_datetime']; ?>

<?php include($tpl_include . 'console_foot' . GK_EXT_TPL); ?>

<?php include($tpl_include . 'html_foot' . GK_EXT_TPL);


text:
<?php
namespace Riskio\EventScheduler\ValueObject\Exception;

use Riskio\EventScheduler\Exception\InvalidArgumentException as BaseInvalidArgumentException;

class InvalidWeekException
    extends BaseInvalidArgumentException
{}


text:
package org.mobadsl.semantic.model.moba;

import org.eclipse.emf.ecore.EObject;

/**
 *
 * A representation of the model object 'REST Abstract Attribute'.
 *
 *
 *

 * The following features are supported:
 *

 *

 *
{@link org.mobadsl.semantic.model.moba.MobaRESTAbstractAttribute#getAliasString Alias String}

 *
{@link org.mobadsl.semantic.model.moba.MobaRESTAbstractAttribute#getAliasConst Alias Const}

 *
{@link org.mobadsl.semantic.model.moba.MobaRESTAbstractAttribute#getAlias Alias}

 *
{@link org.mobadsl.semantic.model.moba.MobaRESTAbstractAttribute#isAttachment Attachment}

 *

 *
 * @see org.mobadsl.semantic.model.moba.MobaPackage#getMobaRESTAbstractAttribute()
 * @model abstract="true"
 * @generated
 */
public interface MobaRESTAbstractAttribute extends EObject {
	/**
	 * Returns the value of the 'Alias String' attribute.
	 *
	 *

	 * If the meaning of the 'Alias String' attribute isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Alias String' attribute.
	 * @see #setAliasString(String)
	 * @see org.mobadsl.semantic.model.moba.MobaPackage#getMobaRESTAbstractAttribute_AliasString()
	 * @model
	 * @generated
	 */
	String getAliasString();

	/**
	 * Sets the value of the '{@link org.mobadsl.semantic.model.moba.MobaRESTAbstractAttribute#getAliasString Alias String}' attribute.
	 *
	 *
	 * @param value the new value of the 'Alias String' attribute.
	 * @see #getAliasString()
	 * @generated
	 */
	void setAliasString(String value);

	/**
	 * Returns the value of the 'Alias Const' reference.
	 *
	 *

	 * If the meaning of the 'Alias Const' reference isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Alias Const' reference.
	 * @see #setAliasConst(MobaConstant)
	 * @see org.mobadsl.semantic.model.moba.MobaPackage#getMobaRESTAbstractAttribute_AliasConst()
	 * @model
	 * @generated
	 */
	MobaConstant getAliasConst();

	/**
	 * Sets the value of the '{@link org.mobadsl.semantic.model.moba.MobaRESTAbstractAttribute#getAliasConst Alias Const}' reference.
	 *
	 *
	 * @param value the new value of the 'Alias Const' reference.
	 * @see #getAliasConst()
	 * @generated
	 */
	void setAliasConst(MobaConstant value);

	/**
	 * Returns the value of the 'Alias' attribute.
	 *
	 *

	 * If the meaning of the 'Alias' attribute isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Alias' attribute.
	 * @see org.mobadsl.semantic.model.moba.MobaPackage#getMobaRESTAbstractAttribute_Alias()
	 * @model transient="true" changeable="false" volatile="true" derived="true"
	 * @generated
	 */
	String getAlias();

	/**
	 * Returns the value of the 'Attachment' attribute.
	 *
	 *

	 * If the meaning of the 'Attachment' attribute isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Attachment' attribute.
	 * @see #setAttachment(boolean)
	 * @see org.mobadsl.semantic.model.moba.MobaPackage#getMobaRESTAbstractAttribute_Attachment()
	 * @model
	 * @generated
	 */
	boolean isAttachment();

	/**
	 * Sets the value of the '{@link org.mobadsl.semantic.model.moba.MobaRESTAbstractAttribute#isAttachment Attachment}' attribute.
	 *
	 *
	 * @param value the new value of the 'Attachment' attribute.
	 * @see #isAttachment()
	 * @generated
	 */
	void setAttachment(boolean value);

} // MobaRESTAbstractAttribute


text:
class Marathon < ActiveRecord::Base
  acts_as_paranoid
  has_many :users
  validates :name, presence: true, length: { minimum: 3, maximum: 255 }

  before_save do
    name.strip!
  end

  def self.all_can_register
    where(can_register: true).order(:name)
  end
end


text:
title: Learning to Create Amidst Chaos
author: sanjiv sahayam
description: Chapter summary of &quote;Learning to Create Amidst Chaos&quote; by Erin Rooney Dolan from the book: &quote;Manage Your Day-To-Day&quote;.
tags: chapter, ideas
---
Ideas from the chapter "Learning to Create Amidst Chaos" from the book [Manage Your Day-To-Day](http://99u.com/book/manage-your-day-to-day-2) by Erin Rooney Dolan.

1. Negative distractions interfere with our creative work. (Eg. TV, Social Media, Chatting with coworkers etc.)
2. Positive distractions help us to do more creative work. (Eg. Rewards after completing a task, going for a walk etc.)
3. Developing any habit can strengthen willpower in other areas of your life.
4. Once a new habit is ingrained and can be completed without much effort or thought, that energy can be turned to other activities requiring more self-control.
4. Tasks done on "autopilot" do not use up our stockpile of energy like tasks that have to be consciously completed.
5. Getting a good night's sleep will help you improve your self-control.
6. Shifting from mindful to mindless work gives the brain time to process complex problems in a relaxed state and also restores the energy necessary for the next round of mindful work.
7. Repetition is a form of mesmerism. Mesmerise yourself to reach a deeper state of mind.
8. To hold repetition for a long period of time requires mental and physical strength.


text:
Go to **Assets/Senspark EE-x/Settings** and enable AdMob plugin

## Basic usage
Initialization
```csharp
var plugin = EE.PluginManager.CreatePlugin<EE.IAdMob>();
EE.Utils.NoAwait(async () => {
    var result = await plugin.Initialize();
    // Handle initialization result.
});
```

Creates and show a banner ad.
```csharp
var ad = plugin.CreateBannerAd("ad_id", EE.AdMobBannerAdSize.Normal);

// Load the ad in background.
ad.Load();

// Show the ad.
ad.IsVisible = true;
```

Creates and show an interstitial ad
```csharp
var ad = plugin.CreateInterstitialAd("ad_id");

// Load and show the ad.
EE.Utils.NoAwait(async () => {
    await ad.Load();
    await ad.Show();
});
```

Creates and show a rewarded ad
```csharp
var ad = plugin.CreateRewardedAd("ad_id");

// Load and show the ad.
EE.Utils.NoAwait(async () => {
    await ad.Load();
    await ad.Show();
});
```


text:
<html>
<head>
<script>if (typeof module === 'object') {window.module = module; module = undefined;}</script>
<script src="../jquery-1.11.1.min.js"></script>
<script src="../mousetrap.min.js"></script>
<script>if (window.module) module = window.module;</script>
<script src="../hotwritingBook.js"></script>
<link rel="stylesheet" type="text/css" href="../hotwriting.css">
<script src="explosionbear.js"></script>
<audio id="explosion1" src='1.mp3' preload="auto"></audio>
<audio id="explosion2" src='2.mp3' preload="auto"></audio>
<audio id="explosion3" src='3.mp3' preload="auto"></audio>
<audio id="explosion4" src='4.mp3' preload="auto"></audio>
<audio id="EBNormal" src='EBSound.mp3' preload="auto"></audio>
<audio id="EBQuestion" src='EBQuestion.mp3' preload="auto"></audio>
<audio id="EBExclamation" src='EBExclamation.mp3' preload="auto"></audio>
<audio id="crazyTrain" src='CrazyTrainRiff.mp3' preload="auto"></audio>
<style>
html {
  background: url(EBIntro.png) no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}
body:after{
    display:none;
    content: url(EB1.jpg) url(EB2.jpg) url(EB3.jpg) url(EB4.jpg) url(XB1.jpg) url(XB2.jpg) url(XB3.jpg) url(XB4.jpg) url(XB5.jpg) url(XB6.jpg);
}
</style>
</head>
<body>
</body>
</html>


text:
import os, sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

import config
import speech_recognition as sr

r = sr.Recognizer()
m = sr.Microphone()

try:
    print("A moment of silence, please...")
    with m as source: r.adjust_for_ambient_noise(source)
    print("Set minimum energy threshold to {}".format(r.energy_threshold))
    while True:
        print("Say something!")
        with m as source: audio = r.listen(source)
        print("Got it! Now to recognize it...")
        try:
            # recognize speech using Google Speech Recognition
            # value = r.recognize_google(audio, language="cmn-Hant-TW")
            value = r.recognize_baidu(audio, app_key=config.APP_KEY, secret_key=config.SECRET_KEY)

            # we need some special handling here to correctly print unicode characters to standard output
            if str is bytes:  # this version of Python uses bytes for strings (Python 2)
                print(u"You said {}".format(value).encode("utf-8"))
            else:  # this version of Python uses unicode for strings (Python 3+)
                print("You said {}".format(value))
        except sr.UnknownValueError:
            print("Oops! Didn't catch that")
        except sr.RequestError as e:
            print("Uh oh! Couldn't request results from Google Speech Recognition service; {0}".format(e))
except KeyboardInterrupt:
    pass


text:
import reducers from './reducers';

describe('reducers', () => {
  describe('drawerOpen', () => {
    it('should handle the initial state', () => {
      expect(reducers(undefined, {}).drawerOpen).toEqual(false);
    });

    it('should handle the TOGGLE_DRAWER action', () => {
      expect(
        reducers({ drawerOpen: false }, { type: 'CHANGE_DRAWER', open: true })
          .drawerOpen
      ).toEqual(true);

      expect(
        reducers({ drawerOpen: true }, { type: 'CHANGE_DRAWER', open: false })
          .drawerOpen
      ).toEqual(false);
    });
  });

  describe('loginDetails', () => {
    it('should handle the initial state', () => {
      expect(reducers(undefined, {}).loginDetails).toEqual({});
    });

    it('should handle the ADD_LOGIN_DETAILS action', () => {
      expect(
        reducers(
          { loginDetails: {} },
          {
            type: 'ADD_LOGIN_DETAILS',
            site: {
              id: 'a',
              name: 'Site',
              url: 'example.com',
              username: 'User',
              password: 'password'
            }
          }
        ).loginDetails
      ).toEqual({
        a: {
          name: 'Site',
          url: 'example.com',
          username: 'User',
          password: 'password'
        }
      });
    });

    it('should handle the REAUTH_AND_RESTORE_LOGIN_DETAILS action', () => {
      expect(
        reducers(
          { loginDetails: {} },
          {
            type: 'REAUTH_AND_RESTORE_LOGIN_DETAILS',
            masterPassword: 'Master Password',
            loginDetails: {
              a: {
                name: 'Site',
                url: 'example.com',
                username: 'User',
                password: 'password'
              },
              b: {
                name: 'Site 2',
                url: 'example2.com',
                username: 'User 2',
                password: 'password2'
              }
            }
          }
        ).loginDetails
      ).toEqual({
        a: {
          name: 'Site',
          url: 'example.com',
          username: 'User',
          password: 'password'
        },
        b: {
          name: 'Site 2',
          url: 'example2.com',
          username: 'User 2',
          password: 'password2'
        }
      });
    });
  });

  describe('active', () => {
    it('should handle the initial state', () => {
      expect(reducers(undefined, {}).active).toEqual(false);
    });

    it('should handle the ADD_MASTER_PASSWORD action', () => {
      expect(
        reducers(
          { active: false },
          {
            type: 'ADD_MASTER_PASSWORD',
            masterPassword: 'Master Password'
          }
        ).active
      ).toEqual(true);
    });

    it('should handle the REAUTH_AND_RESTORE_LOGIN_DETAILS action', () => {
      expect(
        reducers(
          { active: false },
          {
            type: 'REAUTH_AND_RESTORE_LOGIN_DETAILS',
            masterPassword: 'Master Password',
            loginDetails: {
              a: {
                name: 'Site',
                url: 'example.com',
                username: 'User',
                password: 'password'
              }
            }
          }
        ).active
      ).toEqual(true);
    });
  });

  describe('masterPassword', () => {
    it('should handle the initial state', () => {
      expect(reducers(undefined, {}).masterPassword).toEqual('');
    });

    it('should handle the ADD_MASTER_PASSWORD action', () => {
      expect(
        reducers(
          { masterPassword: '' },
          {
            type: 'ADD_MASTER_PASSWORD',
            masterPassword: 'Master Password'
          }
        ).masterPassword
      ).toEqual('Master Password');
    });

    it('should handle the REAUTH_AND_RESTORE_LOGIN_DETAILS action', () => {
      expect(
        reducers(
          { masterPassword: '' },
          {
            type: 'REAUTH_AND_RESTORE_LOGIN_DETAILS',
            masterPassword: 'Master Password',
            loginDetails: {
              a: {
                name: 'Site',
                url: 'example.com',
                username: 'User',
                password: 'password'
              }
            }
          }
        ).masterPassword
      ).toEqual('Master Password');
    });
  });

  describe('shouldSave', () => {
    it('should handle the initial state', () => {
      expect(reducers(undefined, {}).shouldSave).toEqual(false);
    });

    it('should handle the ADD_LOGIN_DETAILS action', () => {
      expect(
        reducers(
          { shouldSave: false },
          {
            type: 'ADD_LOGIN_DETAILS',
            site: {
              id: 'a',
              name: 'Site',
              url: 'example.com',
              username: 'User',
              password: 'password'
            }
          }
        ).shouldSave
      ).toEqual(true);
    });

    it('should handle the SAVED action', () => {
      expect(
        reducers(
          { shouldSave: true },
          {
            type: 'SAVED'
          }
        ).shouldSave
      ).toEqual(false);
    });
  });

  describe('reauth', () => {
    it('should handle the initial state', () => {
      expect(reducers(undefined, {}).reauth).toEqual(false);
    });

    it('should handle the REAUTH_AND_RESTORE_LOGIN_DETAILS action', () => {
      expect(
        reducers(
          { reauth: true },
          {
            type: 'REAUTH_AND_RESTORE_LOGIN_DETAILS',
            masterPassword: 'Master Password',
            loginDetails: {
              a: {
                name: 'Site',
                url: 'example.com',
                username: 'User',
                password: 'password'
              }
            }
          }
        ).reauth
      ).toEqual(false);
    });

    it('should handle the ADD_MASTER_PASSWORD action', () => {
      expect(
        reducers(
          { reauth: true },
          {
            type: 'ADD_MASTER_PASSWORD',
            masterPassword: 'Master Password'
          }
        ).reauth
      ).toEqual(false);
    });
  });
});


text:
package org.jetbrains.jps.incremental.scala.model.impl

import org.jetbrains.jps.incremental.scala.model.JpsSbtModuleExtension
import org.jetbrains.jps.model.ex.{JpsElementBase, JpsElementChildRoleBase}
import org.jetbrains.jps.model.{JpsElement, JpsElementChildRole}

final class JpsSbtModuleExtensionImpl extends JpsElementBase[JpsSbtModuleExtensionImpl] with JpsSbtModuleExtension {
  override def createCopy(): JpsSbtModuleExtensionImpl = new JpsSbtModuleExtensionImpl

  override def applyChanges(modified: JpsSbtModuleExtensionImpl): Unit = {}
}

object JpsSbtModuleExtensionImpl {
  val Role: JpsElementChildRole[JpsSbtModuleExtension] = JpsElementChildRoleBase.create("sbt")
}


text:
module MonkeyParty
  module Attendee
    class Field
      attr_reader :name, :columns, :merge_field

      def initialize(*args)
        @name = args.first

        options = args.extract_options!

        @merge_field = options[:merge_field] || @name
        @columns = []
        @columns << @name.to_s
      end
    end
  end
end


text:
package com.github.particlesystem.modifiers;

import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;

import com.github.particlesystem.Particle;

public class ScaleModifier implements ParticleModifier {

    private float mInitialValue;
    private float mFinalValue;
    private long mEndTime;
    private long mStartTime;
    private long mDuration;
    private float mValueIncrement;
    private Interpolator mInterpolator;

    public ScaleModifier(float initialValue, float finalValue, long startMilis, long endMilis, Interpolator interpolator) {
        mInitialValue = initialValue;
        mFinalValue = finalValue;
        mStartTime = startMilis;
        mEndTime = endMilis;
        mDuration = mEndTime - mStartTime;
        mValueIncrement = mFinalValue - mInitialValue;
        mInterpolator = interpolator;
    }

    public ScaleModifier(float initialValue, float finalValue, long startMilis, long endMilis) {
        this(initialValue, finalValue, startMilis, endMilis, new LinearInterpolator());
    }

    @Override
    public void apply(Particle particle, long miliseconds) {
        if (miliseconds < mStartTime) {
            particle.mScale = mInitialValue;
        } else if (miliseconds > mEndTime) {
            particle.mScale = mFinalValue;
        } else {
            float interpolaterdValue = mInterpolator.getInterpolation((miliseconds - mStartTime) * 1f / mDuration);
            float newScale = mInitialValue + mValueIncrement * interpolaterdValue;
            particle.mScale = newScale;
        }
    }

}


text:
package com.encryptlang.v0.node;

import com.encryptlang.v0.statement.Statement;

/**
 * Created by jianjunwei on 2017/7/5.
 */
public class FunctionCallStatement implements Statement {
}


text:
function varargout = vc_cmf_BasicStatistics(varargin)
% Usages:
%
% GUI MODE
% [vcdb, status, scalar_features, vector_features, sf_names, vf_names, sf_param, vfparam] = vc_cmf_*(vcdb);
%       vcdb: the augmented vcdb.
%       status: string is empty if compute successful, otherwise status is an error message.
%       v: vectors
%       sf: scalar features
%       vf: vector features
%       sf_names: names of scalar features
%       vf_names: names of vector features.
%       sf_params: params used to compute scalar features
%       vf_params: params used to compute vector features.
%
% PARAMETER QUERY MODE
% parameters = vc_cmf_BasicStatistics('parameters')
%   returns structure containing a name field.
%
% BATCH MODE
% [vcdb, status, v, sf, vf, sfn, vfn, sfp, vfp] = vc_cmf_BasicStatistics('batch', vectorNdx)
%       vectorNdx: specified with vector/vector feature to compute stats
%       on.  0 (default) specified vcdb.v, other vectorNdx is the ndx of
%       the vector feature to be used.

% VC_CMF_BASICSTATISTICS M-file for vc_cmf_BasicStatistics.fig
%      VC_CMF_BASICSTATISTICS by itself, creates a new VC_CMF_BASICSTATISTICS or raises the
%      existing singleton*.
%
%      H = VC_CMF_BASICSTATISTICS returns the handle to a new VC_CMF_BASICSTATISTICS or the handle to
%      the existing singleton*.
%
%      VC_CMF_BASICSTATISTICS('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in VC_CMF_BASICSTATISTICS.M with the given input arguments.
%
%      VC_CMF_BASICSTATISTICS('Property','Value',...) creates a new VC_CMF_BASICSTATISTICS or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before vc_cmf_BasicStatistics_OpeningFunction gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to vc_cmf_BasicStatistics_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help vc_cmf_BasicStatistics

% Last Modified by GUIDE v2.5 16-May-2008 14:46:01

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @vc_cmf_BasicStatistics_OpeningFcn, ...
                   'gui_OutputFcn',  @vc_cmf_BasicStatistics_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT

% --- Executes just before vc_cmf_BasicStatistics is made visible.
function vc_cmf_BasicStatistics_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to vc_cmf_BasicStatistics (see VARARGIN)

% Become true if data successfully imported.

%If handles.output is '' then return nother, operation cancelled.
%If handles.output is 'success' then features sucessfully computed.
%if handles.output is 'params', then return function parameters.
%If handles.output is another string, then an error occurred.

handles.output = '';
if(~isempty(varargin) && strcmpi(varargin{1},'parameters'))
    handles.output = 'params';
else
    handles.vcdb = varargin{1};
end
set(handles.popupVector, 'String', [{'vectors'}; handles.vcdb.f.vfname]);
set(handles.popupVector, 'Value', 1);

% Update handles structure
guidata(hObject, handles);

% Determine the position of the dialog - centered on the callback figure
% if available, else, centered on the screen
FigPos=get(0,'DefaultFigurePosition');
OldUnits = get(hObject, 'Units');
set(hObject, 'Units', 'pixels');
OldPos = get(hObject,'Position');
FigWidth = OldPos(3);
FigHeight = OldPos(4);
if isempty(gcbf)
    ScreenUnits=get(0,'Units');
    set(0,'Units','pixels');
    ScreenSize=get(0,'ScreenSize');
    set(0,'Units',ScreenUnits);

    FigPos(1)=1/2*(ScreenSize(3)-FigWidth);
    FigPos(2)=2/3*(ScreenSize(4)-FigHeight);
else
    GCBFOldUnits = get(gcbf,'Units');
    set(gcbf,'Units','pixels');
    GCBFPos = get(gcbf,'Position');
    set(gcbf,'Units',GCBFOldUnits);
    FigPos(1:2) = [(GCBFPos(1) + GCBFPos(3) / 2) - FigWidth / 2, ...
                   (GCBFPos(2) + GCBFPos(4) / 2) - FigHeight / 2];
end
FigPos(3:4)=[FigWidth FigHeight];
set(hObject, 'Position', FigPos);
set(hObject, 'Units', OldUnits);

% Make the GUI modal
set(handles.figure1,'WindowStyle','modal')

% UIWAIT makes vc_imp_ProcessedAnnotationFiles wait for user response (see UIRESUME)
if(~strcmpi(handles.output,'params') || (length(varargin)==1))
    uiwait(handles.figure1);
else
    set(handles.figure1,'Visible','off');
end

if(length(varargin)>1)
    vectorNdx = varargin{2};
    handles = compute(handles, vectorNdx); % main function
    guidata(hObject, handles);
end

% --- Outputs from this function are returned to the command line.
function varargout = vc_cmf_BasicStatistics_OutputFcn(hObject, eventdata, handles)
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

if(strcmpi(handles.output,'')) %Canceled
    if(nargout>0), varargout{1} = handles.vcdb; end
    if(nargout>1), varargout{2} = ''; end
    for nOut = 3:nargout
        varargout{nOut} = [];
    end
elseif(strcmpi(handles.output,'params'))
    params.name = 'Matlab Workspace Variable';
    if(nargout>0), varargout{1} = params; end
elseif(strcmpi(handles.output,'success'))
    handles.vcdb.d.sf = [handles.vcdb.d.sf, handles.sf];
    handles.vcdb.d.vf = [handles.vcdb.d.vf, handles.vf];
    handles.vcdb.f.sfname = [handles.vcdb.f.sfname; handles.sfname];
    handles.vcdb.f.sffcn = [handles.vcdb.f.sffcn; handles.sffcn];
    handles.vcdb.f.sfparam = [handles.vcdb.f.sfparam; handles.sfparam];
    handles.vcdb.f.vfname = [handles.vcdb.f.vfname; handles.vfname];
    handles.vcdb.f.vffcn = [handles.vcdb.f.vffcn; handles.vffcn];
    handles.vcdb.f.vfparam = [handles.vcdb.f.vfparam; handles.vfparam];
    if(nargout>0), varargout{1} = handles.vcdb; end
    if(nargout>1), varargout{2} = 'success'; end
    if(nargout>2), varargout{3} = handles.sf; end
    if(nargout>3), varargout{4} = handles.vf; end
    if(nargout>4), varargout{5} = handles.sfname; end
    if(nargout>5), varargout{6} = handles.vfname; end
    if(nargout>6), varargout{7} = handles.sfparam; end
    if(nargout>7), varargout{8} = handles.vfparam; end
else
    if(nargout>0), varargout{1} = handles.vcdb; end
    if(nargout>1), varargout{2} = handles.output; end
    for nOut = 3:nargout
        varargout{nOut} = [];
    end
end

% The figure can be deleted now
delete(handles.figure1);

% --- Executes when user attempts to close figure1.
function figure1_CloseRequestFcn(hObject, eventdata, handles)
% hObject    handle to figure1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

if isequal(get(handles.figure1, 'waitstatus'), 'waiting')
    % The GUI is still in UIWAIT, us UIRESUME
    uiresume(handles.figure1);
else
    % The GUI is no longer waiting, just close it
    delete(handles.figure1);
end

% --- Executes on key press over figure1 with no controls selected.
function figure1_KeyPressFcn(hObject, eventdata, handles)
% hObject    handle to figure1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Check for "enter" or "escape"
if isequal(get(hObject,'CurrentKey'),'escape')
    uiresume(handles.figure1);
end

% --- Executes on button press in buttonCompute.
function buttonCompute_Callback(hObject, eventdata, handles)
% hObject    handle to buttonCompute (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
vectorNdx = get(handles.popupVector, 'Value');
vectorNdx = vectorNdx-1;
%vectorNdx of 0 specified the original vectors,
%otherwise vectorNdx is the index of the desired vector-feature.
handles = compute(handles, vectorNdx);
guidata(hObject, handles);

% Use UIRESUME instead of delete because the OutputFcn needs
% to get the updated handles structure.
uiresume(handles.figure1);

% --- Executes on button press in buttonCancel.
function buttonCancel_Callback(hObject, eventdata, handles)
% hObject    handle to buttonCancel (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Use UIRESUME instead of delete because the OutputFcn needs
% to get the updated handles structure.
uiresume(handles.figure1);

% --- Executes on selection change in popupVector.
function popupVector_Callback(hObject, eventdata, handles)
% hObject    handle to popupVector (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = get(hObject,'String') returns popupVector contents as cell array
%        contents{get(hObject,'Value')} returns selected item from popupVector

% --- Executes during object creation, after setting all properties.
function popupVector_CreateFcn(hObject, eventdata, handles)
% hObject    handle to popupVector (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- imports
function handles = compute(handles, vectorNdx)
try
    if(vectorNdx == 0)
        vects = handles.vcdb.d.v;
        vname = 'vector';
    else
        vects = handles.vcdb.d.vf{vectorNdx};
        vname = handles.vcdb.f.vfname{vectorNdx};
    end

    handles.sf = cellfun(@mean,vects); % apply function to all the cells in the cell array
    handles.sfname{1,1} = ['mean_',vname];
    handles.sffcn{1,1} = 'vc_cmf_basicStatitics';
    handles.sfparam{1,1} = [];

    handles.sf(:,2) = cellfun(@std,vects);
    handles.sfname{2,1} = ['std_',vname];
    handles.sffcn{2,1} = 'vc_cmf_basicStatitics';
    handles.sfparam{2,1} = [];

    handles.sf(:,3) = cellfun(@max,vects);
    handles.sfname{3,1} = ['max_',vname];
    handles.sffcn{3,1} = 'vc_cmf_basicStatitics';
    handles.sfparam{3,1} = [];

    handles.vf = {};
    handles.vfname = {};
    handles.vffcn = {};
    handles.vfparam = {};

    handles.output = 'success';
catch
    handles.output = ['Compute basic statistic failed: ', lasterr];
end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>GroupInfo (android API)</title>
<meta name="date" content="2017-10-19">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

cn.jpush.im.android.api.model

Class GroupInfo

java.lang.Object

cn.jpush.im.android.api.model.GroupInfo

public abstract class GroupInfo
extends java.lang.Object

Constructor Summary

Constructors

Constructor and Description

GroupInfo()

Method Summary

All Methods Instance Methods Abstract Methods Concrete Methods Deprecated Methods

Modifier and Type
Method and Description

java.lang.String
getAvatar()

获取群头像的mediaID

abstract void
getAvatarBitmap(GetAvatarBitmapCallback callback)

从本地获取群组头像的缩略图bitmap,如果本地存在头像缩略图文件,直接返回;若不存在,会异步从服务器拉取。
 下载完成后 会将头像保存至本地并返回。当群组未设置头像,或者下载失败时回调返回Null。

 所有的缩略头像bitmap在sdk内都会缓存,
 并且会有清理机制,所以上层不需要对缩略头像bitmap做缓存。

abstract java.io.File
getAvatarFile()

从本地获取群头像缩略图文件,头像缩略图会在调用JMessageClient.getGroupInfo(long, GetGroupInfoCallback)
 时自动下载。当此群未设置头像,或者自动下载失败时此接口返回Null。

abstract void
getBigAvatarBitmap(GetAvatarBitmapCallback callback)

从本地获取群组头像的原图bitmap,如果本地存在头像原图文件,直接返回;若不存在,会异步从服务器拉取。
 下载完成后 会将头像保存至本地并返回。当群组未设置头像,或者下载失败时回调返回Null。

 注意:在调用updateAvatar(File, String, BasicCallback) 上传头像时,若
 上传的头像未经压缩处理,调此接口则有可能出现OOM

abstract java.io.File
getBigAvatarFile()

从本地获取群组头像原图文件,当群组未设置头像,或者本地不存在头像原图文件时此接口返回Null。

java.lang.String
getGroupDescription()

获取群组描述信息

int
getGroupFlag()

long
getGroupID()

获取群组id

int
getGroupLevel()

abstract UserInfo
getGroupMemberInfo(java.lang.String username)

Deprecated.

deprecated in jmessage 1.3.0 use getGroupMemberInfo(String, String) instead.

abstract UserInfo
getGroupMemberInfo(java.lang.String username,
                  java.lang.String appKey)

根据appKey跨应用获取单个群成员UserInfo

abstract java.util.List<UserInfo>
getGroupMembers()

获取群成员userinfo列表。

java.lang.String
getGroupName()

获取群组名称

abstract java.lang.String
getGroupOwner()

获取群主的username

int
getMaxMemberCount()

获取群成员数的最大上限

abstract int
getNoDisturb()

群组是否在免打扰名单中

abstract java.lang.String
getOwnerAppkey()

获取群主所属appkey

abstract int
isGroupBlocked()

群组是否在被屏蔽的名单中

abstract void
setBlockGroupMessage(int blocked,
                    BasicCallback callback)

设置屏蔽群消息,设置后将不会再收到此群的消息

abstract void
setNoDisturb(int noDisturb,
            BasicCallback callback)

将此群组设置为免打扰。设置之后收到此群消息时将不会在通知栏展示通知

abstract void
updateAvatar(java.io.File avatar,
            java.lang.String format,
            BasicCallback callback)

更新群组头像,建议用户在上传头像前先对头像先进行压缩,否则在调用getBigAvatarBitmap(GetAvatarBitmapCallback)
 接口拿头像的原图时,有可能会抛出OOM异常。

abstract void
updateDescription(java.lang.String groupDesc,
                 BasicCallback callback)

修改群组描述,新的描述不允许为空

abstract void
updateName(java.lang.String groupName,
          BasicCallback callback)

修改群组名称,新的群名称不允许为空

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

GroupInfo

public GroupInfo()

Method Detail

getGroupID

public long getGroupID()

获取群组id

Returns:

getGroupName

public java.lang.String getGroupName()

获取群组名称

Returns:

getGroupDescription

public java.lang.String getGroupDescription()

获取群组描述信息

Returns:

getGroupLevel

public int getGroupLevel()

getGroupFlag

public int getGroupFlag()

getNoDisturb

public abstract int getNoDisturb()

群组是否在免打扰名单中

Returns:

1表示存在,0表示不存在

getGroupOwner

public abstract java.lang.String getGroupOwner()

获取群主的username

Returns:

getOwnerAppkey

public abstract java.lang.String getOwnerAppkey()

获取群主所属appkey

Since:

1.4.0

getGroupMembers

public abstract java.util.List<UserInfo> getGroupMembers()

获取群成员userinfo列表。

Returns:

getGroupMemberInfo

@Deprecated
public abstract UserInfo getGroupMemberInfo(java.lang.String username)

Deprecated. deprecated in jmessage 1.3.0 use getGroupMemberInfo(String, String) instead.

获取单个群成员Userinfo,默认获取本应用appkey下用户信息,如果需要获取跨应用
 下其他用户的用户信息,请使用getGroupMemberInfo(String, String)

Parameters:

username - 指定群成员的username

Returns:

指定username的用户信息,如果本地未找到则返回null

getGroupMemberInfo

public abstract UserInfo getGroupMemberInfo(java.lang.String username,
                                            java.lang.String appKey)

根据appKey跨应用获取单个群成员UserInfo

Parameters:

username - 指定群成员的username

appKey - 群成员所属的appKey

Returns:

指定username的用户信息,如果本地未找到则返回null

getMaxMemberCount

public int getMaxMemberCount()

获取群成员数的最大上限

Returns:

群成员数上限

setNoDisturb

public abstract void setNoDisturb(int noDisturb,
                                  BasicCallback callback)

将此群组设置为免打扰。设置之后收到此群消息时将不会在通知栏展示通知

Parameters:

noDisturb - 1 -- 免打扰,其他 -- 非免打扰

callback - 回调接口

setBlockGroupMessage

public abstract void setBlockGroupMessage(int blocked,
                                          BasicCallback callback)

设置屏蔽群消息,设置后将不会再收到此群的消息

Parameters:

blocked - 1 -- 设置屏蔽; 其他(int) -- 取消屏蔽

callback - 回调接口

Since:

2.1.0

isGroupBlocked

public abstract int isGroupBlocked()

群组是否在被屏蔽的名单中

Returns:

1 -- 存在; 0 -- 不存在

Since:

2.1.0

getAvatar

public java.lang.String getAvatar()

获取群头像的mediaID

Returns:

用户头像的mediaID,若未设置头像则返回null

Since:

2.3.0

getAvatarFile

public abstract java.io.File getAvatarFile()

从本地获取群头像缩略图文件,头像缩略图会在调用JMessageClient.getGroupInfo(long, GetGroupInfoCallback)
 时自动下载。当此群未设置头像,或者自动下载失败时此接口返回Null。

Returns:

群组缩略头像文件对象,若未设置头像或者未下载完成则返回null

Since:

2.3.0

getAvatarBitmap

public abstract void getAvatarBitmap(GetAvatarBitmapCallback callback)

从本地获取群组头像的缩略图bitmap,如果本地存在头像缩略图文件,直接返回;若不存在,会异步从服务器拉取。
 下载完成后 会将头像保存至本地并返回。当群组未设置头像,或者下载失败时回调返回Null。

 所有的缩略头像bitmap在sdk内都会缓存,
 并且会有清理机制,所以上层不需要对缩略头像bitmap做缓存。

Since:

2.3.0

getBigAvatarFile

public abstract java.io.File getBigAvatarFile()

从本地获取群组头像原图文件,当群组未设置头像,或者本地不存在头像原图文件时此接口返回Null。

Returns:

群组头像原图文件对象,若未设置头像或者本地不存在头像原图文件则返回null

Since:

2.3.0

getBigAvatarBitmap

public abstract void getBigAvatarBitmap(GetAvatarBitmapCallback callback)

从本地获取群组头像的原图bitmap,如果本地存在头像原图文件,直接返回;若不存在,会异步从服务器拉取。
 下载完成后 会将头像保存至本地并返回。当群组未设置头像,或者下载失败时回调返回Null。

 注意:在调用updateAvatar(File, String, BasicCallback) 上传头像时,若
 上传的头像未经压缩处理,调此接口则有可能出现OOM

Since:

2.3.0

updateAvatar

public abstract void updateAvatar(java.io.File avatar,
                                  java.lang.String format,
                                  BasicCallback callback)

更新群组头像,建议用户在上传头像前先对头像先进行压缩,否则在调用getBigAvatarBitmap(GetAvatarBitmapCallback)
 接口拿头像的原图时,有可能会抛出OOM异常。

 此接口可以指定头像文件在后台存储时的扩展名,如果填空或者不填,则后台存储文件时将没有扩展名。

Parameters:

avatar - 头像文件

format - 文件扩展名,注意名称中不要包括"."

callback - 回调对象

Since:

2.3.0

updateName

public abstract void updateName(java.lang.String groupName,
                                BasicCallback callback)

修改群组名称,新的群名称不允许为空

Parameters:

groupName - 群名称

callback - 回调接口

Since:

2.3.0

updateDescription

public abstract void updateDescription(java.lang.String groupDesc,
                                       BasicCallback callback)

修改群组描述,新的描述不允许为空

Parameters:

groupDesc - 群组描述

callback - 回调接口

Since:

2.3.0

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
#include "runtime/north/cc_common.h"

struct cc_calvinsys_obj_t;
struct cc_node_t;
struct cc_transport_client_t;
typedef int wint_t;
cc_result_t cc_calvinsys_temp_sensor_open(struct cc_calvinsys_obj_t *obj, cc_list_t *kwargs);
struct cc_transport_client_t *cc_transport_spritzer_create(struct cc_node_t *node, char *uri);

#define CC_USE_STORAGE (1)
#define CC_PYTHON_FLOATS (0)
#define CC_ACTOR_MODULES_DIR "/mnt/spif/mpys/"
#define CC_STATE_FILE "/mnt/spif/calvin.msgpack"

#define CC_CAPABILITIES \
	{ "io.temperature", cc_calvinsys_temp_sensor_open, NULL, NULL, NULL, false }

#define CC_TRANSPORTS \
	{ "calvinip", cc_transport_spritzer_create }


text:
package com.twitter.ambrose.model.hadoop;

import com.fasterxml.jackson.annotation.JsonCreator;
import org.apache.hadoop.mapred.RunningJob;
import org.apache.hadoop.mapred.TaskReport;

import java.io.IOException;

/**
 * Container that holds state of a MapReduce job
 */
public class MapReduceJobState {
  private String jobId;
  private String jobName;
  private String trackingURL;
  private boolean isComplete;
  private boolean isSuccessful;
  private float mapProgress;
  private float reduceProgress;
  private int totalMappers;
  private int totalReducers;

  @JsonCreator
  public MapReduceJobState() { }

  @SuppressWarnings("deprecation")
  public MapReduceJobState(RunningJob runningJob,
                           TaskReport[] mapTaskReport,
                           TaskReport[] reduceTaskReport) throws IOException {
    jobId = runningJob.getID().toString();
    jobName = runningJob.getJobName();
    trackingURL = runningJob.getTrackingURL();
    isComplete = runningJob.isComplete();
    isSuccessful = runningJob.isSuccessful();
    mapProgress = runningJob.mapProgress();
    reduceProgress = runningJob.reduceProgress();
    totalMappers = mapTaskReport.length;
    totalReducers = reduceTaskReport.length;
  }

  public String getJobId() {
    return jobId;
  }

  public void setJobId(String jobId) {
    this.jobId = jobId;
  }

  public String getJobName() {
    return jobName;
  }

  public void setJobName(String jobName) {
    this.jobName = jobName;
  }

  public String getTrackingURL() {
    return trackingURL;
  }

  public void setTrackingURL(String trackingURL) {
    this.trackingURL = trackingURL;
  }

  public boolean isComplete() {
    return isComplete;
  }

  public void setComplete(boolean complete) {
    isComplete = complete;
  }

  public boolean isSuccessful() {
    return isSuccessful;
  }

  public void setSuccessful(boolean successful) {
    isSuccessful = successful;
  }

  public float getMapProgress() {
    return mapProgress;
  }

  public void setMapProgress(float mapProgress) {
    this.mapProgress = mapProgress;
  }

  public float getReduceProgress() {
    return reduceProgress;
  }

  public void setReduceProgress(float reduceProgress) {
    this.reduceProgress = reduceProgress;
  }

  public int getTotalMappers() {
    return totalMappers;
  }

  public void setTotalMappers(int totalMappers) {
    this.totalMappers = totalMappers;
  }

  public int getTotalReducers() {
    return totalReducers;
  }

  public void setTotalReducers(int totalReducers) {
    this.totalReducers = totalReducers;
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

    Copyright © 2013-2021 The OpenNTF Domino API Team

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

-->
<site>
   <description name="OpenNTF Domino API">
      OpenNTF Domino API
   </description>
   <feature id="org.openntf.domino.nonxsp.feature">
      <category name="OpenNTF Domino API"/>
   </feature>
   <feature id="org.openntf.domino.nonxsp.feature.source">
      <category name="OpenNTF Domino API"/>
   </feature>
   <feature id="org.openntf.domino.dependencies.feature">
      <category name="OpenNTF Domino API"/>
   </feature>
   <feature id="org.openntf.domino.dependencies.feature.source">
      <category name="OpenNTF Domino API"/>
   </feature>
   <category-def name="OpenNTF Domino API" label="OpenNTF Domino API"/>
</site>