text:
//=====================================================================
// Copyright 2016 (c), Advanced Micro Devices, Inc. All rights reserved.
//
/// \author AMD Developer Tools Team
/// \file osThread.cpp
///
//=====================================================================

//------------------------------ osThread.cpp ------------------------------
#include <time.h>

// Infra:
#include <amdt_base_tools/Include/gtAssert.h>
#include <amdt_base_tools/Include/AMDTDefinitions.h>

// On Mac OS X:
#ifdef __APPLE__
    // Mach kernel:
    #include <mach/mach_init.h>
#endif

// POSIX:
#include <signal.h>
#include <pthread.h>
#include <sys/errno.h>
#include <sys/select.h>
#include <sys/syscall.h>
#include <unistd.h>
#include <dirent.h>

// Local:
#include <amdt_os_wrappers/Include/osStringConstants.h>
#include <amdt_os_wrappers/Include/osDebugLog.h>
#include <amdt_os_wrappers/Include/osTime.h>
#include <amdt_os_wrappers/Include/osStopWatch.h>
#include <amdt_os_wrappers/Include/osThread.h>
#include <amdt_os_wrappers/Include/osTimeInterval.h>

// ---------------------------------------------------------------------------
// Name:        osThread::osThread
// Description: Constructor.
// Author:      AMD Developer Tools Team
// Date:        9/11/2006
// ---------------------------------------------------------------------------
osThread::osThread(const gtString& threadName, bool syncTermination, bool isJoinable)
    : _threadName(threadName)
    , _threadId(OS_NO_THREAD_ID)
    , _threadHandle(OS_NO_THREAD_HANDLE)
    , _wasThreadTerminated(false)
    , m_syncTermination(syncTermination)
    , m_isJoinable(isJoinable)
{
}

// ---------------------------------------------------------------------------
// Name:        osThread::~osThread
// Description: Destructor - Terminate the wrapped OS thread.
// Author:      AMD Developer Tools Team
// Date:        9/11/2006
// ---------------------------------------------------------------------------
osThread::~osThread()
{
    terminate();
}

// ---------------------------------------------------------------------------
// Name:        osThread::threadEntryPoint
//
// Description: The POSIX thread entry point.
//              Calls osThread::entryPoint() of the osThread object that represents
//              the POSIX thread.
//
// Arguments:   pParam - A pointer to the osThread object that represents
//                       the OS thread (casted into void*).
//
// Author:      AMD Developer Tools Team
// Date:        9/11/2006
// ---------------------------------------------------------------------------
void* osThread::threadEntryPoint(void* pParam)
{
    // Log the fact that the thread run started into the debug log:
    osThreadId currentThreadId = osGetCurrentThreadId();
    osThread* pThreadWrapper = (osThread*)pParam;
    osThread::debugLogThreadRunStarted(currentThreadId, pThreadWrapper->_threadName);

    // Get the osThread object that represents the OS thread:
    GT_IF_WITH_ASSERT(pThreadWrapper != NULL)
    {
        // Call its osThread::entryPoint() function:
        pThreadWrapper->entryPoint();

        // Enter the thread termination critical section:
        osCriticalSectionLocker csLocker(pThreadWrapper->_threadTerminationCS);

        // If the thread was not already terminated:
        if (!pThreadWrapper->_wasThreadTerminated)
        {
            // Allow "before termination" clean ups of the thread wrapper class instance:
            pThreadWrapper->beforeTermination();

            // Mark that the thread was terminated:
            pThreadWrapper->_wasThreadTerminated = true;
        }

        // Leave the thread termination critical section:
        csLocker.leaveCriticalSection();
    }

    return NULL;
}

// ---------------------------------------------------------------------------
// Name:        osThread::execute
// Description: Starts executing this thread.
//              The thread execution start function will be the entryPoint()
//              function. Sub classes must implement the entryPoint() function.
// Return Val:  bool - Success / failure.
// Author:      AMD Developer Tools Team
// Date:        9/11/2006
// Implementation notes:
//   On Mac OS X we mainly use pthreads. However, since pthread_t on Mac is a pointer to a struct,
//   we prefer using the Mach kernel thread id as our thread id. We store the thread's pthread id as
//   the thread handle.
// ---------------------------------------------------------------------------
bool osThread::execute()
{
    bool retVal = false;

    // Clear class members:
    _wasThreadTerminated = false;

    // Create a thread's attribute structure:
    pthread_attr_t threadAttributes;
    pthread_attr_init(&threadAttributes);

    int rc1 = 0;

    if (false == m_isJoinable)
    {
        // Make the thread a "detached" thread:
        // Yaki - 24/9/2009 - By default, Linux creates "joinable" thread. If the program does not wait for a joinable thread's returned value,
        // it creates quite a big OS resources leak (on Red Hat Enterprize 5 x86_64, we got a leak of ~10 MB per thread). Since we
        // currrently don't offer an API for waiting for or joining threads, we create all threads as "detached" thread. This saves us
        // from this memory leak that caused our license server's memory to inflate. See case 5810 for more details on this issue.
        rc1 = pthread_attr_setdetachstate(&threadAttributes, PTHREAD_CREATE_DETACHED);
    }

    GT_IF_WITH_ASSERT(rc1 == 0)
    {
        // Create the OS thread and store the thread's pthread id as the thread's handle:
        int rc2 = ::pthread_create(&_threadHandle, &threadAttributes, threadEntryPoint, (void*)this);
        GT_IF_WITH_ASSERT(rc2 == 0)
        {
            // On Mac OS X:
#ifdef __APPLE__
            {
                // Get the thread's mach thread id and store it as the thread's id:
                // (See above implementation note)
                _threadId = pthread_mach_thread_np(_threadHandle);
            }
#else
            {
                _threadId = _threadHandle;
            }
#endif

            // Log the thread creation into the debug log file:
            debugLogCreatedThread(_threadId, _threadName);

            retVal = true;
        }

        // Clean up:
        int rc3 = pthread_attr_destroy(&threadAttributes);
        GT_ASSERT(rc3 == 0);
    }

    return retVal;
}

// ---------------------------------------------------------------------------
// Name:        osThread::breakExecution
// Description: Suspends the execution of this thread.
//
//              USE THIS FUNCTION WITH CARE !!!!!
//              (Suspending a thread that owns a synchronization object (mutex /
//               critical section / etc) can lead to a deadlock !!!
//
// Return Val:  bool - Success / failure.
// Author:      AMD Developer Tools Team
// Date:        9/11/2006
// ---------------------------------------------------------------------------
bool osThread::breakExecution()
{
    bool retVal = false;

    // Yaki 11/9/2008:
    // pthreads can be suspended using pthread_cond_wait or similar condition function from
    // within the thread itself. However, as far as we know, POSIX does not offer functions
    // that enable suspending and resuming a thread from within another thread.
    // (HP-UX and Solar offer pthread_suspend() and pthread_continue(), but Linux does not seem to offer
    //  these functions)
    GT_ASSERT(false);

    return retVal;
}

// ---------------------------------------------------------------------------
// Name:        osThread::resumeExecution
// Description:
//   Increments the thread suspend count.
//   If the suspend count reach 0 - The thread run is resumed.
// Return Val:  bool - Success / failure.
// Author:      AMD Developer Tools Team
// Date:        9/11/2006
// ---------------------------------------------------------------------------
bool osThread::resumeExecution()
{
    bool retVal = false;

    // Yaki 11/9/2008:
    // pthreads can be suspended using pthread_cond_wait or similar condition function from
    // within the thread itself. However, as far as we know, POSIX does not offer functions
    // that enable suspending and resuming a thread from within another thread.
    // (HP-UX and Solar offer pthread_suspend() and pthread_continue(), but Linux does not seem to offer
    //  these functions)
    GT_ASSERT(false);

    return retVal;
}

// ---------------------------------------------------------------------------
// Name:        osThread::terminate
// Description: Terminates the OS thread.
// Return Val:  bool - Success / failure.
// Author:      AMD Developer Tools Team
// Date:        9/11/2006
// ---------------------------------------------------------------------------
bool osThread::terminate()
{
    bool retVal = false;

    // Enter the thread termination critical section:
    osCriticalSectionLocker csLocker(_threadTerminationCS);

    // If the thread is not alive:
    bool isThreadAlive = isAlive();

    if (!isThreadAlive)
    {
        // Nothing to be done:
        retVal = true;
    }
    else
    {
        // Issue "before termination" clean ups:
        beforeTermination();

        // Try to terminate the OS thread:
        int rc = ::pthread_cancel(_threadHandle);

        // if sync terminate wait until thread is not alive:
        if (m_syncTermination)
        {
            while (isAlive());
        }

        // If we managed to terminate the thread, or the thread was
        // already terminated:
        GT_IF_WITH_ASSERT((rc == 0) || (rc == ESRCH))
        {
            retVal = true;
        }
    }

    // Mark that the thread was terminated:
    _wasThreadTerminated = true;

    // Leave the thread termination critical section:
    csLocker.leaveCriticalSection();

    return retVal;
}

// ---------------------------------------------------------------------------
// Name:        osThread::isAlive
// Description: Returns true iff the thread is alive (it was executed and its
//              run was not ended).
// Author:      AMD Developer Tools Team
// Date:        9/11/2006
// ---------------------------------------------------------------------------
bool osThread::isAlive() const
{
    bool retVal = false;

    // If the thread was not terminated:
    if (!_wasThreadTerminated)
    {
        // If this thread has no handle, it surely isn't running:
        if (_threadHandle != OS_NO_THREAD_HANDLE)
        {
            // We send a dummy ("0") signal to the thread. If the function fails, the thread
            // is dead. If not, it's alive.
            // This is probably the best way to test this, though it could report a false
            // positive if the thread ID was reused...
            int retCode = ::pthread_kill(_threadHandle, 0);
            retVal = (retCode == 0);
        }
    }

    return retVal;
}

// ---------------------------------------------------------------------------
// Name:        osThread::entryPoint
// Description:
//   The thread entry point.
//   Should be overridden by sub-classes that would like the thread to execute their code.
//
// Return Val:  int - The thread return value.
// Author:      AMD Developer Tools Team
// Date:        9/11/2006
// ---------------------------------------------------------------------------
int osThread::entryPoint()
{
    return 0;
}

// ---------------------------------------------------------------------------
// Name:        osThread::beforeTermination
// Description: Is called before the thread is terminated. Enables sub classes
//              to clean up before the thread exits. (Sub classes can override this method).
//              NOTICE: (Sigal 23/8/10) Do not perform 'delete this' in this function overrides,
//              since we use the class members after the call to 'beforeTermination'
//              in the thread entry point
// Return Val:  bool - Success / failure.
// Author:      AMD Developer Tools Team
// Date:        9/11/2006
// ---------------------------------------------------------------------------
void osThread::beforeTermination()
{
}

// ---------------------------------------------------------------------------
// Name:        osThread::debugLogCreatedThread
// Description: Log the thread creation into the debug log file.
// Arguments: createdThreadId - The created thread id.
// Author:      AMD Developer Tools Team
// Date:        5/5/2009
// ---------------------------------------------------------------------------
void osThread::debugLogCreatedThread(osThreadId createdThreadId, const gtString& threadName)
{
    // If we are in "debug" log severity:
    if (OS_DEBUG_LOG_DEBUG <= osDebugLog::instance().loggedSeverity())
    {
        // Translate it into a string:
        gtString createdThreadIdAsStr;
        osThreadIdAsString(createdThreadId, createdThreadIdAsStr);

        // Output the created thread id to the debug log file:
        gtString dbgStr;
        dbgStr.appendFormattedString(OS_STR_OSThreadWasCreated, threadName.asCharArray());

        if (createdThreadId != OS_NO_THREAD_ID)
        {
            dbgStr += createdThreadIdAsStr;
        }
        else
        {
            dbgStr += L"N/A";
        }

        OS_OUTPUT_DEBUG_LOG(dbgStr.asCharArray(), OS_DEBUG_LOG_DEBUG);
    }
}

// ---------------------------------------------------------------------------
// Name:        osThread::debugLogThreadRunStarted
// Description: Log the fact that the thread run started into the debug log.
// Arguments: threadId - The id of the thread that just started running.
// Author:      AMD Developer Tools Team
// Date:        5/5/2009
// ---------------------------------------------------------------------------
void osThread::debugLogThreadRunStarted(osThreadId threadId, const gtString& threadName)
{
    // If we are in "debug" log severity:
    if (OS_DEBUG_LOG_DEBUG <= osDebugLog::instance().loggedSeverity())
    {
        // Translate the thread id into a string:
        gtString threadIdAsStr;
        osThreadIdAsString(threadId, threadIdAsStr);

        // Output the thread id to the debug log file:
        gtString dbgStr;
        dbgStr.appendFormattedString(OS_STR_OSThreadRunStarted, threadName.asCharArray());
        dbgStr += threadIdAsStr;
        OS_OUTPUT_DEBUG_LOG(dbgStr.asCharArray(), OS_DEBUG_LOG_DEBUG);
    }
}

#ifndef __APPLE__
// ---------------------------------------------------------------------------
// Name:        osThread::waitForThreadEnd
// Description: Wait for the thread to end or until the timeout expires.
//              Returns true if thread ended in time. Returns false if timeout
//              was reached before the thread ended
// Arguments: maxTimeToWait - The length of the timeout
// Author:      AMD Developer Tools Team
// Date:        1/27/2016
// ---------------------------------------------------------------------------
bool osThread::waitForThreadEnd(const osTimeInterval& maxTimeToWait)
{
    bool isThreadEndedInTime = false;

    if (m_isJoinable)
    {
        struct timespec tsTimeout;
        int rc = 0;

        if (clock_gettime(CLOCK_REALTIME, &tsTimeout) == -1)
        {
            /* Handle error */
        }

        gtUInt64 seconds, nanoseconds;
        maxTimeToWait.getAsWholeSecondsAndRemainder(seconds, nanoseconds);

        tsTimeout.tv_sec += seconds;
        tsTimeout.tv_nsec += nanoseconds;

        rc = pthread_timedjoin_np(_threadHandle, NULL, &tsTimeout);

        if (0 == rc)
        {
            isThreadEndedInTime = true;
        }
    }

    return isThreadEndedInTime;
}
#endif

// ---------------------------------------------------------------------------
// Name:        osAreThreadHandlesEquivalent
// Description: checks if two thread handles represent the same thread
// Author:      AMD Developer Tools Team
// Date:        8/12/2008
// ---------------------------------------------------------------------------
bool osAreThreadHandlesEquivalent(const osThreadHandle& handle1, const osThreadHandle& handle2)
{
    bool retVal = false;

    if ((handle1 == OS_NO_THREAD_HANDLE) || (handle2 == OS_NO_THREAD_HANDLE))
    {
        // If one of the values is NULL, return true iff the other is NULL, too
        retVal = ((handle1 == OS_NO_THREAD_HANDLE) && (handle2 == OS_NO_THREAD_HANDLE));
    }
    else
    {
        // Check if the thread handles are equivalent:
        retVal = (::pthread_equal(handle1, handle2) != 0);
    }

    return retVal;
}

// ---------------------------------------------------------------------------
// Name:        osGetCurrentThreadId
// Description: Returns the OS id for the calling thread.
// Author:      AMD Developer Tools Team
// Date:        23/12/2008
// ---------------------------------------------------------------------------
osThreadId osGetCurrentThreadId()
{
    osThreadId retVal = OS_NO_THREAD_ID;

#ifdef __APPLE__

    // Get the current Mach kernel thread id:
     retVal = mach_thread_self();

#elif AMDT_LINUX_VARIANT == AMDT_GENERIC_LINUX_VARIANT
    {
        // Get the current pthread id:
        retVal = ::pthread_self();
    }
#endif

    return retVal;
}

#ifndef __APPLE__
// ---------------------------------------------------------------------------
// Name:        osGetUniqueCurrentThreadId
// Description: Returns the unique OS id for the calling thread.
// Author:      AMD Developer Tools Team
// Date:        18/09/2015
// ---------------------------------------------------------------------------
osThreadId osGetUniqueCurrentThreadId()
{
    osThreadId retVal = OS_NO_THREAD_ID;

#if AMDT_LINUX_VARIANT == AMDT_GENERIC_LINUX_VARIANT
    {
        // Get the current thread id:
        retVal = syscall(SYS_gettid);
    }
#else
#error Error Unknown linux variant!
#endif

    return retVal;
}
#endif

// ---------------------------------------------------------------------------
// Name:        osGetCurrentThreadHandle
// Description: Returns a handle to the current thread
// Author:      AMD Developer Tools Team
// Date:        28/11/2006
// ---------------------------------------------------------------------------
osThreadHandle osGetCurrentThreadHandle()
{
    osThreadHandle retVal = OS_NO_THREAD_HANDLE;

    // Get the current pthread thread id:
    retVal = ::pthread_self();

    return retVal;
}

// ---------------------------------------------------------------------------
// Name:        osThreadIdAsString
// Description: Inputs a thread id and outputs it as a string.
// Arguments: threadId - The input thread id.
//            threadIdAsString - The output thread id as a string.
// Author:      AMD Developer Tools Team
// Date:        5/5/2009
// ---------------------------------------------------------------------------
void osThreadIdAsString(osThreadId threadId, gtString& threadIdAsString)
{
    threadIdAsString.makeEmpty();
    threadIdAsString.appendFormattedString(L"%lu", (unsigned long)threadId);
}

// ---------------------------------------------------------------------------
// Name:        osWaitForFlagToTurnOff
// Description:
//  Suspends the calling thread until an input flag is turned off.
//  Performs an efficient wait (does not load the CPU)
//
// Arguments: flag - The flag to which we wait.
//            timeOutMsec - Wait timeout, measured in msec.
// Return Val: bool  - true iff the flag was cleared before we reached the
//                     timeout period.
// Author:      AMD Developer Tools Team
// Date:        20/11/2005
// ---------------------------------------------------------------------------
bool osWaitForFlagToTurnOff(bool& flag, unsigned long timeOutMsec)
{
    bool retVal = false;

    // Represents 1 millisecond and 50 milliseconds time intervals:
    static struct timeval stat_milisecondTimeInterval;
    static struct timeval stat_fiftyMilisecondTimeInterval;

    // If the time intervals were not calculated yet:
    static bool stat_timeoutsWereCalculated = false;

    if (!stat_timeoutsWereCalculated)
    {
        osTimeValFromMilliseconds(1, stat_milisecondTimeInterval);
        osTimeValFromMilliseconds(50, stat_fiftyMilisecondTimeInterval);

        stat_timeoutsWereCalculated = true;
    }

    // If the flag was not turned off yet:
    if (flag)
    {
        // Start measuring our wait time:
        osStopWatch stopWatch;
        stopWatch.start();

        // Counts our waiting time (msec):
        unsigned long waitedSoFarMSec = 0;

        // Counts the amount of wait intervals:
        int waitedIntervalsCount = 0;

        // While the flag is on and we didn't meet the timeout interval:
        while (flag && (waitedSoFarMSec < timeOutMsec))
        {
            // We will wait 5 times, giving our CPU small time slice to other threads:
            if (waitedIntervalsCount < 5)
            {
                int rc1 = ::select(0, NULL, NULL, NULL, &stat_milisecondTimeInterval);
                GT_ASSERT(rc1 == 0);
            }
            else
            {
                // The rest of the wait intervals will be longer:
                int rc1 = ::select(0, NULL, NULL, NULL, &stat_fiftyMilisecondTimeInterval);
                GT_ASSERT(rc1 == 0);

                // Verify that we will not overflow the waited interval count:
                waitedIntervalsCount = 6;
            }

            // Update the "waited so far" time count:
            double waitedSoFarSec = 0;
            stopWatch.getTimeInterval(waitedSoFarSec);
            waitedSoFarMSec = long(waitedSoFarSec * 1000);

            // Increment the intervals count:
            waitedIntervalsCount++;
        }
    }

    // Return true iff the function execution was ended:
    retVal = !flag;

    return retVal;
}

// ---------------------------------------------------------------------------
// Name:        osWaitForFlagToTurnOn
// Description:
//  Suspends the calling thread until an input flag is turned on.
//  Performs an efficient wait (does not load the CPU)
//
// Arguments: flag - The flag to which we wait.
//            timeOutMsec - Wait timeout, measured in msec.
// Return Val: bool  - true iff the flag was set before we reached the
//                     timeout period.
// Author:      AMD Developer Tools Team
// Date:        20/11/2005
// ---------------------------------------------------------------------------
bool osWaitForFlagToTurnOn(bool& flag, unsigned long timeOutMsec)
{
    bool retVal = false;

    // Represents 1 millisecond and 50 milliseconds time intervals:
    static struct timeval stat_milisecondTimeInterval;
    static struct timeval stat_fiftyMilisecondTimeInterval;

    // If the time intervals were not calculated yet:
    static bool stat_timeoutsWereCalculated = false;

    if (!stat_timeoutsWereCalculated)
    {
        osTimeValFromMilliseconds(1, stat_milisecondTimeInterval);
        osTimeValFromMilliseconds(50, stat_fiftyMilisecondTimeInterval);

        stat_timeoutsWereCalculated = true;
    }

    // If the flag was not turned on yet:
    if (!flag)
    {
        // Start measuring our wait time:
        osStopWatch stopWatch;
        stopWatch.start();

        // Counts our waiting time (msec):
        unsigned long waitedSoFarMSec = 0;

        // Counts the amount of wait intervals:
        int waitedIntervalsCount = 0;

        // While the flag is off and we didn't meet the timeout interval:
        while (!flag && (waitedSoFarMSec < timeOutMsec))
        {
            // We will wait 5 times, giving our CPU small time slice to other threads:
            if (waitedIntervalsCount < 5)
            {
                int rc1 = ::select(0, NULL, NULL, NULL, &stat_milisecondTimeInterval);
                GT_ASSERT(rc1 == 0);
            }
            else
            {
                // The rest of the wait intervals will be longer:
                int rc1 = ::select(0, NULL, NULL, NULL, &stat_fiftyMilisecondTimeInterval);
                GT_ASSERT(rc1 == 0);

                // Verify that we will not overflow the waited interval count:
                waitedIntervalsCount = 6;
            }

            // Update the "waited so far" time count:
            double waitedSoFarSec = 0;
            stopWatch.getTimeInterval(waitedSoFarSec);
            waitedSoFarMSec = long(waitedSoFarSec * 1000);

            // Increment the intervals count:
            waitedIntervalsCount++;
        }
    }

    // Return true iff the function execution was ended:
    retVal = flag;

    return retVal;
}

// ---------------------------------------------------------------------------
// Name:        osSleep
// Description: Suspends the execution of the current thread until the
//              time-out interval elapses.
// Arguments: miliseconds - Timeout interval, measured in milliseconds.
// Author:      AMD Developer Tools Team
// Date:        4/6/2008
// ---------------------------------------------------------------------------
void osSleep(unsigned long miliseconds)
{
    timeval milisecondTimeInterval;
    osTimeValFromMilliseconds(miliseconds, milisecondTimeInterval);

    // The rest of the wait intervals will be longer:
    int rc1 = ::select(0, NULL, NULL, NULL, &milisecondTimeInterval);
    GT_ASSERT(rc1 == 0);
}

osProcessThreadsEnumerator::osProcessThreadsEnumerator() : m_pEnumHandler(NULL)
{
}

osProcessThreadsEnumerator::~osProcessThreadsEnumerator()
{
    deinitialize();
}

bool osProcessThreadsEnumerator::initialize(osProcessId pid)
{
    char filename[OS_MAX_PATH];
    snprintf(filename, sizeof(filename), "/proc/%d/task", pid);

    m_pEnumHandler = opendir(filename);
    return (NULL != m_pEnumHandler);
}

void osProcessThreadsEnumerator::deinitialize()
{
    if (NULL != m_pEnumHandler)
    {
        closedir(reinterpret_cast<DIR*>(m_pEnumHandler));
        m_pEnumHandler = NULL;
    }
}

bool osProcessThreadsEnumerator::next(gtUInt32& threadId)
{
    struct dirent entry, *pNext;
    bool ret = false;

    while (0 == readdir_r(reinterpret_cast<DIR*>(m_pEnumHandler), &entry, &pNext) && NULL != pNext)
    {
        if (isdigit(*entry.d_name))
        {
            threadId = static_cast<gtUInt32>(strtoul(entry.d_name, NULL, 10));
            ret = true;
            break;
        }
    }

    return ret;
}


text:
import IW from './IW.js';
import Position from './Position.js';

export default class Action {
  constructor(avatar) {
    this.avatar = avatar;
  }

  setRandomTarget() {
    let enemies = this.avatar.team.opponent.survivals();

    if (enemies.length == 0) return;

    this.target = enemies[Math.floor(Math.random()*enemies.length)];
  }

  setNearestTarget() {
    let enemies = this.avatar.team.opponent.survivals();
    if (enemies.length == 0) return;

    this.target = enemies[0];
    let dist = Position.distance(this.target, this.avatar);

    for (let idx in enemies) {
      let newDist = Position.distance(enemies[idx],this.avatar);
      if (newDist < dist) {
        dist = newDist;
        this.target = enemies[idx];
      }
    }
  }

  get power() {
    let powerFactor = 0.25;

    this.computedPower = this.computedPower || (this.avatar.power * (1.0 + ( Math.random()* 2 * powerFactor - powerFactor)));

    return this.computedPower;
  }

  forward() {
    if (this.target) {
      this.target.team.receive(this);
    }
  }
}

redpajama_set_name: RedPajamaGithub


text: <input class="weui_input" type="datetime-local" value="" placeholder="">


text:
"""
This is part of WebScout software
Docs EN: http://hack4sec.pro/wiki/index.php/WebScout_en
Docs RU: http://hack4sec.pro/wiki/index.php/WebScout
License: MIT
Copyright (c) Anton Kuzmin <http://anton-kuzmin.ru> (ru) <http://anton-kuzmin.pro> (en)

Thread class for Dafs modules (selenium)
"""

import Queue
import time
import re
import pprint

from selenium.common.exceptions import TimeoutException

from classes.Registry import Registry
from classes.threads.SeleniumThread import SeleniumThread

class SParamsBruterThread(SeleniumThread):
    """ Thread class for Dafs modules (selenium) """
    queue = None
    method = None
    template = None
    mask_symbol = None
    counter = None
    last_action = 0
    queue_is_empty = False
    last_word = ""

    def __init__(
            self, queue, protocol, host, url, max_params_length, value, method, mask_symbol, not_found_re,
            delay, ddos_phrase, ddos_human, recreate_re, ignore_words_re, counter, result
    ):
        super(SParamsBruterThread, self).__init__()
        self.queue = queue
        self.protocol = protocol.lower()
        self.host = host
        self.method = 'get'
        self.url = url
        self.max_params_length = int(max_params_length)
        self.mask_symbol = mask_symbol
        self.counter = counter
        self.result = result
        self.value = value
        self.done = False
        self.not_found_re = False if not len(not_found_re) else re.compile(not_found_re)
        self.recreate_re = False if not len(recreate_re) else re.compile(recreate_re)
        self.http = Registry().get('http')
        self.delay = int(delay)
        self.ddos_phrase = ddos_phrase
        self.ddos_human = ddos_human
        self.ignore_words_re = False if not len(ignore_words_re) else re.compile(ignore_words_re)

        Registry().set('url_for_proxy_check', "{0}://{1}".format(protocol, host))

        self.browser_create()

        self.logger = Registry().get('logger')

    def build_params_str(self):
        params_str = "" if not len(self.last_word) else "{0}={1}&".format(self.last_word, self.value)
        self.last_word = ""
        while len(params_str) < self.max_params_length:
            try:
                word = self.queue.get()
            except Queue.Empty:
                self.queue_is_empty = True
                break

            if not len(word.strip()) or (self.ignore_words_re and self.ignore_words_re.findall(word)):
                continue

            self.counter.up()

            params_str += "{0}={1}&".format(word, self.value)

            self.last_word = word

        return params_str[:-(len(self.last_word) + 3)]

    def run(self):
        """ Run thread """
        need_retest = False

        while not self.done:
            self.last_action = int(time.time())

            if self.delay:
                time.sleep(self.delay)

            try:
                if not need_retest:
                    params_str = params_str = self.build_params_str()

                self.browser.get(self.protocol + "://" + self.host + self.url + params_str)

                if self.recreate_re and self.recreate_re.findall(self.browser.page_source):
                    need_retest = True
                    self.browser_close()
                    self.browser_create()
                    continue

                positive_item = False
                if not self.not_found_re.findall(self.browser.page_source):
                    param_found = False
                    for one_param in params_str.split("&"):
                        self.browser.get(self.protocol + "://" + self.host + self.url + one_param)

                        if not self.not_found_re.findall(self.browser.page_source):
                            self.result.append(one_param)
                            param_found = True
                            found_item = one_param

                    if param_found is False:
                        self.result.append(params_str)
                        found_item = params_str

                    positive_item = True

                    self.logger.item(found_item, self.browser.page_source, True, positive=positive_item)

                if len(self.result) >= int(Registry().get('config')['main']['positive_limit_stop']):
                    Registry().set('positive_limit_stop', True)

                need_retest = False

                if self.queue_is_empty:
                    self.done = True
                    break
            except UnicodeDecodeError as e:
                self.logger.ex(e)
                need_retest = False
            except TimeoutException as e:
                need_retest = True
                self.browser_close()
                self.browser_create()
                continue
            except BaseException as e:
                try:
                    need_retest = True
                    if len(e.args) and e.args[0] == 111:
                        self.browser_close()
                        self.browser_create()
                    elif not str(e).count('Timed out waiting for page load'):
                        self.logger.ex(e)
                except UnicodeDecodeError:
                    need_retest = False
            self.up_requests_count()

        self.browser_close()


text:
class ShadingNode;

class ShaderDefinitions
{
public:
	std::vector<ShadingNode> shadingNodes;
	bool readDone;

	ShaderDefinitions();
	~ShaderDefinitions();
	void readShaderDefinitions();
	bool validString(std::string& line);
	void printShaderDefs();
	ShadingNode findShadingNode(MObject mobject);
	ShadingNode findShadingNode(MString typeName);
private:
};

ShadingNode findShadingNode(MObject mobject);
ShadingNode findShadingNode(MString typeName);

#endif


text:
layout: post
title: 如何生成安全的密码 Hash:MD5, SHA, PBKDF2, BCrypt 示例

---

密码 Hash 值的产生是将用户所提供的密码通过使用一定的算法计算后得到的加密字符序列。在 Java 中提供很多被证明能有效保证密码安全的 Hash 算法实现,我将在这篇文章中讨论其中的部分算法。

需要注意的是,一旦生成密码的 Hash 值并存储在数据库中后,你将不可能再把它转换回密码明文。只能每次用户在登录到应用程序时,须重新生成 Hash 值与数据库中的 Hash 值匹配来完成密码的校验。

目录

* [简单的密码安全实现使用 MD5 算法](#md5)
* [使用 salt 让生成的 MD5 更加安全](#add_salt_to_md5)
* [中等密码安全实现使用 SHA 算法](#sha)
* [较高密码安全实现使用 PBKDF2WithHmacSHA1 算法](#PBKDF2WithHmacSHA1)
* [更加安全的密码实现使用 BCrypt 和 scrypt 算法](#BCrypt-and-Scrypt)
* [最后说明](#Fn)

简单的密码安全实现使用 MD5 算法

MD5消息摘要算法(MD5 Message-Digest Algorithm)是一种广泛使用的加密 Hash 函数,主要用于生成一个128bit(16byte) Hash 值。它的实现思路非常简单且易懂,**其最基本的思路是将可变长度的数据集映射为固定长度的数据集**。为了做到这一点,它将输入消息分割成 512-bit 的数据块。通过填补消息到末尾以确保其长度能除以512。现在这些块将通过 MD5 算法处理,其结果将是一个128位的散列值。使用MD5后,**生成的散列值通常是32位16进制的数字**。

在该文中,对于被加密的密码明文被称为"消息(message)",其加密后所生成的 Hash 值称为 "消息摘要(message digest)" 或简称 "摘要(digest)"。以下是 MD5 产生 Hash 值的代码示例:
{% highlight java %}
public class SimpleMD5Example
{
    public static void main(String[] args)
    {
        String passwordToHash = "password";
        String generatedPassword = null;
        try {
            // Create MessageDigest instance for MD5
            MessageDigest md = MessageDigest.getInstance("MD5");
            //Add password bytes to digest
            md.update(passwordToHash.getBytes());
            //Get the hash's bytes
            byte[] bytes = md.digest();
            //This bytes[] has bytes in decimal format;
            //Convert it to hexadecimal format
            StringBuilder sb = new StringBuilder();
            for(int i=0; i< bytes.length ;i++)
            {
                sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1));
            }
            //Get complete hashed password in hex format
            generatedPassword = sb.toString();
        }
        catch (NoSuchAlgorithmException e)
        {
            e.printStackTrace();
        }
        System.out.println(generatedPassword);
    }
}

Console output:

5f4dcc3b5aa765d61d8327deb882cf99
{% endhighlight java %}

虽然 MD5 是一个广为流传的 Hash 算法, 但它并不安全且所生成的 Hash 值也是相当的薄弱。它主要的优点在于生成速度快且易于实现。但是,这也意味着它是容易被[暴力攻击](http://en.wikipedia.org/wiki/Brute-force_attack)和[字典攻击](http://en.wikipedia.org/wiki/Dictionary_attack)。例如使用明文和 Hash 生成的[彩虹表](http://en.wikipedia.org/wiki/Rainbow_table)可以快速地搜索已知 Hash 对应的原数据。

此外,MD5 并没有避免 [Hash 碰撞](http://zh.wikipedia.org/wiki/%E5%93%88%E5%B8%8C%E8%A1%A8#.E5.A4.84.E7.90.86.E7.A2.B0.E6.92.9E):这意味不同的密码会导致生成相同的 Hash 值。

不过,如果你仍然需要使用 MD5,可以考虑为其加 [salt](http://zh.wikipedia.org/wiki/%E7%9B%90_%28%E5%AF%86%E7%A0%81%E5%AD%A6%29) 来进一步保证它的安全性。

使用 salt 让生成的 MD5 更加安全

这里需要注意的是,加 salt 並不是 MD5 所特有的, 你同样可以把它应用在其它算法中。所以,在这里你只需关注它是如何应用而不是它与 MD5 的联系。

在 Wikipedia 上对 salt 的定义是**通过一个单向函数获取随机数据来为密码或口令添加一些额外的数据**。更简单的说法则是**通过生成一些随机的文本将其附加到密码上来生成 Hash**。

为 Hash 加 salt 的主要目的是用来防止预先被计算好的彩虹表攻击。现在加 slat 好处是将原本一次比较变为多次比较从而减慢对密码 Hash 值的猜测,否则对 Hash 密码库的破解效率将是非常之高。

重要的是:在 Java 中,我们总是需要使用 SecureRandom 来生成一个好的 salt 值,因此可以利用 SecureRandom 类所提供 "SHA1PRNG" 算法来生成伪随机数。代码如下所示:

{% highlight java %}
private static String getSalt() throws NoSuchAlgorithmException
{
    //Always use a SecureRandom generator
    SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
    //Create array for salt
    byte[] salt = new byte[16];
    //Get a random salt
    sr.nextBytes(salt);
    //return salt
    return salt.toString();
}
{% endhighlight java %}

SHA1PRNG 算法是基于 SHA-1 算法实现且保密性较强的伪随机数生成器。要注意的是,如果不为它提供随机数种子,它将会通过真随机数来生成一个种子(TRNG)。 译注:[关于 TRGN 和 PRGN](http://blog.bluesky.cn/archives/418/true-random-number-and-pseudo-random-number.html)。

接下来,看看为 MD5 Hash 加 slat 的代码示例:

{% highlight java %}
public class SaltedMD5Example
{
    public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchProviderException
    {
        String passwordToHash = "password";
        String salt = getSalt();

        String securePassword = getSecurePassword(passwordToHash, salt);
        System.out.println(securePassword); //Prints 83ee5baeea20b6c21635e4ea67847f66

        String regeneratedPassowrdToVerify = getSecurePassword(passwordToHash, salt);
        System.out.println(regeneratedPassowrdToVerify); //Prints 83ee5baeea20b6c21635e4ea67847f66
    }

    private static String getSecurePassword(String passwordToHash, String salt)
    {
        String generatedPassword = null;
        try {
            // Create MessageDigest instance for MD5
            MessageDigest md = MessageDigest.getInstance("MD5");
            //Add password bytes to digest
            md.update(salt.getBytes());
            //Get the hash's bytes
            byte[] bytes = md.digest(passwordToHash.getBytes());
            //This bytes[] has bytes in decimal format;
            //Convert it to hexadecimal format
            StringBuilder sb = new StringBuilder();
            for(int i=0; i< bytes.length ;i++)
            {
                sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1));
            }
            //Get complete hashed password in hex format
            generatedPassword = sb.toString();
        }
        catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return generatedPassword;
    }

    //Add salt
    private static String getSalt() throws NoSuchAlgorithmException, NoSuchProviderException
    {
        //Always use a SecureRandom generator
        SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", "SUN");
        //Create array for salt
        byte[] salt = new byte[16];
        //Get a random salt
        sr.nextBytes(salt);
        //return salt
        return salt.toString();
    }
}
{% endhighlight java %}

重要提示:请注意,现在你必须每一个密码 Hash 存储它 slat 值。因为当用户登录系统,你必须使用最初生成的 slat 来再次生成 Hash 与存储的 Hash 进行匹配。如果使用不同的 slat(生成随机 slat)那么生成的 Hash 将不同。

此外,你可能听说过多次 Hash 和加 salt。通常就是指创建自定义的组合,如:

```salt+password+salt => hash```

实际上你没必要这样去做,因为这并不能帮助你进一步巩固 Hash 的安全性。如果你需要更高的安全性,正确的做法应该去选择一个更好的算法。

中等的密码安全实现使用SHA算法

SHA(安全散列算法)同样是作为加密 Hash 函数家族中的一员。除了它生成的 Hash 安全性比 MD5 更强之外其它都与 MD5 非常类似。然而,它们生成的 Hash 并不总是唯一的,这意味着输入两个不同的值所获的 Hash 却是相同的。通常这种情况的发生我们称之为"碰撞"。 不过,SHA 碰撞的几率小于 MD5。你甚至无需担心碰撞的发生,因为这种情况非常罕见。

在 Java 中有提供有4种 SHA 算法的实现,相对 MD5(128 bit hash) 它提供了以下长度的 Hash:

* SHA-1 (简单实现 – 160 bits Hash)
* SHA-256 (强于 SHA-1 – 256 bits Hash)
* SHA-384 (强于 SHA-256 – 384 bits Hash)
* SHA-512 (强于 SHA-384 – 512 bits Hash)

通常越长的 Hash 越难破解,这是核心思想。

要获取相应算法实现,可通过参数的方式传给 MessageDigest 来获得实例。如下所示:

{% highlight java %}
MessageDigest md = MessageDigest.getInstance("SHA-1");
//OR
MessageDigest md = MessageDigest.getInstance("SHA-256");
{% endhighlight java %}

下面通过测试程序来看 SHA 的应用:

{% highlight java %}
package com.howtodoinjava.hashing.password.demo.sha;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

public class SHAExample {

    public static void main(String[] args) throws NoSuchAlgorithmException {
        String passwordToHash = "password";
        String salt = getSalt();

        String securePassword = get_SHA_1_SecurePassword(passwordToHash, salt);
        System.out.println(securePassword);

        securePassword = get_SHA_256_SecurePassword(passwordToHash, salt);
        System.out.println(securePassword);

        securePassword = get_SHA_384_SecurePassword(passwordToHash, salt);
        System.out.println(securePassword);

        securePassword = get_SHA_512_SecurePassword(passwordToHash, salt);
        System.out.println(securePassword);
    }

    private static String get_SHA_1_SecurePassword(String passwordToHash, String salt)
    {
        String generatedPassword = null;
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            md.update(salt.getBytes());
            byte[] bytes = md.digest(passwordToHash.getBytes());
            StringBuilder sb = new StringBuilder();
            for(int i=0; i< bytes.length ;i++)
            {
                sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1));
            }
            generatedPassword = sb.toString();
        }
        catch (NoSuchAlgorithmException e)
        {
            e.printStackTrace();
        }
        return generatedPassword;
    }

    private static String get_SHA_256_SecurePassword(String passwordToHash, String salt)
    {
        //Use MessageDigest md = MessageDigest.getInstance("SHA-256");
    }

    private static String get_SHA_384_SecurePassword(String passwordToHash, String salt)
    {
        //Use MessageDigest md = MessageDigest.getInstance("SHA-384");
    }

    private static String get_SHA_512_SecurePassword(String passwordToHash, String salt)
    {
        //Use MessageDigest md = MessageDigest.getInstance("SHA-512");
    }

    //Add salt
    private static String getSalt() throws NoSuchAlgorithmException
    {
        SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
        byte[] salt = new byte[16];
        sr.nextBytes(salt);
        return salt.toString();
    }
}

Output:
// SHA-1
e4c53afeaa7a08b1f27022abd443688c37981bc4
// SHA-256
87adfd14a7a89b201bf6d99105b417287db6581d8aee989076bb7f86154e8f32
// SHA-384
bc5914fe3896ae8a2c43a4513f2a0d716974cc305733847e3d49e1ea52d1ca50e2a9d0ac192acd43facfb422bb5ace88
// SAH-512
529211542985b8f7af61994670d03d25d55cc9cd1cff8d57bb799c4b586891e112b197530c76744bcd7ef135b58d47d65a0bec221eb5d77793956cf2709dd012
{% endhighlight java %}

如上代码所示,在使用 SHA 的同时同样可以为其加 salt 来加强它的安全性。

较高密码安全实现使用 PBKDF2WithHmacSHA1 算法

到目前为止,我们已经了解如何为密码生成安全的 Hash 值以及通过利用 salt 来加强它的安全性。但今天的问题是,硬件的速度已经远远超过任何使用字典或彩虹表进行的暴力攻击,并且任何密码都能被破解,只是使用时间多少的问题。

为了解决这个问题,主要想法是尽可能降低暴力攻击速度来保证最小化的损失。我们下一个算法同样是基于这个概念。目标是使 Hash 函数足够慢以妨碍攻击,并对用户来说仍然非常快且不会感到有明显的延时。

要达到这个目的通常是使用某些 CPU 密集型算法来实现,比如 PBKDF2, [Bcrypt](http://en.wikipedia.org/wiki/Bcrypt) 或 [Scrypt](http://en.wikipedia.org/wiki/Bcrypt) 。这些算法采用 work factor(也称之为 security factor)或迭代次数作为参数来确定 Hash 函数将变的有多慢,并且随着日后计算能力的提高,可以逐步增大 work factor 来使之与计算能力达到平衡。

Java 中可通过 "[PBKDF2WithHmacSHA1](http://docs.oracle.com/javase/7/docs/technotes/guides/security/StandardNames.html#SecretKeyFactory)" 来实现"[PBKDF2](http://en.wikipedia.org/wiki/PBKDF2)"算法,下面代码是使用示例:

{% highlight java %}
public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeySpecException
{
    String  originalPassword = "password";
    String generatedSecuredPasswordHash = generateStorngPasswordHash(originalPassword);
    System.out.println(generatedSecuredPasswordHash);
}
private static String generateStorngPasswordHash(String password) throws NoSuchAlgorithmException, InvalidKeySpecException
{
    int iterations = 1000;
    char[] chars = password.toCharArray();
    byte[] salt = getSalt().getBytes();

    PBEKeySpec spec = new PBEKeySpec(chars, salt, iterations, 64 * 8);
    SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    byte[] hash = skf.generateSecret(spec).getEncoded();
    return iterations + ":" + toHex(salt) + ":" + toHex(hash);
}

private static String getSalt() throws NoSuchAlgorithmException
{
    SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
    byte[] salt = new byte[16];
    sr.nextBytes(salt);
    return salt.toString();
}

private static String toHex(byte[] array) throws NoSuchAlgorithmException
{
    BigInteger bi = new BigInteger(1, array);
    String hex = bi.toString(16);
    int paddingLength = (array.length * 2) - hex.length();
    if(paddingLength > 0)
    {
        return String.format("%0"  +paddingLength + "d", 0) + hex;
    }else{
        return hex;
    }
}

Output:

1000:5b4240333032306164:f38d165fce8ce42f59d366139ef5d9e1ca1247f0e06e503ee1a611dd9ec40876bb5edb8409f5abe5504aab6628e70cfb3d3a18e99d70357d295002c3d0a308a0
{% endhighlight java %}

接下来的是当重新回来时,需要提供登录密码验证的方法实现:

{% highlight java %}
public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeySpecException
    {
        String  originalPassword = "password";
        String generatedSecuredPasswordHash = generateStorngPasswordHash(originalPassword);
        System.out.println(generatedSecuredPasswordHash);

        boolean matched = validatePassword("password", generatedSecuredPasswordHash);
        System.out.println(matched);

        matched = validatePassword("password1", generatedSecuredPasswordHash);
        System.out.println(matched);
    }

    private static boolean validatePassword(String originalPassword, String storedPassword) throws NoSuchAlgorithmException, InvalidKeySpecException
    {
        String[] parts = storedPassword.split(":");
        int iterations = Integer.parseInt(parts[0]);
        byte[] salt = fromHex(parts[1]);
        byte[] hash = fromHex(parts[2]);

        PBEKeySpec spec = new PBEKeySpec(originalPassword.toCharArray(), salt, iterations, hash.length * 8);
        SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        byte[] testHash = skf.generateSecret(spec).getEncoded();

        int diff = hash.length ^ testHash.length;
        for(int i = 0; i < hash.length && i < testHash.length; i++)
        {
            diff |= hash[i] ^ testHash[i];
        }
        return diff == 0;
    }
    private static byte[] fromHex(String hex) throws NoSuchAlgorithmException
    {
        byte[] bytes = new byte[hex.length() / 2];
        for(int i = 0; i<bytes.length ;i++)
        {
            bytes[i] = (byte)Integer.parseInt(hex.substring(2 * i, 2 * i + 2), 16);
        }
        return bytes;
    }
{% endhighlight java %}

参考以上代码时需注意,如果发现任何问题请下载本文章结尾处附件中的代码。

更加安全的密码实现使用 bcrypt 和 scrypt 算法

bcrypt 的背后的思想与 PBKDF2 类似。只是 Java 中并没有内置支持使攻击者变慢的 bcrypt 算法实现,但你仍然可以找到并下载它的源码。

下以是 bcrypt 的使用代码示例(其中 Bcrypt.java 已提供在源码中):
{% highlight java %}
public class BcryptHashingExample
{
    public static void main(String[] args) throws NoSuchAlgorithmException
    {
        String  originalPassword = "password";
        String generatedSecuredPasswordHash = BCrypt.hashpw(originalPassword, BCrypt.gensalt(12));
        System.out.println(generatedSecuredPasswordHash);

        boolean matched = BCrypt.checkpw(originalPassword, generatedSecuredPasswordHash);
        System.out.println(matched);
    }
}

Output:

$2a$12$WXItscQ/FDbLKU4mO58jxu3Tx/mueaS8En3M6QOVZIZLaGdWrS.pK
true
{% endhighlight java %}

与 bcrypt 算法类似,我已经从 [github](https://github.com/wg/scrypt) 下载了 scrypt 算法的源代码并添加到在最后一节中的源码下载中。看看它是如何使用:

{% highlight java %}
public class ScryptPasswordHashingDemo
{
    public static void main(String[] args) {
        String originalPassword = "password";
        String generatedSecuredPasswordHash = SCryptUtil.scrypt(originalPassword, 16, 16, 16);
        System.out.println(generatedSecuredPasswordHash);

        boolean matched = SCryptUtil.check("password", generatedSecuredPasswordHash);
        System.out.println(matched);

        matched = SCryptUtil.check("passwordno", generatedSecuredPasswordHash);
        System.out.println(matched);
    }
}

Output:

$s0$41010$Gxbn9LQ4I+fZ/kt0glnZgQ==$X+dRy9oLJz1JaNm1xscUl7EmUFHIILT1ktYB5DQ3fZs=
true
false
{% endhighlight java %}

最后说明

1. 在应用程序中存储密码明文是极其危险的事情。
2. MD5 提供了最基本的安全 Hash 生成,使用时应为其添加 slat 来进一步加强它的安全性。
3. MD5 生成128位的 Hash。为了使它更安全,应该使用 SHA 算法生成 160-bit 或 512-bit 的长 Hash,其中 512-bit 是最强的。
4. 虽然使用 SHA Hash 密码也能被当今快速的硬件破解,如要避免这一点,你需要的算法是能让暴力攻击尽可能的变慢且使影响减至最低。这时候你可以使用 PBKDF2, BCrypt 或 SCrypt 算法。
5. 请在深思熟虑后来选择适当的安全算法。

[点击这里下载完整源码](https://docs.google.com/file/d/0B7yo2HclmjI4ZDNfdlZ2YUhoSGM/edit?usp=sharing)

参考资料:

* https://en.wikipedia.org/wiki/MD5
* https://en.wikipedia.org/wiki/Secure_Hash_Algorithm
* http://en.wikipedia.org/wiki/Bcrypt
* http://en.wikipedia.org/wiki/Scrypt
* http://en.wikipedia.org/wiki/PBKDF2
* https://github.com/wg/scrypt
* http://www.mindrot.org/projects/jBCrypt/

**Original: [How to generate secure password hash : MD5, SHA, PBKDF2, BCrypt examples](http://howtodoinjava.com/2013/07/22/how-to-generate-secure-password-hash-md5-sha-pbkdf2-bcrypt-examples/)**


text:
require 'nokogiri'
require 'bzip2'

FULL_SIZE = 29131775005

class MyDoc < Nokogiri::XML::SAX::Document
  def start_element name, attrs = []
    @inTitleTag = false
    case name
    when "page"
      @pos = $pos
    when "title"
      @inTitleTag = true
      @title = ''
    end
  end

  def characters string
    @title += string if @inTitleTag
  end

  def end_element name
    return unless name == 'page'

    $pages_count += 1

    interval = 25000
    if $pages_count % interval == 0
      stats_thread = Thread.start({ :pages_count => $pages_count, :pos => @pos, :now => Time.now, :start_time => @start_time }) do |args|
        now = args[:now]
        completion = args[:pos].to_f/FULL_SIZE.to_f
        time_taken = now - $start
        time_total = time_taken / completion
        time_left = time_total - time_taken
        time_left_h = time_left.to_i / 3600
        time_left_m = time_left.to_i / 60 - time_left_h * 60
        time_left_s = time_left.to_i % 60

        STDERR.puts "#{(completion * 100.0).round(3)}%", "Pages read: #{args[:pages_count]}"
        STDERR.puts "#{(interval.to_f / (now - args[:start_time])).round 2} pages/sec. #{time_left_h}h#{time_left_m}m#{time_left_s}s" if !args[:start_time].nil?
      end
      @start_time = Time.now
    end

    STDOUT.puts "#{@title.strip} #{@pos}"
  end
end

exit if ARGV.count != 1

$pages_count = 0
$pos = 0
$start = Time.now
parser = Nokogiri::XML::SAX::PushParser.new(MyDoc.new, nil, 'UTF-8')
io = Bzip2::Reader.new(File.open(ARGV[0]))
while line = io.readline
  parser << line
  $pos += line.bytesize
end
parser.finish


text:
Login

            {{vm.invalidUsername}}

            {{vm.invalidPassword}}

        <form novalidate name="myForm">

            <input type="text"
                   ng-model="username"
                   name="username"
                   class="form-control wd-center"
                   placeholder="username"
                   autocapitalize="off"
                   required />

                <input type="password"
                       ng-model="password"
                       class="form-control wd-center"
                       placeholder="password"
                       required />

        </form>
        Login

            Facebook

        Register


text:
<?php
namespace Nepf\System;

class Singleton {
	private static $instance = array();

	function __construct(){
		$cls = get_called_class();
		if (isset(self::$instance[$cls])) {
			throw new FrameworkException('Only one instance allowed.');
		}
		self::$instance[$cls] = &$this;
	}

	public static function getInstance(){
		$cls = get_called_class();
		return isset(self::$instance[$cls])?self::$instance[$cls]:null;
	}
}

?>


text:
package net.cserny.videosmover.service.parser;

import net.cserny.videosmover.model.Video;
import net.cserny.videosmover.model.VideoType;
import net.cserny.videosmover.service.MessageProvider;
import net.cserny.videosmover.service.SimpleMessageRegistry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
public class TvShowOutputVideoNameChecker implements OutputVideoNameChecker {

    private final SimpleMessageRegistry messageRegistry;
    private final Pattern pattern = Pattern.compile(
            "(.*)s(?<season>\\d{1,4})e(?<episodes>\\d{1,3}([eE-]{1,2}\\d{1,3})?)(.*)",
            Pattern.CASE_INSENSITIVE);

    @Autowired
    public TvShowOutputVideoNameChecker(SimpleMessageRegistry messageRegistry) {
        this.messageRegistry = messageRegistry;
    }

    @Override
    public boolean canHandle(VideoType type) {
        return type == VideoType.TVSHOW;
    }

    @Override
    public void check(Video video) {
        Matcher matcher = pattern.matcher(video.getFileName());
        if (!matcher.find()) {
            messageRegistry.displayMessage(MessageProvider.incorrectTvShowFileName(video.getFileName()));
        }
    }
}


text:
using System;
using System.Linq;
using System.Reflection;

namespace SewingMachine.Impl
{
    static class ReflectionHelpers
    {
        public const BindingFlags AllInstance = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance;
        public static readonly MethodInfo CastIntPtrToVoidPtr = typeof(IntPtr).GetMethods()
            .Single(m => m.ReturnType == typeof(void*) && m.GetParameters().Length == 1 && m.GetParameters()[0].ParameterType == typeof(IntPtr));
    }
}


text:
"""
Abstract base class for the various polynomial Classes.

The ABCPolyBase class provides the methods needed to implement the common API
for the various polynomial classes. It operates as a mixin, but uses the
abc module from the stdlib, hence it is only available for Python >= 2.6.

"""
import os
import abc
import numbers

import numpy as np
from . import polyutils as pu

__all__ = ['ABCPolyBase']

class ABCPolyBase(abc.ABC):
    """An abstract base class for immutable series classes.

    ABCPolyBase provides the standard Python numerical methods
    '+', '-', '*', '//', '%', 'divmod', '**', and '()' along with the
    methods listed below.

    .. versionadded:: 1.9.0

    Parameters
    ----------
    coef : array_like
        Series coefficients in order of increasing degree, i.e.,
        ``(1, 2, 3)`` gives ``1*P_0(x) + 2*P_1(x) + 3*P_2(x)``, where
        ``P_i`` is the basis polynomials of degree ``i``.
    domain : (2,) array_like, optional
        Domain to use. The interval ``[domain[0], domain[1]]`` is mapped
        to the interval ``[window[0], window[1]]`` by shifting and scaling.
        The default value is the derived class domain.
    window : (2,) array_like, optional
        Window, see domain for its use. The default value is the
        derived class window.

    Attributes
    ----------
    coef : (N,) ndarray
        Series coefficients in order of increasing degree.
    domain : (2,) ndarray
        Domain that is mapped to window.
    window : (2,) ndarray
        Window that domain is mapped to.

    Class Attributes
    ----------------
    maxpower : int
        Maximum power allowed, i.e., the largest number ``n`` such that
        ``p(x)**n`` is allowed. This is to limit runaway polynomial size.
    domain : (2,) ndarray
        Default domain of the class.
    window : (2,) ndarray
        Default window of the class.

    """

    # Not hashable
    __hash__ = None

    # Opt out of numpy ufuncs and Python ops with ndarray subclasses.
    __array_ufunc__ = None

    # Limit runaway size. T_n^m has degree n*m
    maxpower = 100

    # Unicode character mappings for improved __str__
    _superscript_mapping = str.maketrans({
        "0": "⁰",
        "1": "¹",
        "2": "²",
        "3": "³",
        "4": "⁴",
        "5": "⁵",
        "6": "⁶",
        "7": "⁷",
        "8": "⁸",
        "9": "⁹"
    })
    _subscript_mapping = str.maketrans({
        "0": "₀",
        "1": "₁",
        "2": "₂",
        "3": "₃",
        "4": "₄",
        "5": "₅",
        "6": "₆",
        "7": "₇",
        "8": "₈",
        "9": "₉"
    })
    # Some fonts don't support full unicode character ranges necessary for
    # the full set of superscripts and subscripts, including common/default
    # fonts in Windows shells/terminals. Therefore, default to ascii-only
    # printing on windows.
    _use_unicode = not os.name == 'nt'

    @property
    @abc.abstractmethod
    def domain(self):
        pass

    @property
    @abc.abstractmethod
    def window(self):
        pass

    @property
    @abc.abstractmethod
    def basis_name(self):
        pass

    @staticmethod
    @abc.abstractmethod
    def _add(c1, c2):
        pass

    @staticmethod
    @abc.abstractmethod
    def _sub(c1, c2):
        pass

    @staticmethod
    @abc.abstractmethod
    def _mul(c1, c2):
        pass

    @staticmethod
    @abc.abstractmethod
    def _div(c1, c2):
        pass

    @staticmethod
    @abc.abstractmethod
    def _pow(c, pow, maxpower=None):
        pass

    @staticmethod
    @abc.abstractmethod
    def _val(x, c):
        pass

    @staticmethod
    @abc.abstractmethod
    def _int(c, m, k, lbnd, scl):
        pass

    @staticmethod
    @abc.abstractmethod
    def _der(c, m, scl):
        pass

    @staticmethod
    @abc.abstractmethod
    def _fit(x, y, deg, rcond, full):
        pass

    @staticmethod
    @abc.abstractmethod
    def _line(off, scl):
        pass

    @staticmethod
    @abc.abstractmethod
    def _roots(c):
        pass

    @staticmethod
    @abc.abstractmethod
    def _fromroots(r):
        pass

    def has_samecoef(self, other):
        """Check if coefficients match.

        .. versionadded:: 1.6.0

        Parameters
        ----------
        other : class instance
            The other class must have the ``coef`` attribute.

        Returns
        -------
        bool : boolean
            True if the coefficients are the same, False otherwise.

        """
        if len(self.coef) != len(other.coef):
            return False
        elif not np.all(self.coef == other.coef):
            return False
        else:
            return True

    def has_samedomain(self, other):
        """Check if domains match.

        .. versionadded:: 1.6.0

        Parameters
        ----------
        other : class instance
            The other class must have the ``domain`` attribute.

        Returns
        -------
        bool : boolean
            True if the domains are the same, False otherwise.

        """
        return np.all(self.domain == other.domain)

    def has_samewindow(self, other):
        """Check if windows match.

        .. versionadded:: 1.6.0

        Parameters
        ----------
        other : class instance
            The other class must have the ``window`` attribute.

        Returns
        -------
        bool : boolean
            True if the windows are the same, False otherwise.

        """
        return np.all(self.window == other.window)

    def has_sametype(self, other):
        """Check if types match.

        .. versionadded:: 1.7.0

        Parameters
        ----------
        other : object
            Class instance.

        Returns
        -------
        bool : boolean
            True if other is same class as self

        """
        return isinstance(other, self.__class__)

    def _get_coefficients(self, other):
        """Interpret other as polynomial coefficients.

        The `other` argument is checked to see if it is of the same
        class as self with identical domain and window. If so,
        return its coefficients, otherwise return `other`.

        .. versionadded:: 1.9.0

        Parameters
        ----------
        other : anything
            Object to be checked.

        Returns
        -------
        coef
            The coefficients of`other` if it is a compatible instance,
            of ABCPolyBase, otherwise `other`.

        Raises
        ------
        TypeError
            When `other` is an incompatible instance of ABCPolyBase.

        """
        if isinstance(other, ABCPolyBase):
            if not isinstance(other, self.__class__):
                raise TypeError("Polynomial types differ")
            elif not np.all(self.domain == other.domain):
                raise TypeError("Domains differ")
            elif not np.all(self.window == other.window):
                raise TypeError("Windows differ")
            return other.coef
        return other

    def __init__(self, coef, domain=None, window=None):
        [coef] = pu.as_series([coef], trim=False)
        self.coef = coef

        if domain is not None:
            [domain] = pu.as_series([domain], trim=False)
            if len(domain) != 2:
                raise ValueError("Domain has wrong number of elements.")
            self.domain = domain

        if window is not None:
            [window] = pu.as_series([window], trim=False)
            if len(window) != 2:
                raise ValueError("Window has wrong number of elements.")
            self.window = window

    def __repr__(self):
        coef = repr(self.coef)[6:-1]
        domain = repr(self.domain)[6:-1]
        window = repr(self.window)[6:-1]
        name = self.__class__.__name__
        return f"{name}({coef}, domain={domain}, window={window})"

    def __format__(self, fmt_str):
        if fmt_str == '':
            return self.__str__()
        if fmt_str not in ('ascii', 'unicode'):
            raise ValueError(
                f"Unsupported format string '{fmt_str}' passed to "
                f"{self.__class__}.__format__. Valid options are "
                f"'ascii' and 'unicode'"
            )
        if fmt_str == 'ascii':
            return self._generate_string(self._str_term_ascii)
        return self._generate_string(self._str_term_unicode)

    def __str__(self):
        if self._use_unicode:
            return self._generate_string(self._str_term_unicode)
        return self._generate_string(self._str_term_ascii)

    def _generate_string(self, term_method):
        """
        Generate the full string representation of the polynomial, using
        ``term_method`` to generate each polynomial term.
        """
        # Get configuration for line breaks
        linewidth = np.get_printoptions().get('linewidth', 75)
        if linewidth < 1:
            linewidth = 1
        out = f"{self.coef[0]}"
        for i, coef in enumerate(self.coef[1:]):
            out += " "
            power = str(i + 1)
            # Polynomial coefficient
            # The coefficient array can be an object array with elements that
            # will raise a TypeError with >= 0 (e.g. strings or Python
            # complex). In this case, represent the coefficient as-is.
            try:
                if coef >= 0:
                    next_term = f"+ {coef}"
                else:
                    next_term = f"- {-coef}"
            except TypeError:
                next_term = f"+ {coef}"
            # Polynomial term
            next_term += term_method(power, "x")
            # Length of the current line with next term added
            line_len = len(out.split('\n')[-1]) + len(next_term)
            # If not the last term in the polynomial, it will be two
            # characters longer due to the +/- with the next term
            if i < len(self.coef[1:]) - 1:
                line_len += 2
            # Handle linebreaking
            if line_len >= linewidth:
                next_term = next_term.replace(" ", "\n", 1)
            out += next_term
        return out

    @classmethod
    def _str_term_unicode(cls, i, arg_str):
        """
        String representation of single polynomial term using unicode
        characters for superscripts and subscripts.
        """
        if cls.basis_name is None:
            raise NotImplementedError(
                "Subclasses must define either a basis_name, or override "
                "_str_term_unicode(cls, i, arg_str)"
            )
        return (f"·{cls.basis_name}{i.translate(cls._subscript_mapping)}"
                f"({arg_str})")

    @classmethod
    def _str_term_ascii(cls, i, arg_str):
        """
        String representation of a single polynomial term using ** and _ to
        represent superscripts and subscripts, respectively.
        """
        if cls.basis_name is None:
            raise NotImplementedError(
                "Subclasses must define either a basis_name, or override "
                "_str_term_ascii(cls, i, arg_str)"
            )
        return f" {cls.basis_name}_{i}({arg_str})"

    @classmethod
    def _repr_latex_term(cls, i, arg_str, needs_parens):
        if cls.basis_name is None:
            raise NotImplementedError(
                "Subclasses must define either a basis name, or override "
                "_repr_latex_term(i, arg_str, needs_parens)")
        # since we always add parens, we don't care if the expression needs them
        return f"{{{cls.basis_name}}}_{{{i}}}({arg_str})"

    @staticmethod
    def _repr_latex_scalar(x):
        # TODO: we're stuck with disabling math formatting until we handle
        # exponents in this function
        return r'\text{{{}}}'.format(x)

    def _repr_latex_(self):
        # get the scaled argument string to the basis functions
        off, scale = self.mapparms()
        if off == 0 and scale == 1:
            term = 'x'
            needs_parens = False
        elif scale == 1:
            term = f"{self._repr_latex_scalar(off)} + x"
            needs_parens = True
        elif off == 0:
            term = f"{self._repr_latex_scalar(scale)}x"
            needs_parens = True
        else:
            term = (
                f"{self._repr_latex_scalar(off)} + "
                f"{self._repr_latex_scalar(scale)}x"
            )
            needs_parens = True

        mute = r"\color{{LightGray}}{{{}}}".format

        parts = []
        for i, c in enumerate(self.coef):
            # prevent duplication of + and - signs
            if i == 0:
                coef_str = f"{self._repr_latex_scalar(c)}"
            elif not isinstance(c, numbers.Real):
                coef_str = f" + ({self._repr_latex_scalar(c)})"
            elif not np.signbit(c):
                coef_str = f" + {self._repr_latex_scalar(c)}"
            else:
                coef_str = f" - {self._repr_latex_scalar(-c)}"

            # produce the string for the term
            term_str = self._repr_latex_term(i, term, needs_parens)
            if term_str == '1':
                part = coef_str
            else:
                part = rf"{coef_str}\,{term_str}"

            if c == 0:
                part = mute(part)

            parts.append(part)

        if parts:
            body = ''.join(parts)
        else:
            # in case somehow there are no coefficients at all
            body = '0'

        return rf"$x \mapsto {body}$"

    # Pickle and copy

    def __getstate__(self):
        ret = self.__dict__.copy()
        ret['coef'] = self.coef.copy()
        ret['domain'] = self.domain.copy()
        ret['window'] = self.window.copy()
        return ret

    def __setstate__(self, dict):
        self.__dict__ = dict

    # Call

    def __call__(self, arg):
        off, scl = pu.mapparms(self.domain, self.window)
        arg = off + scl*arg
        return self._val(arg, self.coef)

    def __iter__(self):
        return iter(self.coef)

    def __len__(self):
        return len(self.coef)

    # Numeric properties.

    def __neg__(self):
        return self.__class__(-self.coef, self.domain, self.window)

    def __pos__(self):
        return self

    def __add__(self, other):
        othercoef = self._get_coefficients(other)
        try:
            coef = self._add(self.coef, othercoef)
        except Exception:
            return NotImplemented
        return self.__class__(coef, self.domain, self.window)

    def __sub__(self, other):
        othercoef = self._get_coefficients(other)
        try:
            coef = self._sub(self.coef, othercoef)
        except Exception:
            return NotImplemented
        return self.__class__(coef, self.domain, self.window)

    def __mul__(self, other):
        othercoef = self._get_coefficients(other)
        try:
            coef = self._mul(self.coef, othercoef)
        except Exception:
            return NotImplemented
        return self.__class__(coef, self.domain, self.window)

    def __truediv__(self, other):
        # there is no true divide if the rhs is not a Number, although it
        # could return the first n elements of an infinite series.
        # It is hard to see where n would come from, though.
        if not isinstance(other, numbers.Number) or isinstance(other, bool):
            raise TypeError(
                f"unsupported types for true division: "
                f"'{type(self)}', '{type(other)}'"
            )
        return self.__floordiv__(other)

    def __floordiv__(self, other):
        res = self.__divmod__(other)
        if res is NotImplemented:
            return res
        return res[0]

    def __mod__(self, other):
        res = self.__divmod__(other)
        if res is NotImplemented:
            return res
        return res[1]

    def __divmod__(self, other):
        othercoef = self._get_coefficients(other)
        try:
            quo, rem = self._div(self.coef, othercoef)
        except ZeroDivisionError:
            raise
        except Exception:
            return NotImplemented
        quo = self.__class__(quo, self.domain, self.window)
        rem = self.__class__(rem, self.domain, self.window)
        return quo, rem

    def __pow__(self, other):
        coef = self._pow(self.coef, other, maxpower=self.maxpower)
        res = self.__class__(coef, self.domain, self.window)
        return res

    def __radd__(self, other):
        try:
            coef = self._add(other, self.coef)
        except Exception:
            return NotImplemented
        return self.__class__(coef, self.domain, self.window)

    def __rsub__(self, other):
        try:
            coef = self._sub(other, self.coef)
        except Exception:
            return NotImplemented
        return self.__class__(coef, self.domain, self.window)

    def __rmul__(self, other):
        try:
            coef = self._mul(other, self.coef)
        except Exception:
            return NotImplemented
        return self.__class__(coef, self.domain, self.window)

    def __rdiv__(self, other):
        # set to __floordiv__ /.
        return self.__rfloordiv__(other)

    def __rtruediv__(self, other):
        # An instance of ABCPolyBase is not considered a
        # Number.
        return NotImplemented

    def __rfloordiv__(self, other):
        res = self.__rdivmod__(other)
        if res is NotImplemented:
            return res
        return res[0]

    def __rmod__(self, other):
        res = self.__rdivmod__(other)
        if res is NotImplemented:
            return res
        return res[1]

    def __rdivmod__(self, other):
        try:
            quo, rem = self._div(other, self.coef)
        except ZeroDivisionError:
            raise
        except Exception:
            return NotImplemented
        quo = self.__class__(quo, self.domain, self.window)
        rem = self.__class__(rem, self.domain, self.window)
        return quo, rem

    def __eq__(self, other):
        res = (isinstance(other, self.__class__) and
               np.all(self.domain == other.domain) and
               np.all(self.window == other.window) and
               (self.coef.shape == other.coef.shape) and
               np.all(self.coef == other.coef))
        return res

    def __ne__(self, other):
        return not self.__eq__(other)

    #
    # Extra methods.
    #

    def copy(self):
        """Return a copy.

        Returns
        -------
        new_series : series
            Copy of self.

        """
        return self.__class__(self.coef, self.domain, self.window)

    def degree(self):
        """The degree of the series.

        .. versionadded:: 1.5.0

        Returns
        -------
        degree : int
            Degree of the series, one less than the number of coefficients.

        """
        return len(self) - 1

    def cutdeg(self, deg):
        """Truncate series to the given degree.

        Reduce the degree of the series to `deg` by discarding the
        high order terms. If `deg` is greater than the current degree a
        copy of the current series is returned. This can be useful in least
        squares where the coefficients of the high degree terms may be very
        small.

        .. versionadded:: 1.5.0

        Parameters
        ----------
        deg : non-negative int
            The series is reduced to degree `deg` by discarding the high
            order terms. The value of `deg` must be a non-negative integer.

        Returns
        -------
        new_series : series
            New instance of series with reduced degree.

        """
        return self.truncate(deg + 1)

    def trim(self, tol=0):
        """Remove trailing coefficients

        Remove trailing coefficients until a coefficient is reached whose
        absolute value greater than `tol` or the beginning of the series is
        reached. If all the coefficients would be removed the series is set
        to ``[0]``. A new series instance is returned with the new
        coefficients.  The current instance remains unchanged.

        Parameters
        ----------
        tol : non-negative number.
            All trailing coefficients less than `tol` will be removed.

        Returns
        -------
        new_series : series
            New instance of series with trimmed coefficients.

        """
        coef = pu.trimcoef(self.coef, tol)
        return self.__class__(coef, self.domain, self.window)

    def truncate(self, size):
        """Truncate series to length `size`.

        Reduce the series to length `size` by discarding the high
        degree terms. The value of `size` must be a positive integer. This
        can be useful in least squares where the coefficients of the
        high degree terms may be very small.

        Parameters
        ----------
        size : positive int
            The series is reduced to length `size` by discarding the high
            degree terms. The value of `size` must be a positive integer.

        Returns
        -------
        new_series : series
            New instance of series with truncated coefficients.

        """
        isize = int(size)
        if isize != size or isize < 1:
            raise ValueError("size must be a positive integer")
        if isize >= len(self.coef):
            coef = self.coef
        else:
            coef = self.coef[:isize]
        return self.__class__(coef, self.domain, self.window)

    def convert(self, domain=None, kind=None, window=None):
        """Convert series to a different kind and/or domain and/or window.

        Parameters
        ----------
        domain : array_like, optional
            The domain of the converted series. If the value is None,
            the default domain of `kind` is used.
        kind : class, optional
            The polynomial series type class to which the current instance
            should be converted. If kind is None, then the class of the
            current instance is used.
        window : array_like, optional
            The window of the converted series. If the value is None,
            the default window of `kind` is used.

        Returns
        -------
        new_series : series
            The returned class can be of different type than the current
            instance and/or have a different domain and/or different
            window.

        Notes
        -----
        Conversion between domains and class types can result in
        numerically ill defined series.

        """
        if kind is None:
            kind = self.__class__
        if domain is None:
            domain = kind.domain
        if window is None:
            window = kind.window
        return self(kind.identity(domain, window=window))

    def mapparms(self):
        """Return the mapping parameters.

        The returned values define a linear map ``off + scl*x`` that is
        applied to the input arguments before the series is evaluated. The
        map depends on the ``domain`` and ``window``; if the current
        ``domain`` is equal to the ``window`` the resulting map is the
        identity.  If the coefficients of the series instance are to be
        used by themselves outside this class, then the linear function
        must be substituted for the ``x`` in the standard representation of
        the base polynomials.

        Returns
        -------
        off, scl : float or complex
            The mapping function is defined by ``off + scl*x``.

        Notes
        -----
        If the current domain is the interval ``[l1, r1]`` and the window
        is ``[l2, r2]``, then the linear mapping function ``L`` is
        defined by the equations::

            L(l1) = l2
            L(r1) = r2

        """
        return pu.mapparms(self.domain, self.window)

    def integ(self, m=1, k=[], lbnd=None):
        """Integrate.

        Return a series instance that is the definite integral of the
        current series.

        Parameters
        ----------
        m : non-negative int
            The number of integrations to perform.
        k : array_like
            Integration constants. The first constant is applied to the
            first integration, the second to the second, and so on. The
            list of values must less than or equal to `m` in length and any
            missing values are set to zero.
        lbnd : Scalar
            The lower bound of the definite integral.

        Returns
        -------
        new_series : series
            A new series representing the integral. The domain is the same
            as the domain of the integrated series.

        """
        off, scl = self.mapparms()
        if lbnd is None:
            lbnd = 0
        else:
            lbnd = off + scl*lbnd
        coef = self._int(self.coef, m, k, lbnd, 1./scl)
        return self.__class__(coef, self.domain, self.window)

    def deriv(self, m=1):
        """Differentiate.

        Return a series instance of that is the derivative of the current
        series.

        Parameters
        ----------
        m : non-negative int
            Find the derivative of order `m`.

        Returns
        -------
        new_series : series
            A new series representing the derivative. The domain is the same
            as the domain of the differentiated series.

        """
        off, scl = self.mapparms()
        coef = self._der(self.coef, m, scl)
        return self.__class__(coef, self.domain, self.window)

    def roots(self):
        """Return the roots of the series polynomial.

        Compute the roots for the series. Note that the accuracy of the
        roots decrease the further outside the domain they lie.

        Returns
        -------
        roots : ndarray
            Array containing the roots of the series.

        """
        roots = self._roots(self.coef)
        return pu.mapdomain(roots, self.window, self.domain)

    def linspace(self, n=100, domain=None):
        """Return x, y values at equally spaced points in domain.

        Returns the x, y values at `n` linearly spaced points across the
        domain.  Here y is the value of the polynomial at the points x. By
        default the domain is the same as that of the series instance.
        This method is intended mostly as a plotting aid.

        .. versionadded:: 1.5.0

        Parameters
        ----------
        n : int, optional
            Number of point pairs to return. The default value is 100.
        domain : {None, array_like}, optional
            If not None, the specified domain is used instead of that of
            the calling instance. It should be of the form ``[beg,end]``.
            The default is None which case the class domain is used.

        Returns
        -------
        x, y : ndarray
            x is equal to linspace(self.domain[0], self.domain[1], n) and
            y is the series evaluated at element of x.

        """
        if domain is None:
            domain = self.domain
        x = np.linspace(domain[0], domain[1], n)
        y = self(x)
        return x, y

    @classmethod
    def fit(cls, x, y, deg, domain=None, rcond=None, full=False, w=None,
        window=None):
        """Least squares fit to data.

        Return a series instance that is the least squares fit to the data
        `y` sampled at `x`. The domain of the returned instance can be
        specified and this will often result in a superior fit with less
        chance of ill conditioning.

        Parameters
        ----------
        x : array_like, shape (M,)
            x-coordinates of the M sample points ``(x[i], y[i])``.
        y : array_like, shape (M,)
            y-coordinates of the M sample points ``(x[i], y[i])``.
        deg : int or 1-D array_like
            Degree(s) of the fitting polynomials. If `deg` is a single integer
            all terms up to and including the `deg`'th term are included in the
            fit. For NumPy versions >= 1.11.0 a list of integers specifying the
            degrees of the terms to include may be used instead.
        domain : {None, [beg, end], []}, optional
            Domain to use for the returned series. If ``None``,
            then a minimal domain that covers the points `x` is chosen.  If
            ``[]`` the class domain is used. The default value was the
            class domain in NumPy 1.4 and ``None`` in later versions.
            The ``[]`` option was added in numpy 1.5.0.
        rcond : float, optional
            Relative condition number of the fit. Singular values smaller
            than this relative to the largest singular value will be
            ignored. The default value is len(x)*eps, where eps is the
            relative precision of the float type, about 2e-16 in most
            cases.
        full : bool, optional
            Switch determining nature of return value. When it is False
            (the default) just the coefficients are returned, when True
            diagnostic information from the singular value decomposition is
            also returned.
        w : array_like, shape (M,), optional
            Weights. If not None, the weight ``w[i]`` applies to the unsquared
            residual ``y[i] - y_hat[i]`` at ``x[i]``. Ideally the weights are
            chosen so that the errors of the products ``w[i]*y[i]`` all have
            the same variance.  When using inverse-variance weighting, use
            ``w[i] = 1/sigma(y[i])``.  The default value is None.

            .. versionadded:: 1.5.0
        window : {[beg, end]}, optional
            Window to use for the returned series. The default
            value is the default class domain

            .. versionadded:: 1.6.0

        Returns
        -------
        new_series : series
            A series that represents the least squares fit to the data and
            has the domain and window specified in the call. If the
            coefficients for the unscaled and unshifted basis polynomials are
            of interest, do ``new_series.convert().coef``.

        [resid, rank, sv, rcond] : list
            These values are only returned if ``full == True``

            - resid -- sum of squared residuals of the least squares fit
            - rank -- the numerical rank of the scaled Vandermonde matrix
            - sv -- singular values of the scaled Vandermonde matrix
            - rcond -- value of `rcond`.

            For more details, see `linalg.lstsq`.

        """
        if domain is None:
            domain = pu.getdomain(x)
        elif type(domain) is list and len(domain) == 0:
            domain = cls.domain

        if window is None:
            window = cls.window

        xnew = pu.mapdomain(x, domain, window)
        res = cls._fit(xnew, y, deg, w=w, rcond=rcond, full=full)
        if full:
            [coef, status] = res
            return cls(coef, domain=domain, window=window), status
        else:
            coef = res
            return cls(coef, domain=domain, window=window)

    @classmethod
    def fromroots(cls, roots, domain=[], window=None):
        """Return series instance that has the specified roots.

        Returns a series representing the product
        ``(x - r[0])*(x - r[1])*...*(x - r[n-1])``, where ``r`` is a
        list of roots.

        Parameters
        ----------
        roots : array_like
            List of roots.
        domain : {[], None, array_like}, optional
            Domain for the resulting series. If None the domain is the
            interval from the smallest root to the largest. If [] the
            domain is the class domain. The default is [].
        window : {None, array_like}, optional
            Window for the returned series. If None the class window is
            used. The default is None.

        Returns
        -------
        new_series : series
            Series with the specified roots.

        """
        [roots] = pu.as_series([roots], trim=False)
        if domain is None:
            domain = pu.getdomain(roots)
        elif type(domain) is list and len(domain) == 0:
            domain = cls.domain

        if window is None:
            window = cls.window

        deg = len(roots)
        off, scl = pu.mapparms(domain, window)
        rnew = off + scl*roots
        coef = cls._fromroots(rnew) / scl**deg
        return cls(coef, domain=domain, window=window)

    @classmethod
    def identity(cls, domain=None, window=None):
        """Identity function.

        If ``p`` is the returned series, then ``p(x) == x`` for all
        values of x.

        Parameters
        ----------
        domain : {None, array_like}, optional
            If given, the array must be of the form ``[beg, end]``, where
            ``beg`` and ``end`` are the endpoints of the domain. If None is
            given then the class domain is used. The default is None.
        window : {None, array_like}, optional
            If given, the resulting array must be if the form
            ``[beg, end]``, where ``beg`` and ``end`` are the endpoints of
            the window. If None is given then the class window is used. The
            default is None.

        Returns
        -------
        new_series : series
             Series of representing the identity.

        """
        if domain is None:
            domain = cls.domain
        if window is None:
            window = cls.window
        off, scl = pu.mapparms(window, domain)
        coef = cls._line(off, scl)
        return cls(coef, domain, window)

    @classmethod
    def basis(cls, deg, domain=None, window=None):
        """Series basis polynomial of degree `deg`.

        Returns the series representing the basis polynomial of degree `deg`.

        .. versionadded:: 1.7.0

        Parameters
        ----------
        deg : int
            Degree of the basis polynomial for the series. Must be >= 0.
        domain : {None, array_like}, optional
            If given, the array must be of the form ``[beg, end]``, where
            ``beg`` and ``end`` are the endpoints of the domain. If None is
            given then the class domain is used. The default is None.
        window : {None, array_like}, optional
            If given, the resulting array must be if the form
            ``[beg, end]``, where ``beg`` and ``end`` are the endpoints of
            the window. If None is given then the class window is used. The
            default is None.

        Returns
        -------
        new_series : series
            A series with the coefficient of the `deg` term set to one and
            all others zero.

        """
        if domain is None:
            domain = cls.domain
        if window is None:
            window = cls.window
        ideg = int(deg)

        if ideg != deg or ideg < 0:
            raise ValueError("deg must be non-negative integer")
        return cls([0]*ideg + [1], domain, window)

    @classmethod
    def cast(cls, series, domain=None, window=None):
        """Convert series to series of this class.

        The `series` is expected to be an instance of some polynomial
        series of one of the types supported by by the numpy.polynomial
        module, but could be some other class that supports the convert
        method.

        .. versionadded:: 1.7.0

        Parameters
        ----------
        series : series
            The series instance to be converted.
        domain : {None, array_like}, optional
            If given, the array must be of the form ``[beg, end]``, where
            ``beg`` and ``end`` are the endpoints of the domain. If None is
            given then the class domain is used. The default is None.
        window : {None, array_like}, optional
            If given, the resulting array must be if the form
            ``[beg, end]``, where ``beg`` and ``end`` are the endpoints of
            the window. If None is given then the class window is used. The
            default is None.

        Returns
        -------
        new_series : series
            A series of the same kind as the calling class and equal to
            `series` when evaluated.

        See Also
        --------
        convert : similar instance method

        """
        if domain is None:
            domain = cls.domain
        if window is None:
            window = cls.window
        return series.convert(domain, cls, window)


text:
package io.tracee.binding.cxf.interceptor;

import io.tracee.testhelper.SimpleTraceeBackend;
import io.tracee.TraceeBackend;
import io.tracee.TraceeConstants;
import org.apache.cxf.message.Exchange;
import org.apache.cxf.message.Message;
import org.apache.cxf.message.MessageImpl;
import org.junit.Before;
import org.junit.Test;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasKey;
import static org.hamcrest.Matchers.is;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;

public class IncomingRequestMessageTest {

	private static final TraceeBackend backend = SimpleTraceeBackend.createNonLoggingAllPermittingBackend();

	private TraceeRequestInInterceptor unit = new TraceeRequestInInterceptor(backend);

	private final MessageImpl message = spy(new MessageImpl());

	@Before
	public void onSetup() throws Exception {
		backend.clear();

		when(message.getExchange()).thenReturn(mock(Exchange.class));
		when(message.getExchange().get(eq(Message.REST_MESSAGE))).thenReturn(Boolean.TRUE);
	}

	@Test
	public void shouldHandleMessageWithoutHeader() {
		unit.handleMessage(message);
	}

	@Test
	public void shouldHandleMessageWithoutTraceeHeader() {
		final Map<String, List<String>> headers = new HashMap<String, List<String>>();
		final String context = "myContext";
		headers.put(TraceeConstants.TPIC_HEADER, Collections.singletonList(context));
		message.put(Message.PROTOCOL_HEADERS, headers);
		unit.handleMessage(message);
		assertThat(backend.copyToMap(), hasKey(TraceeConstants.INVOCATION_ID_KEY));
	}

	@Test
	public void generateInvocationIdUponRequest() {
		unit.handleMessage(message);
		assertThat(backend.copyToMap(), hasKey(TraceeConstants.INVOCATION_ID_KEY));
	}

	@Test
	public void onIncomingRequestMessagesIamNotTheRequestor() {
		when(message.get(eq(Message.REQUESTOR_ROLE))).thenReturn(Boolean.FALSE);
		assertThat(unit.shouldHandleMessage(message), is(true));
	}
}


text:
user_agent=""
client_id=""
client_secret=""
refresh_token=""
subreddit=""
remote_config_path=""
message_subject=""
ban_reason=""
ban_message_subject=""
ban_message_body=""
shame_message_subject=""
shame_message_body=""


text:
<?php

/**
 * Created by PhpStorm.
 * User: maxim
 * Date: 02/05/2017
 * Time: 15:14
 */
namespace AppBundle\Form;
use AppBundle\Entity\Categories;
use Doctrine\DBAL\Types\IntegerType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\TextAreaType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use AppBundle\Entity\User;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
class AjoutCatType extends AbstractType

{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name', TextType::class)

        ;
    }
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array('data_class'=>Categories::class));
    }

}


text:
/* 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.
 */
package org.flowable.batch.api;

import java.util.List;

/**
 * Service which provides access to batch entities.
 *
 * @author Tijs Rademakers
 */
public interface BatchService {

    Batch getBatch(String id);

    List<Batch> getAllBatches();

    List<Batch> findBatchesBySearchKey(String searchKey);

    List<Batch> findBatchesByQueryCriteria(BatchQuery batchQuery);

    long findBatchCountByQueryCriteria(BatchQuery batchQuery);

    BatchBuilder createBatchBuilder();

    void insertBatch(Batch batch);

    Batch updateBatch(Batch batch);

    void deleteBatch(String batchId);

    BatchPart getBatchPart(String id);

    List<BatchPart> findBatchPartsByBatchId(String batchId);

    List<BatchPart> findBatchPartsByBatchIdAndStatus(String batchId, String status);

    List<BatchPart> findBatchPartsByScopeIdAndType(String scopeId, String scopeType);

    BatchPart createBatchPart(Batch batch, String status, String scopeId, String subScopeId, String scopeType);

    BatchPart completeBatchPart(String batchPartId, String status, String resultJson);

    Batch completeBatch(String batchId, String status);

}


text:
This repository contains the legacy ESLintRC configuration file format for ESLint.

**Note:** This package is not intended for use outside of the ESLint ecosystem. It is ESLint-specific and not intended for use in other programs.

## Usage

You can install the package as follows:

```
npm install @eslint/eslintrc --save-dev

# or

yarn add @eslint/eslintrc -D
```

## License

MIT License


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>MItoDancer</groupId>
    <artifactId>MitoDancer</artifactId>
    <version>1.0-SNAPSHOT</version>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <dependency>
            <groupId>org.jetbrains</groupId>
            <artifactId>annotations-java5</artifactId>
            <version>15.0</version>
        </dependency>
    </dependencies>

</project>


text:
package space.wxh.pureweather.util;

/**
 * Created by howord on 15-10-3.
 */
public interface HttpCallbackListener {
    void onFinish(String response);
    void onError(Exception e);
}