text:
#include <winsock2.h>
#include <wininet.h>
#include <stdio.h>
#include <errno.h>

#include "winetest.h"

#define USER_AGENT  "Winetest Shell"
#define SERVER_NAME "test.winehq.org"
#define URL_PATH "/submit"
#define SEP "--8<--cut-here--8<--"
#define CONTENT_HEADERS "Content-Type: multipart/form-data; boundary=\"" SEP "\"\r\n" \
                        "Content-Length: %u\r\n\r\n"
static const char body1[] = "--" SEP "\r\n"
    "Content-Disposition: form-data; name=\"reportfile\"; filename=\"%s\"\r\n"
    "Content-Type: application/octet-stream\r\n\r\n";
static const char body2[] = "\r\n--" SEP "\r\n"
    "Content-Disposition: form-data; name=\"submit\"\r\n\r\n"
    "Upload File\r\n"
    "--" SEP "--\r\n";

static SOCKET
open_http (const char *server)
{
    WSADATA wsad;
    struct sockaddr_in sa;
    SOCKET s;

    report (R_STATUS, "Opening HTTP connection to %s", server);
    if (WSAStartup (MAKEWORD (2,2), &wsad)) return INVALID_SOCKET;

    sa.sin_family = AF_INET;
    sa.sin_port = htons (80);
    sa.sin_addr.s_addr = inet_addr (server);
    if (sa.sin_addr.s_addr == INADDR_NONE) {
        struct hostent *host = gethostbyname (server);
        if (!host) {
            report (R_ERROR, "Hostname lookup failed for %s", server);
            goto failure;
        }
        sa.sin_addr.s_addr = ((struct in_addr *)host->h_addr)->s_addr;
    }
    s = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (s == INVALID_SOCKET) {
        report (R_ERROR, "Can't open network socket: %d",
                WSAGetLastError ());
        goto failure;
    }
    if (!connect (s, (struct sockaddr*)&sa, sizeof (struct sockaddr_in)))
        return s;

    report (R_ERROR, "Can't connect: %d", WSAGetLastError ());
    closesocket (s);
 failure:
    WSACleanup ();
    return INVALID_SOCKET;
}

static int
close_http (SOCKET s)
{
    int ret;

    ret = closesocket (s);
    return (WSACleanup () || ret);
}

static int
send_buf (SOCKET s, const char *buf, size_t length)
{
    int sent;

    while (length > 0) {
        sent = send (s, buf, length, 0);
        if (sent == SOCKET_ERROR) return 1;
        buf += sent;
        length -= sent;
    }
    return 0;
}

static int
send_str (SOCKET s, ...)
{
    va_list ap;
    char *p;
    int ret;
    size_t len;

    va_start (ap, s);
    p = vstrmake (&len, ap);
    va_end (ap);
    if (!p) return 1;
    ret = send_buf (s, p, len);
    heap_free (p);
    return ret;
}

static int
send_file_direct (const char *name)
{
    SOCKET s;
    HANDLE file;
#define BUFLEN 8192
    char buffer[BUFLEN+1];
    DWORD bytes_read, filesize;
    size_t total, count;
    char *str;
    int ret;

    /* RFC 2616 */
    static const char head[] = "POST " URL_PATH " HTTP/1.0\r\n"
        "Host: " SERVER_NAME "\r\n"
        "User-Agent: " USER_AGENT "\r\n"
        CONTENT_HEADERS
        "\r\n";

    s = open_http (SERVER_NAME);
    if (s == INVALID_SOCKET) return 1;

    file = CreateFileA( name, GENERIC_READ,
                        FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
                        NULL, OPEN_EXISTING, 0, NULL );

    if ((file == INVALID_HANDLE_VALUE) &&
        (GetLastError() == ERROR_INVALID_PARAMETER)) {
        /* FILE_SHARE_DELETE not supported on win9x */
        file = CreateFileA( name, GENERIC_READ,
                            FILE_SHARE_READ | FILE_SHARE_WRITE,
                            NULL, OPEN_EXISTING, 0, NULL );
    }
    if (file == INVALID_HANDLE_VALUE)
    {
        report (R_WARNING, "Can't open file '%s': %u", name, GetLastError());
        goto abort1;
    }
    filesize = GetFileSize( file, NULL );
    if (filesize > 1.5*1024*1024) {
        report (R_WARNING,
                "File too big (%.1f MB > 1.5 MB); submitting partial report.",
                filesize/1024.0/1024);
        filesize = (DWORD) 1.5*1024*1024;
    }

    report (R_STATUS, "Sending header");
    str = strmake (&total, body1, name);
    ret = send_str (s, head, filesize + total + sizeof body2 - 1) ||
        send_buf (s, str, total);
    heap_free (str);
    if (ret) {
        report (R_WARNING, "Error sending header: %d, %d",
                errno, WSAGetLastError ());
        goto abort2;
    }

    report (R_STATUS, "Sending %u bytes of data", filesize);
    report (R_PROGRESS, 2, filesize);
    total = 0;
    while (total < filesize && ReadFile( file, buffer, BUFLEN/2, &bytes_read, NULL )) {
        if (aborting) goto abort2;
        if (!bytes_read) break;
        total += bytes_read;
        if (total > filesize) bytes_read -= total - filesize;
        if (send_buf (s, buffer, bytes_read)) {
            report (R_WARNING, "Error sending body: %d, %d",
                    errno, WSAGetLastError ());
            goto abort2;
        }
        report (R_DELTA, bytes_read, "Network transfer: In progress");
    }
    CloseHandle( file );

    if (send_buf (s, body2, sizeof body2 - 1)) {
        report (R_WARNING, "Error sending trailer: %d, %d",
                errno, WSAGetLastError ());
        goto abort1;
    }
    report (R_DELTA, 0, "Network transfer: Done");

    total = 0;
    while ((bytes_read = recv (s, buffer+total, BUFLEN-total, 0))) {
        if ((signed)bytes_read == SOCKET_ERROR) {
            report (R_WARNING, "Error receiving reply: %d, %d",
                    errno, WSAGetLastError ());
            goto abort1;
        }
        total += bytes_read;
        if (total == BUFLEN) {
            report (R_WARNING, "Buffer overflow");
            goto abort1;
        }
    }
    if (close_http (s)) {
        report (R_WARNING, "Error closing connection: %d, %d",
                errno, WSAGetLastError ());
        return 1;
    }

    str = strmake (&count, "Received %s (%d bytes).\n",
                   name, filesize);
    ret = total < count || memcmp (str, buffer + total - count, count) != 0;
    heap_free (str);
    if (ret) {
        buffer[total] = 0;
        str = strstr (buffer, "\r\n\r\n");
        if (!str) str = buffer;
        else str = str + 4;
        report (R_ERROR, "Can't submit logfile '%s'. "
                "Server response: %s", name, str);
    }
    return ret;

 abort2:
    CloseHandle( file );
 abort1:
    close_http (s);
    return 1;
}

static int
send_file_wininet (const char *name)
{
    int ret = 0;
    HMODULE wininet_mod = NULL;
    HINTERNET (WINAPI *pInternetOpen)(LPCSTR agent, DWORD access_type, LPCSTR proxy_name, LPCSTR proxy_bypass, DWORD flags);
    HINTERNET (WINAPI *pInternetConnect)(HINTERNET session, LPCSTR server_name, INTERNET_PORT server_port, LPCSTR username, LPCSTR password, DWORD service, DWORD flags, DWORD_PTR *context);
    HINTERNET (WINAPI *pHttpOpenRequest)(HINTERNET connection, LPCSTR verb, LPCSTR object_name, LPCSTR version, LPCSTR referer, LPCSTR *accept_types, DWORD flags, DWORD_PTR context);
    BOOL (WINAPI *pHttpSendRequestEx)(HINTERNET request, LPINTERNET_BUFFERSA buffers_in, LPINTERNET_BUFFERSA buffers_out, DWORD flags, DWORD_PTR context);
    BOOL (WINAPI *pInternetWriteFile)(HINTERNET file, LPCVOID buffer, DWORD number_of_bytes_to_write, LPDWORD number_of_bytes_written);
    BOOL (WINAPI *pHttpEndRequest)(HINTERNET request, LPINTERNET_BUFFERSA buffers_out, DWORD flags, DWORD_PTR context);
    BOOL (WINAPI *pInternetReadFile)(HINTERNET file, LPCVOID buffer, DWORD number_of_bytes_to_read, LPDWORD number_of_bytes_read);
    BOOL (WINAPI *pInternetCloseHandle)(HINTERNET Handle) = NULL;
    HANDLE file = INVALID_HANDLE_VALUE;
    DWORD filesize, bytes_read, bytes_written;
    size_t total, count;
    char *str = NULL;
    HINTERNET session = NULL;
    HINTERNET connection = NULL;
    HINTERNET request = NULL;
    INTERNET_BUFFERSA buffers_in = { 0 };
    char buffer[BUFLEN+1];

    static const char extra_headers[] =
        CONTENT_HEADERS;

    wininet_mod = LoadLibraryA("wininet.dll");
    if (wininet_mod == NULL)
        goto done;
    pInternetOpen = (void *)GetProcAddress(wininet_mod, "InternetOpenA");
    pInternetConnect = (void *)GetProcAddress(wininet_mod, "InternetConnectA");
    pHttpOpenRequest = (void *)GetProcAddress(wininet_mod, "HttpOpenRequestA");
    pHttpSendRequestEx = (void *)GetProcAddress(wininet_mod, "HttpSendRequestExA");
    pInternetWriteFile = (void *)GetProcAddress(wininet_mod, "InternetWriteFile");
    pHttpEndRequest = (void *)GetProcAddress(wininet_mod, "HttpEndRequestA");
    pInternetReadFile = (void *)GetProcAddress(wininet_mod, "InternetReadFile");
    pInternetCloseHandle = (void *)GetProcAddress(wininet_mod, "InternetCloseHandle");
    if (pInternetOpen == NULL || pInternetConnect == NULL || pHttpOpenRequest == NULL || pHttpSendRequestEx == NULL || pHttpEndRequest == NULL ||
        pInternetWriteFile == NULL || pInternetReadFile == NULL || pInternetCloseHandle == NULL) {
        goto done;
    }

    ret = 1;

    file = CreateFileA( name, GENERIC_READ,
                        FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
                        NULL, OPEN_EXISTING, 0, NULL );

    if ((file == INVALID_HANDLE_VALUE) &&
        (GetLastError() == ERROR_INVALID_PARAMETER)) {
        /* FILE_SHARE_DELETE not supported on win9x */
        file = CreateFileA( name, GENERIC_READ,
                            FILE_SHARE_READ | FILE_SHARE_WRITE,
                            NULL, OPEN_EXISTING, 0, NULL );
    }
    if (file == INVALID_HANDLE_VALUE) {
        report (R_WARNING, "Can't open file '%s': %u", name, GetLastError());
        goto done;
    }

    filesize = GetFileSize( file, NULL );
    if (filesize > 1.5*1024*1024) {
        report (R_WARNING,
                "File too big (%.1f MB > 1.5 MB); submitting partial report.",
                filesize/1024.0/1024);
        filesize = 1.5*1024*1024;
    }

    report (R_STATUS, "Opening HTTP connection to " SERVER_NAME);
    session = pInternetOpen (USER_AGENT, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
    if (session == NULL) {
        report (R_WARNING, "Unable to open connection, error %u", GetLastError());
        goto done;
    }
    connection = pInternetConnect (session, SERVER_NAME, INTERNET_DEFAULT_HTTP_PORT, "", "", INTERNET_SERVICE_HTTP, 0, 0);
    if (connection == NULL) {
        report (R_WARNING, "Unable to connect, error %u", GetLastError());
        goto done;
    }
    request = pHttpOpenRequest (connection, "POST", URL_PATH, NULL, NULL, NULL,
                                INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_NO_COOKIES | INTERNET_FLAG_NO_UI |
                                INTERNET_FLAG_PRAGMA_NOCACHE | INTERNET_FLAG_RELOAD, 0);
    if (request == NULL) {
        report (R_WARNING, "Unable to open request, error %u", GetLastError());
        goto done;
    }

    report (R_STATUS, "Sending request");
    str = strmake (&total, body1, name);
    memset(&buffers_in, 0, sizeof(INTERNET_BUFFERSA));
    buffers_in.dwStructSize = sizeof(INTERNET_BUFFERSA);
    buffers_in.dwBufferTotal = filesize + total + sizeof body2 - 1;
    buffers_in.lpcszHeader = strmake (&count, extra_headers, buffers_in.dwBufferTotal);
    buffers_in.dwHeadersLength = count;
    if (! pHttpSendRequestEx(request, &buffers_in, NULL, 0, 0)) {
        report (R_WARNING, "Unable to send request, error %u", GetLastError());
        goto done;
    }

    if (! pInternetWriteFile(request, str, total, &bytes_written) || bytes_written != total) {
        report (R_WARNING, "Unable to write body data, error %u", GetLastError());
        goto done;
    }

    report (R_STATUS, "Sending %u bytes of data", filesize);
    report (R_PROGRESS, 2, filesize);
    total = 0;
    while (total < filesize && ReadFile( file, buffer, BUFLEN/2, &bytes_read, NULL )) {
        if (aborting) goto done;
        if (!bytes_read) break;
        total += bytes_read;
        if (total > filesize) bytes_read -= total - filesize;
        if (! pInternetWriteFile (request, buffer, bytes_read, &bytes_written) || bytes_written != bytes_read) {
            report (R_WARNING, "Error sending body: %u", GetLastError ());
            goto done;
        }
        report (R_DELTA, bytes_read, "Network transfer: In progress");
    }

    if (! pInternetWriteFile(request, body2, sizeof body2 - 1, &bytes_written) || bytes_written != sizeof body2 - 1) {
        report (R_WARNING, "Unable to write final body data, error %u", GetLastError());
        goto done;
    }
    if (! pHttpEndRequest(request, NULL, 0, 0)) {
        report (R_WARNING, "Unable to end request, error %u", GetLastError());
        goto done;
    }
    report (R_DELTA, 0, "Network transfer: Done");

    total = 0;
    do
    {
        if (! pInternetReadFile(request, buffer+total, BUFLEN-total, &bytes_read)) {
            report (R_WARNING, "Error receiving reply: %u", GetLastError ());
            goto done;
        }
        total += bytes_read;
        if (total == BUFLEN) {
            report (R_WARNING, "Buffer overflow");
            goto done;
        }
    }
    while (bytes_read != 0);

    heap_free (str);
    str = strmake (&count, "Received %s (%d bytes).\n",
                   name, filesize);
    if (total < count || memcmp (str, buffer + total - count, count) != 0) {
        buffer[total] = 0;
        report (R_ERROR, "Can't submit logfile '%s'. "
                "Server response: %s", name, buffer);
    }

 done:
    if (buffers_in.lpcszHeader != NULL)
        heap_free((void *) buffers_in.lpcszHeader);
    if (str != NULL)
        heap_free (str);
    if (pInternetCloseHandle != NULL && request != NULL)
        pInternetCloseHandle (request);
    if (pInternetCloseHandle != NULL && connection != NULL)
        pInternetCloseHandle (connection);
    if (pInternetCloseHandle != NULL && session != NULL)
        pInternetCloseHandle (session);
    if (file != INVALID_HANDLE_VALUE)
        CloseHandle (file);
    if (wininet_mod != NULL)
        FreeLibrary (wininet_mod);

    return ret;
}

int
send_file (const char *name)
{
    return send_file_wininet( name ) || send_file_direct( name );
}


text:
import Vue from 'vue'
import VueRouter from 'vue-router'
import Register from '@/components/Register'
import Login from '@/components/Login'
import Songs from '@/components/Songs/Index'
import CreateSong from '@/components/CreateSong'
import ViewSong from '@/components/ViewSong/Index'
import EditSong from '@/components/EditSong'

import PasswordRecovery from '@/components/PasswordRecovery'
import AccountCodeVerification from '@/components/AccountCodeVerification'

import Logout from '@/components/globals/Logout'

import Start from '@/components/orcapp/Start'
import Resume from '@/components/orcapp/Resume'

import Emailer from '@/components/MailerManager/Emailer'
import EmailerCreate from '@/components/MailerManager/EmailerCreate'
import EmailerEdit from '@/components/MailerManager/EmailerEdit'
import EmailerRemove from '@/components/MailerManager/EmailerRemove'
import CustomerProfile from '@/components/appcomponents/CustomerProfile'

import vueAuthInstance from '../services/auth.js'
import AccountService from '../services/AccountService.js'
import store from '../store'
Vue.use(VueRouter)

const routes = [
  {
    path: '/start',
    name: 'start',
    component: Start,
    meta: { auth: false, title: 'Login to existing account' }
  },
  {
    path: '/register',
    name: 'register',
    component: Register,
    meta: { auth: false, title: 'Login to existing account' }
  },
  {
    path: '/login',
    name: 'login',
    component: Login,
    meta: { auth: false, title: 'Login to existing account' }
  },
  {
    path: '/passwordRecovery',
    name: 'passwordRecovery',
    component: PasswordRecovery,
    meta: { auth: false, title: 'Password Recovery to existing account' },
    props: true
  },
  {
    path: '/AccountCodeVerification',
    name: 'AccountCodeVerification',
    component: AccountCodeVerification,
    meta: { auth: true, title: 'Account Code Verification' }
  },
  {
    path: '/CustomerProfile',
    name: 'CustomerProfile',
    component: CustomerProfile,
    meta: { auth: true, title: 'Customer Profile Manager' }
  },
  {
    path: '/songs',
    name: 'songs',
    component: Songs
  },
  {
    path: '/songs/create',
    name: 'songs-create',
    component: CreateSong
  },
  {
    path: '/songs/:songId',
    name: 'song',
    component: ViewSong
  },
  {
    path: '/songs/:songId/edit',
    name: 'song-edit',
    component: EditSong
  },
  {
    path: '/resume',
    name: 'resume',
    component: Resume,
    meta: { auth: true, title: 'Login to existing account' }
  },
  {
    path: '/emailer/profiles',
    name: 'emailer-profiles',
    component: Emailer,
    meta: { auth: true, title: 'Login to existing account' }
  },
  {
    path: '/emailer/create',
    name: 'emailer-create',
    component: EmailerCreate,
    meta: { auth: true, title: 'Login to existing account' }
  },
  {
    path: '/emailer/edit',
    name: 'emailer-edit',
    component: EmailerEdit,
    meta: { auth: true, title: 'Login to existing account' }
  },
  {
    path: '/emailer/:profileid/remove',
    name: 'emailer-remove',
    component: EmailerRemove,
    meta: { auth: true, title: 'Login to existing account' }

  },
  {
    path: '/logout',
    name: 'logout',
    component: Logout,
    meta: { auth: true, title: 'Login to existing account' }
  },
  {
    path: '/emailer',
    name: 'emailer',
    redirect: '/emailer/profiles',
    meta: { auth: true, title: 'Login to existing account' }
  },
  {
    path: '*',
    redirect: vueAuthInstance.isAuthenticated() ? '/resume' : '/start',
    meta: { auth: false, title: 'Login to existing account' }
  }
]

const vueRouterInstance = new VueRouter({
  mode: 'history',
  routes, // short for routes: routes
  linkActiveClass: 'active'
})

function redirectLogin () {
  // vueRouterInstance.push({ name: 'login' })
  // return next('/login')
  if (store) {
    store.dispatch('auth/LOCAL_LOGOUT', {})
  }
  location.href = '/login'
}
function redirectAccountCodeVerification () {
  // vueRouterInstance.push({ name: 'login' })
  // return next('/login')
  location.href = '/AccountCodeVerification'
}

vueRouterInstance.beforeEach(async function (to, from, next) {
  debugger
  let result = null
  try {
    if (to.meta && to.meta.auth && to.path !== '/AccountCodeVerification') {
      if (vueAuthInstance.isAuthenticated()) {
        result = await AccountService.checkAccountStatus(vueAuthInstance)
        if (result) {
          const {as, ns} = result.data.accountStatus
          if ((as === 10000 && ns === 11000) || (as === 5000 && ns === 5020)) {
            result = true
            if (as === 10000 && ns === 11000) {
              result = await AccountService.generateAccountCodeVerification(vueAuthInstance)
            }
            if (result) {
              redirectAccountCodeVerification() // redirect to code validator
            }
            return false
          } else if (as === 101010 && ns === 101010) {
            return next()
          } else if (as === 20000 && ns === 21000) {
            var user = localStorage.getItem('userProfile')
            if (user) {
              user = JSON.parse(user)
              store.dispatch('auth/LOCAL_LOGOUT', {})
              vueRouterInstance.push({name: 'passwordRecovery', params: {state: 21000, email: user.email}})
              return next()
            }
          }
        }
      }
      throw new Error('Account Code Verification need is authenticated..')
    }
    if (to.path === '/AccountCodeVerification' && !vueAuthInstance.isAuthenticated()) {
      throw new Error('Account Code Verification need is authenticated..')
    }
    return next()
  } catch (error) {
    redirectLogin()
    return next(false)
  }
})
export default vueRouterInstance

redpajama_set_name: RedPajamaGithub


text:
namespace gfx {
class Rect;
}

namespace autofill {

class AutofillPopupController;

// A suggestion view that acts as an alternative to the field-attached popup
// window. This view appears above the keyboard and spans the width of the
// screen, condensing rather than overlaying the content area. Enable via
// --enable-autofill-keyboard-accessory-view.
class AutofillKeyboardAccessoryView : public AutofillPopupView {
 public:
  explicit AutofillKeyboardAccessoryView(AutofillPopupController* controller);

  // --------------------------------------------------------------------------
  // Methods called from Java via JNI
  // --------------------------------------------------------------------------
  // Called when an autofill item was selected.
  void SuggestionSelected(JNIEnv* env, jobject obj, jint list_index);

  void ViewDismissed(JNIEnv* env, jobject obj);

  static bool RegisterAutofillKeyboardAccessoryView(JNIEnv* env);

 protected:
  // AutofillPopupView implementation.
  void Show() override;
  void Hide() override;
  void InvalidateRow(size_t row) override;
  void UpdateBoundsAndRedrawPopup() override;

 private:
  ~AutofillKeyboardAccessoryView() override;

  AutofillPopupController* controller_;  // weak.

  // The corresponding java object.
  base::android::ScopedJavaGlobalRef<jobject> java_object_;

  DISALLOW_COPY_AND_ASSIGN(AutofillKeyboardAccessoryView);
};

}  // namespace autofill

#endif  // CHROME_BROWSER_UI_ANDROID_AUTOFILL_AUTOFILL_KEYBOARD_ACCESSORY_VIEW_H_


text:
App.TemperatureChangeInTimeController = Ember.ObjectController.extend({
	needs: ['termotaxisInterval','interval'],

	updateInitial: function(){
		var slider = this.get('model.temperatureInitialSlider');
		if(slider){
			slider.setValue(parseFloat(this.get('model.initialTemperature')));
		}
	}.observes('model.initialTemperature'),

	updateFinal: function(){
		var slider = this.get('model.temperatureFinalSlider');
		if(slider){
			slider.setValue(parseFloat(this.get('model.finalTemperature')));
		}
	}.observes('model.finalTemperature'),

});


text:
suite('Dia::SharedFeatures') do

  suite('RubyBlock') do

    suite('#exit_status') do

      setup do
        @result = nil
      end

      exercise('#run is called, exits process with status of 10. ') do
        sandbox = Dia::RubyBlock.new(Dia::Profiles::NO_INTERNET) { exit(10) }
        sandbox.run
        @result = sandbox.exit_status
      end

      verify('#exit_status returns 10') do
        @result == 10
      end

      exercise('Neither #run or #run_nonblock has been called. ') do
        sandbox = Dia::RubyBlock.new(Dia::Profiles::NO_INTERNET) { }
        @result = sandbox.exit_status
      end

      verify('#exit_status returns nil') do
        @result == nil
      end

    end

    suite('#terminate') do

      setup do
        @result  = nil
        @sandbox = Dia::RubyBlock.new(Dia::Profiles::NO_OS_SERVICES) { $stdin.gets }
      end

      exercise('#run_nonblock is called, blocking IO performed, #terminate sent to process. ') do
        @sandbox.run_nonblock
        @result = @sandbox.terminate
      end

      verify('#terminate returns 1.') do
        @result == 1
      end

      exercise('#run_nonblock is called, blocking IO performed, #terminate sent to process. ') do
        @sandbox.run_nonblock
        @sandbox.terminate
        @result = @sandbox.exit_status
      end

      verify('#exit_status returns nil, or a Process PID(PID) as a Fixnum.') do
        @result == nil || @result.class == Fixnum
      end

      exercise('#run_nonblock is called, blocking IO is performed, #terminate sent to process') do
        @sandbox.run_nonblock
        @sandbox.terminate
      end

      verify('#running? verifies the process is dead') do
        @sandbox.running? == false
      end

      exercise('Neither #run or #run_nonblock has been called. ') do
        sandbox = Dia::RubyBlock.new(Dia::Profiles::NO_INTERNET) { }
        @result = sandbox.terminate
      end

      verify('#terminate returns nil') do
        @result == nil
      end

    end

    suite('#running?') do

      setup do
        @result = nil
      end

      exercise('#run_nonblock is called, spawned process sleeps. ') do
        sandbox = Dia::RubyBlock.new(Dia::Profiles::NO_INTERNET) { sleep(10) }
        sandbox.run_nonblock
        @result = sandbox.running?
        sandbox.terminate
      end

      verify('#running? returns true') do
        @result == true
      end

      exercise('#run is called, process exits immediately. ') do
        sandbox = Dia::RubyBlock.new(Dia::Profiles::NO_INTERNET) { exit }
        sandbox.run
        @result = sandbox.running?
      end

      verify('#running? returns false') do
        @result == false
      end

      exercise('Neither #run or #run_nonblock has been called. ') do
        sandbox = Dia::RubyBlock.new(Dia::Profiles::NO_INTERNET) { }
        @result = sandbox.running?
      end

      verify('#running? returns nil') do
        @result == nil
      end

    end

  end

  suite('Application') do

    suite('#running?') do

      setup do
        @result = nil
      end

      exercise('#run_nonblock is called, spawned process sleeps. ') do
        sandbox = Dia::Application.new(Dia::Profiles::NO_INTERNET, "sleep 10")
        sandbox.run_nonblock
        @result = sandbox.running?
        sandbox.terminate
      end

      verify('#running? returns true') do
        @result == true
      end

      exercise('#run is called, process exits immediately. ') do
        sandbox = Dia::Application.new(Dia::Profiles::NO_INTERNET, "sleep 0")
        sandbox.run
        @result = sandbox.running?
      end

      verify('#running? returns false') do
        @result == false
      end

      exercise('Neither #run or #run_nonblock has been called. ') do
        sandbox = Dia::Application.new(Dia::Profiles::NO_INTERNET, "")
        @result = sandbox.running?
      end

      verify('#running? returns nil') do
        @result == nil
      end

    end

    suite('#terminate') do

      setup do
        @result  = nil
        @sandbox = Dia::Application.new(Dia::Profiles::NO_INTERNET, "sleep 10000")
      end

      exercise('#run_nonblock is called, blocking operation performed, ' \
               '#terminate sent to process. ') do
        @sandbox.run_nonblock
        @result = @sandbox.terminate
      end

      verify('#terminate returns 1.') do
        @result == 1
      end

      exercise('#run_nonblock is called, blocking operation performed, ' \
               '#terminate sent to process. ') do
        @sandbox.run_nonblock
        @sandbox.terminate
        @result = @sandbox.exit_status
      end

      verify('#exit_status returns nil, or a Process PID(PID) as a Fixnum.') do
        @result == nil || @result.class == Fixnum
      end

      exercise('#run_nonblock is called, blocking operation is performed, ' \
               '#terminate sent to process') do
        @sandbox.run_nonblock
        @sandbox.terminate
      end

      verify('#running? verifies the process is dead') do
        @sandbox.running? == false
      end

      exercise('Neither #run or #run_nonblock has been called. ') do
        sandbox = Dia::Application.new(Dia::Profiles::NO_INTERNET, "sleep 0")
        @result = sandbox.terminate
      end

      verify('#terminate returns nil') do
        @result == nil
      end

    end

    suite('#exit_status') do

      setup do
        @result = nil
      end

      exercise('#run is called, exits process with status of 10. ') do
        sandbox = Dia::Application.new(Dia::Profiles::NO_INTERNET, "ruby -e 'exit 10'")
        sandbox.run
        @result = sandbox.exit_status
      end

      verify('#exit_status returns 10') do
        @result == 10
      end

      exercise('Neither #run or #run_nonblock has been called. ') do
        sandbox = Dia::Application.new(Dia::Profiles::NO_INTERNET, "")
        @result = sandbox.exit_status
      end

      verify('#exit_status returns nil') do
        @result == nil
      end

    end

  end

end


text:
<?php

namespace Acme\IndexBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class DefaultController extends Controller
{

    public function indexAction()
    {
        if( $this->container->get('security.context')->isGranted('IS_AUTHENTICATED_FULLY') ){
            return $this->redirect("/home");
        }
        return $this->redirect("/login");
    }
}


text:
import datetime
import base64
import binascii
import logging
import socket
import json
import time

from pajbot.web.utils import requires_level
from pajbot.models.user import User
from pajbot.models.command import Command, CommandManager
from pajbot.models.module import ModuleManager, Module
from pajbot.models.timer import Timer
from pajbot.models.banphrase import Banphrase
from pajbot.models.pleblist import PleblistSong
from pajbot.models.pleblist import PleblistSongInfo
from pajbot.models.pleblist import PleblistManager
from pajbot.models.stream import Stream
from pajbot.models.db import DBManager
from pajbot.models.sock import SocketClientManager

import requests
from flask import Blueprint
from flask import jsonify
from flask import make_response
from flask import request
from flask import redirect
from flask import abort
from flask.ext.scrypt import generate_password_hash
from flask.ext.scrypt import check_password_hash
from sqlalchemy import func
from sqlalchemy import and_

from functools import wraps, update_wrapper

page = Blueprint('api', __name__)
config = None

sqlconn = False

log = logging.getLogger('pajbot')

def nocache(view):
    @wraps(view)
    def no_cache(*args, **kwargs):
        response = make_response(view(*args, **kwargs))
        response.headers['Last-Modified'] = datetime.datetime.now()
        response.headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0, max-age=0'
        response.headers['Pragma'] = 'no-cache'
        response.headers['Expires'] = '-1'
        return response

    return update_wrapper(no_cache, view)

@page.route('/api/v1/user/<username>')
def get_user(username):
    session = DBManager.create_session()
    user = session.query(User).filter_by(username=username).one_or_none()
    if user is None:
        return make_response(jsonify({'error': 'Not found'}), 404)

    rank = session.query(func.Count(User.id)).filter(User.points > user.points).one()
    rank = rank[0] + 1
    session.close()
    if user:
        accessible_data = {
                'id': user.id,
                'username': user.username,
                'username_raw': user.username_raw,
                'points': user.points,
                'rank': rank,
                'level': user.level,
                'last_seen': user.last_seen,
                'last_active': user.last_active,
                'subscriber': user.subscriber,
                'num_lines': user.num_lines,
                'minutes_in_chat_online': user.minutes_in_chat_online,
                'minutes_in_chat_offline': user.minutes_in_chat_offline,
                'banned': user.banned,
                'ignored': user.ignored,
                }
        return jsonify(accessible_data)

    return make_response(jsonify({'error': 'Not found'}), 404)

@page.route('/api/v1/pleblist/list')
def pleblist_list():
    with DBManager.create_session_scope() as session:
        current_stream = session.query(Stream).filter_by(ended=False).order_by(Stream.stream_start).first()
        if current_stream is None:
            return make_response(jsonify({'error': 'Stream offline'}), 400)

        songs = session.query(PleblistSong).filter(PleblistSong.stream_id == current_stream.id, PleblistSong.date_played.is_(None)).all()
        payload = {
                '_total': len(songs),
                'songs': [song.jsonify() for song in songs],
                }

        return jsonify(payload)

@page.route('/api/v1/pleblist/list/after/<song_id>')
@nocache
def pleblist_list_after(song_id):
    with DBManager.create_session_scope() as session:
        current_stream = session.query(Stream).filter_by(ended=False).order_by(Stream.stream_start).first()
        if current_stream is None:
            return make_response(jsonify({'error': 'Stream offline'}), 400)

        songs = session.query(PleblistSong).filter(and_(PleblistSong.stream_id == current_stream.id, PleblistSong.date_played.is_(None), PleblistSong.id > song_id)).all()

        payload = {
                '_total': len(songs),
                'songs': [song.jsonify() for song in songs],
                }

        return jsonify(payload)

@page.route('/api/v1/pleblist/list/<stream_id>')
def pleblist_list_by_stream(stream_id):
    with DBManager.create_session_scope() as session:
        songs = session.query(PleblistSong).filter_by(stream_id=stream_id).all()

        payload = {
                '_total': len(songs),
                'songs': [song.jsonify() for song in songs],
                }

        return jsonify(payload)

@page.route('/api/v1/pleblist/add', methods=['POST', 'GET'])
def pleblist_add():
    if not request.method == 'POST':
        return make_response(jsonify({'error': 'Invalid request method'}), 405)
    if 'youtube_id' not in request.form:
        return make_response(jsonify({'error': 'Missing data youtube_id'}), 400)
    if 'password' not in request.form:
        return make_response(jsonify({'error': 'Missing data password'}), 400)
    salted_password = generate_password_hash(config['web']['pleblist_password'], config['web']['pleblist_password_salt'])
    try:
        user_password = base64.b64decode(request.form['password'])
    except binascii.Error:
        return make_response(jsonify({'error': 'Invalid data password'}), 400)
    if not user_password == salted_password:
        return make_response(jsonify({'error': 'Invalid password'}), 401)

    with DBManager.create_session_scope() as session:
        youtube_id = request.form['youtube_id']
        current_stream = session.query(Stream).filter_by(ended=False).order_by(Stream.stream_start).first()
        if current_stream is None:
            return make_response(jsonify({'error': 'Stream offline'}), 400)

        song_requested = PleblistSong(current_stream.id, youtube_id)
        session.add(song_requested)
        song_info = session.query(PleblistSongInfo).filter_by(pleblist_song_youtube_id=youtube_id).first()
        if song_info is None and song_requested.song_info is None:
            PleblistManager.init(config['youtube']['developer_key'])
            song_info = PleblistManager.create_pleblist_song_info(song_requested.youtube_id)
            if song_info is not False:
                session.add(song_info)
                session.commit()

        return jsonify({'success': True})

@page.route('/api/v1/pleblist/next', methods=['POST', 'GET'])
def pleblist_next():
    if not request.method == 'POST':
        return make_response(jsonify({'error': 'Invalid request method'}), 405)
    if 'song_id' not in request.form:
        return make_response(jsonify({'error': 'Missing data song_id'}), 400)
    if 'password' not in request.form:
        return make_response(jsonify({'error': 'Missing data password'}), 400)
    salted_password = generate_password_hash(config['web']['pleblist_password'], config['web']['pleblist_password_salt'])
    try:
        user_password = base64.b64decode(request.form['password'])
    except binascii.Error:
        return make_response(jsonify({'error': 'Invalid data password'}), 400)
    if not user_password == salted_password:
        return make_response(jsonify({'error': 'Invalid password'}), 401)

    with DBManager.create_session_scope() as session:
        try:
            current_song = session.query(PleblistSong).filter(PleblistSong.id == int(request.form['song_id'])).order_by(PleblistSong.date_added.asc()).first()
        except ValueError:
            return make_response(jsonify({'error': 'Invalid data song_id'}), 400)

        if current_song is None:
            return make_response(jsonify({'error': 'No song active in the pleblist'}), 404)

        current_song.date_played = datetime.datetime.now()
        session.commit()

        # TODO: Add more data.
        # Was this song forcefully skipped? Or did it end naturally.

        return jsonify({'message': 'Success!'})

@page.route('/api/v1/pleblist/validate', methods=['POST', 'GET'])
def pleblist_validate():
    if not request.method == 'POST':
        return make_response(jsonify({'error': 'Invalid request method'}), 405)
    if 'youtube_id' not in request.form:
        return make_response(jsonify({'error': 'Missing data youtube_id'}), 400)

    with DBManager.create_session_scope() as session:
        youtube_id = request.form['youtube_id']
        print(youtube_id)
        song_info = session.query(PleblistSongInfo).filter_by(pleblist_song_youtube_id=youtube_id).first()
        if song_info is not None:
            return jsonify({
                'message': 'success',
                'song_info': song_info.jsonify()
                })

        PleblistManager.init(config['youtube']['developer_key'])
        song_info = PleblistManager.create_pleblist_song_info(youtube_id)
        if not song_info and len(youtube_id) > 11:
            youtube_id = youtube_id[:11]
            song_info = session.query(PleblistSongInfo).filter_by(pleblist_song_youtube_id=youtube_id).first()
            if song_info is not None:
                return jsonify({
                    'message': 'success',
                    'new_youtube_id': youtube_id,
                    'song_info': song_info.jsonify()
                    })
            else:
                song_info = PleblistManager.create_pleblist_song_info(youtube_id)

        if song_info:
            print(song_info)
            session.add(song_info)
            session.commit()
            return jsonify({
                'message': 'success',
                'new_youtube_id': youtube_id,
                'song_info': song_info.jsonify()
                })

        return jsonify({
            'message': 'invalid youtube id',
            'song_info': None
            })

@page.route('/api/v1/pleblist/blacklist')
def pleblist_blacklist():
    with DBManager.create_session_scope() as session:
        current_stream = session.query(Stream).filter_by(ended=False).order_by(Stream.stream_start).first()
        if current_stream is None:
            return make_response(jsonify({'error': 'Stream offline'}), 400)

        # TODO: implement this

        return make_response(jsonify({'error': 'NOT IMPLEMENTED'}), 400)

        # return jsonify({'success': True})

@page.route('/api/v1/streamtip/oauth')
def streamtip_oauth():
    if not request.method == 'GET':
        return make_response(jsonify({'error': 'Invalid request method. (Expected GET)'}), 400)

    if 'code' not in request.args:
        return make_response(jsonify({'error': 'Missing `code` parameter.'}), 400)

    if 'streamtip' not in config:
        return make_response(jsonify({'error': 'Config not set up properly.'}), 400)

    payload = {
            'client_id': config['streamtip']['client_id'],
            'client_secret': config['streamtip']['client_secret'],
            'grant_type': 'authorization_code',
            'redirect_uri': config['streamtip']['redirect_uri'],
            'code': request.args['code'],
            }

    r = requests.post('https://streamtip.com/api/oauth2/token', data=payload)

    return redirect('/pleblist/host/#{}'.format(r.json()['access_token']), 303)

@page.route('/api/v1/streamtip/validate', methods=['POST', 'GET'])
def streamtip_validate():
    if not request.method == 'POST':
        return make_response(jsonify({'error': 'Invalid request method. (Expected POST)'}), 400)

    if 'access_token' not in request.form:
        return make_response(jsonify({'error': 'Missing `access_token` parameter.'}), 400)

    if 'streamtip' not in config:
        return make_response(jsonify({'error': 'Config not set up properly.'}), 400)

    r = requests.get('https://streamtip.com/api/me?access_token={}'.format(request.form['access_token']))
    valid_streamtip_ids = [config['web']['pleblist_streamtip_userid'], '54c1354fe6b5a0f83c5d2ab1']
    if r.json()['user']['_id'] in valid_streamtip_ids:
        salted_password = generate_password_hash(config['web']['pleblist_password'], config['web']['pleblist_password_salt'])
        password = base64.b64encode(salted_password)
        resp = make_response(jsonify({'password': password}))
        resp.set_cookie('password', password)
        return resp
    else:
        return make_response(jsonify({'error': 'Invalid user ID'}), 400)

@page.route('/api/v1/command/remove/<command_id>', methods=['GET'])
@requires_level(500)
def command_remove(command_id, **options):
    with DBManager.create_session_scope() as db_session:
        command = db_session.query(Command).filter_by(id=command_id).one_or_none()
        if command is None:
            return make_response(jsonify({'error': 'Invalid command ID'}), 404)
        if command.level > options['user'].level:
            abort(403)
        db_session.delete(command.data)
        db_session.delete(command)

    payload = {
            'event': 'command.remove',
            'data': {
                'command_id': command_id
                }
            }
    payload_bytes = json.dumps(payload).encode('utf-8')
    try:
        with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as client:
            client.connect(config['sock']['sock_file'])
            client.sendall(payload_bytes)
            return make_response(jsonify({'success': 'good job'}))
    except:
        log.exception('???')
        return make_response(jsonify({'error': 'Could not push update'}))

@page.route('/api/v1/command/update/<command_id>', methods=['POST', 'GET'])
@requires_level(500)
def command_update(command_id, **options):
    if not request.method == 'POST':
        return make_response(jsonify({'error': 'Invalid request method. (Expected POST)'}), 400)
    if len(request.form) == 0:
        return make_response(jsonify({'error': 'Missing parameter to edit.'}), 400)

    valid_names = [
            'enabled',
            'level',
            'delay_all',
            'delay_user',
            'cost',
            'can_execute_with_whisper',
            'sub_only'
            ]

    valid_action_names = [
            'type',
            'message'
            ]

    with DBManager.create_session_scope() as db_session:
        command = db_session.query(Command).filter_by(id=command_id).one_or_none()
        if command is None:
            return make_response(jsonify({'error': 'Invalid command ID'}), 404)
        if command.level > options['user'].level:
            abort(403)
        parsed_action = json.loads(command.action_json)
        options = {}

        for key in request.form:
            if key.startswith('data_'):
                name = key[5:]
                value = request.form[key]

                if name.startswith('action_'):
                    name = name[7:]
                    if name in valid_action_names and name in parsed_action and command.action.type == 'message':
                        value_type = type(parsed_action[name])
                        if value_type is bool:
                            parsed_value = True if value == '1' else False
                        elif value_type is int:
                            try:
                                parsed_value = int(value)
                            except ValueError:
                                continue
                        else:
                            parsed_value = value
                        parsed_action[name] = parsed_value
                    command.action_json = json.dumps(parsed_action)
                else:
                    if name in valid_names:
                        value_type = type(getattr(command, name))
                        if value_type is bool:
                            parsed_value = True if value == '1' else False
                        elif value_type is int:
                            try:
                                parsed_value = int(value)
                            except ValueError:
                                continue
                        else:
                            parsed_value = value
                        options[name] = parsed_value

        command.set(**options)

    if SocketClientManager.send('command.update', {'command_id': command_id}) is True:
        return make_response(jsonify({'success': 'good job'}))
    else:
        return make_response(jsonify({'error': 'Could not push update'}))

@page.route('/api/v1/command/checkalias', methods=['POST'])
@requires_level(500)
def command_checkalias(**options):
    if 'alias' not in request.form:
        return make_response(jsonify({'error': 'Missing `alias` parameter.'}), 400)

    request_alias = request.form['alias'].lower()

    command_manager = CommandManager(
            socket_manager=None,
            module_manager=ModuleManager(None).load(),
            bot=None).load(enabled=None)

    command_aliases = []

    for alias, command in command_manager.items():
        command_aliases.append(alias)
        if command.command and len(command.command) > 0:
            command_aliases.extend(command.command.split('|'))

    command_aliases = set(command_aliases)

    if request_alias in command_aliases:
        return make_response(jsonify({'error': 'Alias already in use'}))
    else:
        return make_response(jsonify({'success': 'good job'}))

@page.route('/api/v1/timer/remove/<timer_id>', methods=['GET'])
@requires_level(500)
def timer_remove(timer_id, **options):
    with DBManager.create_session_scope() as db_session:
        timer = db_session.query(Timer).filter_by(id=timer_id).one_or_none()
        if timer is None:
            return make_response(jsonify({'error': 'Invalid timer ID'}))
        db_session.delete(timer)
        SocketClientManager.send('timer.remove', {'timer_id': timer.id})
        return make_response(jsonify({'success': 'good job'}))

@page.route('/api/v1/banphrase/remove/<banphrase_id>', methods=['GET'])
@requires_level(500)
def banphrase_remove(banphrase_id, **options):
    with DBManager.create_session_scope() as db_session:
        banphrase = db_session.query(Banphrase).filter_by(id=banphrase_id).one_or_none()
        if banphrase is None:
            return make_response(jsonify({'error': 'Invalid banphrase ID'}))
        db_session.delete(banphrase)
        db_session.delete(banphrase.data)
        SocketClientManager.send('banphrase.remove', {'banphrase_id': banphrase.id})
        return make_response(jsonify({'success': 'good job'}))

@page.route('/api/v1/<route_key>/toggle/<row_id>', methods=['POST'])
@requires_level(500)
def generic_toggle(route_key, row_id, **options):
    valid_routes = {
            'timer': Timer,
            'banphrase': Banphrase,
            'module': Module,
            }

    if route_key not in valid_routes:
        return make_response(jsonify({'error': 'Invalid route.'}), 400)
    if 'new_state' not in request.form:
        return make_response(jsonify({'error': 'Missing `new_state` parameter.'}), 400)
    try:
        new_state = int(request.form['new_state'])
    except (ValueError, KeyError):
        return make_response(jsonify({'error': 'Invalid `new_state` parameter.'}), 400)

    route_value = valid_routes[route_key]

    with DBManager.create_session_scope() as db_session:
        row = db_session.query(route_value).filter_by(id=row_id).one_or_none()
        if row:
            row.enabled = True if new_state == 1 else False
            db_session.commit()
            SocketClientManager.send('{}.update'.format(route_key), {'{}_id'.format(route_key): row.id})
            return make_response(jsonify({'success': 'successful toggle', 'new_state': new_state}))
        else:
            return make_response(jsonify({'error': 'invalid {} id'.format(route_key)}))


text:
require "log4r"
require "ipaddr"

module VagrantPlugins
  module OpenStack
    module Action
      # This action reads the SSH info for the machine and puts it into the
      # `:machine_ssh_info` key in the environment.
      class ReadSSHInfo
        def initialize(app, env)
          @app    = app
          @logger = Log4r::Logger.new("vagrant_openstack::action::read_ssh_info")
        end

        def call(env)
          env[:machine_ssh_info] = read_ssh_info(env[:openstack_compute], env[:machine], env[:floating_ip])

          @app.call(env)
        end

        def read_ssh_info(openstack, machine, floating_ip)
            id = machine.id || openstack.servers.all( :name => machine.name ).first.id rescue nil
          return nil if id.nil?
          server = openstack.servers.get(id)
          if server.nil?
            # The machine can't be found
            @logger.info("Machine couldn't be found, assuming it got destroyed.")
            machine.id = nil
            return nil
          end

          config = machine.provider_config

          # Print a list of the available networks
          server.addresses.each do |network_name, network_info|
            @logger.debug("OpenStack Network Name: #{network_name}")
          end

          if config.network
            host = server.addresses[config.network].last['addr'] rescue nil
          else
            if config.address_id.to_sym == :floating_ip
              host = floating_ip
            else
              host = server.addresses[config.address_id].last['addr'] rescue nil
            end
          end

          # If host is still nil, try to find the IP address another way
          if host.nil?
            @logger.debug("Was unable to determine what network to use. Trying to find a valid IP to use.")
            if server.public_ip_addresses.length > 0
              @logger.debug("Public IP addresses available: #{server.public_ip_addresses}")
              if floating_ip
                if server.public_ip_addresses.include?(floating_ip)
                  @logger.debug("Using the floating IP defined in Vagrantfile.")
                  host = machine.floating_ip
                else
                  @logger.debug("The floating IP that was specified is not available to this instance.")
                  raise Errors::FloatingIPNotValid
                end
              else
                host = server.public_ip_address
                @logger.debug("Using the first available public IP address: #{host}.")
              end
            elsif server.private_ip_addresses.length > 0
              @logger.debug("Private IP addresses available: #{server.private_ip_addresses}")
              if config.ssh_ip_family.nil?
                host = server.private_ip_address
                @logger.debug("Using the first available private IP address: #{host}.")
              else
                for ip in server.private_ip_addresses
                  addr = IPAddr.new ip
                  if addr.send("#{config.ssh_ip_family}?".to_sym)
                    host = ip.to_s
                    @logger.debug("Using the first available #{config.ssh_ip_family} IP address: #{host}.")
                    break
                  end
                end
              end
            end
          end

          # If host got this far and is still nil/empty, raise an error or
          # else vagrant will try connecting to localhost which will never
          # make sense in this scenario
          if host.nil? or host.empty?
            @logger.debug("No valid SSH host could be found.")
            raise Errors::SSHNoValidHost
          end

          # Read the DNS info
          return {
            # Usually there should only be one public IP
            :host => host,
            :port => 22,
            :username => config.ssh_username
          }
        end
      end
    end
  end
end


text:
package goja.castor.castor;

import java.util.Set;

import com.alibaba.fastjson.JSON;
import goja.castor.Castor;
import goja.exceptions.FailToCastObjectException;

@SuppressWarnings("rawtypes")
public class String2Set extends Castor<String, Set> {

    @Override
    public Set cast(String src, Class<?> toType, String... args) throws FailToCastObjectException {
        return JSON.parseObject(src,Set.class);
    }

}


text:
import os
from os import path
from itertools import izip
import shutil
from multiprocessing import Pool
from math import pi
import math
import csv
import operator
import pickle
import time

import numpy as np
from scipy.optimize import leastsq

#import pyfits
#from pywcs import WCS
#from ephem import Equatorial, Ecliptic

import matplotlib
# Force matplotlib to not use any Xwindows backend.
matplotlib.use('Agg')
import matplotlib.pyplot as plot
import pickle
import urllib2

def parse_AAS_like_a_boss():
    AAS_num = []
    AAS_session_num = []
    AAS_session_title = []

    for i in range(182,208):
        file1 = open('AAS'+str(i)+'.txt','r')
        #Different files have different formats because fuck everything

        #Case 1
        if i < 187:
            #For these files, the format is:
            #...... >Session #: SESSION TITLE
            session_num_to_find = 1
            found = False
            for line in file1:
                garbage,phrase_to_find,after = line.partition('>Session '+str(session_num_to_find)+': ')
                if after != '':
                    the_name,parser,blank = after.partition('')
                    AAS_num.append(str(i))
                    AAS_session_num.append(str(session_num_to_find))
                    AAS_session_title.append(the_name)
                    session_num_to_find = session_num_to_find+1

        #Case 2
        if i > 186 and i < 193:
            #For these files, the format is:
            #Sess###>SESSION TITLE

            session_num_to_find = 1
            for line in file1:
                if session_num_to_find < 10:
                    garbage,phrase_to_find,after = line.partition('Sess00'+str(session_num_to_find)+'>')
                    if after !='':
                        the_name,parser,blank = after.partition('
')
                        AAS_num.append(str(i))
                        AAS_session_num.append(str(session_num_to_find))
                        AAS_session_title.append(the_name)
                        session_num_to_find = session_num_to_find+1

                if session_num_to_find > 9 and session_num_to_find < 100:
                    garbage,phrase_to_find,after = line.partition('Sess0'+str(session_num_to_find)+'>')
                    if after !='':
                        the_name,parser,blank = after.partition('
')
                        AAS_num.append(str(i))
                        AAS_session_num.append(str(session_num_to_find))
                        AAS_session_title.append(the_name)
                        session_num_to_find = session_num_to_find+1

                if session_num_to_find > 100:
                    garbage,phrase_to_find,after = line.partition('Sess'+str(session_num_to_find)+'>')
                    if after !='':
                        the_name,parser,blank = after.partition('
')
                        AAS_num.append(str(i))
                        AAS_session_num.append(str(session_num_to_find))
                        AAS_session_title.append(the_name)
                        session_num_to_find = session_num_to_find+1

        #Case 3
        if i > 193:
            #For these files, the format is:
            #.... Session #. ..... S#0.htm">Session Title
            session_num_to_find = 1
            for line in file1:
                garbage,phrase_to_find,after = line.partition('S'+str(session_num_to_find)+'0.htm">')
                if after != '':
                    the_name,parser,blank = after.partition('')
                    AAS_num.append(str(i))
                    AAS_session_num.append(str(session_num_to_find))
                    AAS_session_title.append(the_name)
                    session_num_to_find = session_num_to_find+1

    pickle.dump([AAS_num,AAS_session_num,AAS_session_title], open("AAS_Lists.pickle","wb"))

    return(0)

def main():
    dummy_variable = parse_AAS_like_a_boss()

if __name__ == '__main__':
    main()


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" android:exitFadeDuration="@android:integer/config_mediumAnimTime">

    <item android:drawable="@color/holo_blue_dark" android:state_pressed="true"/>
    <item android:drawable="@color/holo_blue_dark" android:state_enabled="true" android:state_focused="true"/>
    <item android:drawable="@color/transparent"/>

</selector>


text:
// RubDivSolverV1.cpp

#include "RubDivSolverV1.h"

RubDivSolverV1::RubDivSolverV1( void )
{
	puzzleClone = 0;
}

/*virtual*/ RubDivSolverV1::~RubDivSolverV1( void )
{
	wxASSERT( puzzleClone == 0 );
}

/*virtual*/ bool RubDivSolverV1::Solve( const RubDivPuzzle* puzzle, RubDivPuzzle::MoveList& moveList )
{
	wxASSERT( puzzleClone == 0 );

	// We only deal with the vertical case, which is really no different than the horizontal case.
	if( puzzle->GetOrientation() != RubDivPuzzle::VERTICAL )
		return false;

	moveList.clear();
	puzzleClone = puzzle->Clone();
	while( !puzzleClone->IsSolved() )
	{
		RubDivPuzzle::MoveList algorithm;
		if( FindAlgorithm( algorithm ) )
		{
			bool manipulated = puzzleClone->ManipulatePuzzle( algorithm );
			wxASSERT( manipulated );
			ConcatinateMoveList( moveList, algorithm );
		}
		else
		{
			RubDivPuzzle::Move rotateMove;
			rotateMove.squareOffset = 2;
			rotateMove.rotateCCWCount = 1;
			rotateMove.rowOrColumn = -1;
			rotateMove.shiftDir = RubDivPuzzle::SHIFT_NONE;

			bool manipulated = puzzleClone->ManipulatePuzzle( rotateMove );
			wxASSERT( manipulated );
			moveList.push_back( rotateMove );
		}
	}

	delete puzzleClone;
	puzzleClone = 0;

	CompressMoveList( moveList );

	return true;
}

// Note that this could generalize even further by solving multiple rows at the same time and using multiple preservation columns.
// As long as there's no collision between the columns we solve in the rows and the preservation columns, it works out.
bool RubDivSolverV1::FindAlgorithm( RubDivPuzzle::MoveList& algorithm )
{
	int size = puzzleClone->GetSize();

	for( int i = 0; i < size; i++ )
	{
		RubDivPuzzle::MoveList algorithmCCW, algorithmCW;

		RubDivPuzzle::Move rotationMove;
		rotationMove.squareOffset = 1;
		rotationMove.rowOrColumn = -1;
		rotationMove.shiftDir = RubDivPuzzle::SHIFT_NONE;

		rotationMove.rotateCCWCount = 1;
		bool foundCCW = FindAlgorithmForRow( i, rotationMove, algorithmCCW );

		rotationMove.rotateCCWCount = 3;
		bool foundCW = FindAlgorithmForRow( i, rotationMove, algorithmCW );

		if( foundCCW && foundCW )
		{
			if( algorithmCCW.size() > algorithmCW.size() )
				ConcatinateMoveList( algorithm, algorithmCCW );
			else
				ConcatinateMoveList( algorithm, algorithmCW );
		}
		else if( foundCCW )
			ConcatinateMoveList( algorithm, algorithmCCW );
		else if( foundCW )
			ConcatinateMoveList( algorithm, algorithmCW );

		if( algorithm.size() > 0 )
			return true;
	}

	return false;
}

// Notice that for puzzles with an odd size, the centers cannot move.
// So to avoid this special case, we always restore color A to the top
// square, and color B to the bottom square.
bool RubDivSolverV1::FindAlgorithmForRow( int row, const RubDivPuzzle::Move& rotationMove, RubDivPuzzle::MoveList& algorithm )
{
	int size = puzzleClone->GetSize();

	int preservationColumn;
	if( rotationMove.rotateCCWCount == 1 )
		preservationColumn = row;
	else if( rotationMove.rotateCCWCount == 3 )
		preservationColumn = size - 1 - row;
	else
		return false;

	RubDivPuzzle::MoveList shiftMoveList;
	RubDivPuzzle::MoveList inverseShiftMoveList;

	for( int j = 0; j < size; j++ )
	{
		if( j == preservationColumn )
			continue;

		if( puzzleClone->GetColor( 1, row, j ) == RubDivPuzzle::Element::COLOR_B && puzzleClone->GetColor( 2, row, j ) == RubDivPuzzle::Element::COLOR_A )
		{
			RubDivPuzzle::Move shiftMove;
			shiftMove.squareOffset = -1;
			shiftMove.rotateCCWCount = 0;
			shiftMove.rowOrColumn = j;
			shiftMove.shiftDir = RubDivPuzzle::SHIFT_BACKWARD;
			shiftMoveList.push_back( shiftMove );

			RubDivPuzzle::Move inverseShiftMove;
			shiftMove.Invert( inverseShiftMove );
			inverseShiftMoveList.push_back( inverseShiftMove );
		}
	}

	if( shiftMoveList.size() == 0 )
		return false;

	ConcatinateMoveList( algorithm, shiftMoveList );

	algorithm.push_back( rotationMove );

	RubDivPuzzle::Move preservationShiftMove;
	preservationShiftMove.squareOffset = -1;
	preservationShiftMove.rotateCCWCount = 0;
	preservationShiftMove.rowOrColumn = preservationColumn;
	preservationShiftMove.shiftDir = RubDivPuzzle::SHIFT_BACKWARD;
	algorithm.push_back( preservationShiftMove );

	RubDivPuzzle::Move inverseRotationMove;
	rotationMove.Invert( inverseRotationMove );
	algorithm.push_back( inverseRotationMove );

	ConcatinateMoveList( algorithm, inverseShiftMoveList );

	algorithm.push_back( rotationMove );

	RubDivPuzzle::Move inversePreservationShiftMove;
	preservationShiftMove.Invert( inversePreservationShiftMove );
	algorithm.push_back( inversePreservationShiftMove );

	algorithm.push_back( inverseRotationMove );

	return true;
}

// RubDivSolverV1.cpp


text:
package org.quartzpowered.protocol.codec.v1_8_R1.play.client;

import org.quartzpowered.network.buffer.Buffer;
import org.quartzpowered.network.protocol.codec.Codec;
import org.quartzpowered.protocol.data.metadata.Metadata;
import org.quartzpowered.protocol.packet.play.client.SpawnPlayerPacket;

public class SpawnPlayerCodec implements Codec<SpawnPlayerPacket> {
    @Override
    public void encode(Buffer buffer, SpawnPlayerPacket packet) {
        buffer.writeVarInt(packet.getEntityId());
        buffer.writeUuid(packet.getPlayerId());
        buffer.writeFixedPointInt(packet.getX());
        buffer.writeFixedPointInt(packet.getY());
        buffer.writeFixedPointInt(packet.getZ());
        buffer.writeAngle((float) packet.getYaw());
        buffer.writeAngle((float) packet.getPitch());
        buffer.writeShort(packet.getHeldItem());
        packet.getMetadata().write(buffer);
    }

    @Override
    public void decode(Buffer buffer, SpawnPlayerPacket packet) {
        packet.setEntityId(buffer.readVarInt());
        packet.setPlayerId(buffer.readUuid());
        packet.setX(buffer.readFixedPointInt());
        packet.setY(buffer.readFixedPointInt());
        packet.setZ(buffer.readFixedPointInt());
        packet.setYaw(buffer.readAngle());
        packet.setPitch(buffer.readAngle());
        packet.setHeldItem(buffer.readShort());

        Metadata metadata = new Metadata();
        metadata.read(buffer);
        packet.setMetadata(metadata);
    }
}


text:
/*  THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW:
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a
 *  copy of this software and associated documentation files (the "Software"),
 *  to deal in the Software without restriction, including without limitation
 *  the rights to use, copy, modify, merge, publish, distribute, sublicense,
 *  and/or sell copies of the Software, and to permit persons to whom the
 *  Software is furnished to do so, subject to the following conditions:
 *
 *  The above copyright notice and this permission notice shall be included in
 *  all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 *  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 *  DEALINGS IN THE SOFTWARE.
 */

using System;
using System.Threading;
using System.Runtime.InteropServices;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Diagnostics;
using System.Globalization;
#if !win32
using Mono.Unix;
#else
using Banshee.Winforms;
#endif

namespace Banshee.Base
{
    public static class UidGenerator
    {
        private static int uid = 0;

        public static int Next
        {
            get {
                return ++uid;
            }
        }
    }

    public static class Utilities
    {
#if !win32
        [DllImport("libglib-2.0.so")]
        private static extern IntPtr g_get_real_name();

        public static string GetRealName()
        {
            try {
                string name = GLib.Marshaller.Utf8PtrToString(g_get_real_name());
                string [] parts = name.Split(' ');
                return parts[0].Replace(',', ' ').Trim();
            } catch(Exception) {
                return null;
            }
        }
#else
        public static string GetRealName()
        {
            try
            {

            }
            catch
            {

            }
            return "realname";
        }
#endif
        public static string BytesToString(ulong bytes)
        {
            double mb = (double)bytes / 1048576.0;
            return mb > 1024.0
                ? String.Format(Catalog.GetString("{0:0.00} GB"), mb / 1024.0)
                : String.Format(Catalog.GetString("{0} MB"), Math.Round(mb));
        }

        public static bool UnmountVolume(string device)
        {
            try {
                if(ExecProcess("pumount", device) != 0) {
                    throw new ApplicationException("pumount returned error");
                }

                return true;
            } catch(Exception) {
                try {
                    return ExecProcess("umount", device) == 0;
                } catch(Exception) {
                }
            }

            return false;
        }

        public static int ExecProcess(string command, string args)
        {
            Process process = Process.Start(command, args == null ? "" : args);
            process.WaitForExit();
            return process.ExitCode;
        }
#if win32
        public static System.Drawing.Color ColorBlend(System.Drawing.Color a, System.Drawing.Color b)
        {
            // Cornel 03-22-2007 - Do we want a vista style glassblend ?
            return System.Drawing.Color.White;
        }
#else
        public static Gdk.Color ColorBlend(Gdk.Color a, Gdk.Color b)
        {
            // at some point, might be nice to allow any blend?
            double blend = 0.5;

            if(blend < 0.0 || blend > 1.0) {
                throw new ApplicationException("blend < 0.0 || blend > 1.0");
            }

            double blendRatio = 1.0 - blend;

            int aR = a.Red >> 8;
            int aG = a.Green >> 8;
            int aB = a.Blue >> 8;

            int bR = b.Red >> 8;
            int bG = b.Green >> 8;
            int bB = b.Blue >> 8;

            double mR = aR + bR;
            double mG = aG + bG;
            double mB = aB + bB;

            double blR = mR * blendRatio;
            double blG = mG * blendRatio;
            double blB = mB * blendRatio;

            Gdk.Color color = new Gdk.Color((byte)blR, (byte)blG, (byte)blB);
            Gdk.Colormap.System.AllocColor(ref color, true, true);
            return color;
        }
#endif
#if win32
        // Cornel 22-03-2007 this is not required for win32 since banshee will start as process "banshee"
        // Although for Accuracy i will add a dummy method
        public static void SetProcessName(string name)
        {

        }
#else
        [DllImport("libc")]
        private static extern int prctl(int option, byte [] arg2, IntPtr arg3, IntPtr arg4, IntPtr arg5);

        public static void SetProcessName(string name)
        {
            if(prctl(15 /* PR_SET_NAME */, Encoding.ASCII.GetBytes(name + "\0"),
                IntPtr.Zero, IntPtr.Zero, IntPtr.Zero) != 0) {
                throw new ApplicationException("Error setting process name: " +
                    Mono.Unix.Native.Stdlib.GetLastError());
            }
        }
#endif
    }

    public static class ReflectionUtil
    {
        public static bool IsVirtualMethodImplemented(Type type, string methodName)
        {
            MethodInfo methodInfo = type.GetMethod(methodName,
                BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);

            if(methodInfo == null) {
                return false;
            }

            return methodInfo.IsVirtual ? methodInfo != methodInfo.GetBaseDefinition() : true;
        }

        public static object InvokeMethod(Assembly assembly, string typeName, string methodName)
        {
            if(assembly == null) {
                throw new ArgumentNullException("assembly");
            }

            Type type = assembly.GetType(typeName, true);
            MethodInfo method = type.GetMethod(methodName);
            return method.Invoke(null, null);
        }

        public static Type [] ModuleGetTypes(Assembly assembly, string typeName)
        {
            return (Type [])InvokeMethod(assembly, typeName, "GetTypes");
        }
    }

    public class DateTimeUtil
    {
        public static readonly DateTime LocalUnixEpoch = new DateTime(1970, 1, 1).ToLocalTime();

        public static DateTime ToDateTime(long time)
        {
            return FromTimeT(time);
        }

        public static long FromDateTime(DateTime time)
        {
            return ToTimeT(time);
        }

        public static DateTime FromTimeT(long time)
        {

            return LocalUnixEpoch.AddSeconds(time);
        }

        public static long ToTimeT(DateTime time)
        {
            return (long)time.Subtract(LocalUnixEpoch).TotalSeconds;
        }

        public static string FormatDuration(long time) {
            return (time > 3600 ?
                    String.Format("{0}:{1:00}:{2:00}", time / 3600, (time / 60) % 60, time % 60) :
                    String.Format("{0}:{1:00}", time / 60, time % 60));
        }
    }

    public class Timer : IDisposable
    {
        private DateTime start;
        private string label;

        public Timer(string label)
        {
            this.label = label;
            start = DateTime.Now;
        }

        public TimeSpan ElapsedTime {
            get {
                return DateTime.Now - start;
            }
        }

        public void WriteElapsed(string message)
        {
            Console.WriteLine("{0} {1} {2}", label, message, ElapsedTime);
        }

        public void Dispose()
        {
            WriteElapsed("timer stopped:");
        }
    }

    public static class ThreadAssist
    {
        private static Thread main_thread;

        static ThreadAssist()
        {
            main_thread = Thread.CurrentThread;
        }

        public static bool InMainThread {
            get {
                return main_thread.Equals(Thread.CurrentThread);
            }
        }

        public static void ProxyToMain(EventHandler handler)
        {
            if (!InMainThread)
            {
                if (InterfaceElements.MainWindow != null)
                    InterfaceElements.MainWindow.BeginInvoke(handler);
            }
            else
            {
                handler(null, new EventArgs());
            }
        }

        public static Thread Spawn(ThreadStart threadedMethod, bool autoStart)
        {
            Thread thread = new Thread(threadedMethod);
            thread.IsBackground = true;
            if(autoStart) {
                thread.Start();
            }
            return thread;
        }

        public static Thread Spawn(ThreadStart threadedMethod)
        {
            return Spawn(threadedMethod, true);
        }
    }

    public static class PathUtil
    {
        public static string MakeFileNameKey(SafeUri uri)
        {
            string path = uri.LocalPath;
            return Path.GetDirectoryName(path) +
                Path.DirectorySeparatorChar +
                Path.GetFileNameWithoutExtension(path);
        }

        public static long GetDirectoryAvailableSpace(string path)
        {
            try {
#if win32
                //TODO Cornel 22-03-2007 - Will add this later
                DirectoryInfo statvfs_info = new DirectoryInfo(path);
                //statvfsinfo.
                return 1;
#else
                Mono.Unix.Native.Statvfs statvfs_info;
                if(Mono.Unix.Native.Syscall.statvfs(path, out statvfs_info) == 0) {
                    return (long)(statvfs_info.f_bavail * statvfs_info.f_bsize);

                }
#endif

                return -1;
            } catch {
                return -1;
            }
        }
    }

    public class Resource
    {
        public static string GetFileContents(string name)
        {
            Assembly asm = Assembly.GetCallingAssembly();
            Stream stream = asm.GetManifestResourceStream(name);
            StreamReader reader = new StreamReader(stream);
            return reader.ReadToEnd();
        }
    }

    public static class NamingUtil
    {
        public delegate bool PostfixDuplicateIncrementHandler(string check);

        public static string GenerateTrackCollectionName(IEnumerable tracks, string fallback)
        {
            Dictionary<string, int> weight_map = new Dictionary<string, int>();

            if(tracks == null) {
                return fallback;
            }

            foreach(TrackInfo track in tracks) {
                string artist = null;
                string album = null;

                if(track.Artist != null) {
                    artist = track.Artist.Trim();
                    if(artist == String.Empty) {
                        artist = null;
                    }
                }

                if(track.Album != null) {
                    album = track.Album.Trim();
                    if(album == String.Empty) {
                        album = null;
                    }
                }

                if(artist != null && album != null) {
                    IncrementCandidate(weight_map, "\0" + artist + " - " + album);
                    IncrementCandidate(weight_map, artist);
                    IncrementCandidate(weight_map, album);
                } else if(artist != null) {
                    IncrementCandidate(weight_map, artist);
                } else if(album != null) {
                    IncrementCandidate(weight_map, album);
                }
            }

            int max_hit_count = 0;
            string max_candidate = fallback;

            List<string> sorted_keys = new List<string>(weight_map.Keys);
            sorted_keys.Sort();

            foreach(string candidate in sorted_keys) {
                int current_hit_count = weight_map[candidate];
                if(current_hit_count > max_hit_count) {
                    max_hit_count = current_hit_count;
                    max_candidate = candidate;
                }
            }

            if(max_candidate[0] == '\0') {
                return max_candidate.Substring(1);
            }

            return max_candidate;
        }

        private static void IncrementCandidate(Dictionary<string, int> map, string hit)
        {
            if(map.ContainsKey(hit)) {
                map[hit]++;
            } else {
                map.Add(hit, 1);
            }
        }

        public static string PostfixDuplicate(string prefix, PostfixDuplicateIncrementHandler duplicateHandler)
        {
            if(duplicateHandler == null) {
                throw new ArgumentNullException("A PostfixDuplicateIncrementHandler delegate must be given");
            }

            string name = prefix;
            for(int i = 1; true; i++) {
                if(!duplicateHandler(name)) {
                    return name;
                }

                name = prefix + " " + i;
            }
        }
    }
}


text:
/* globals test expect jest */
import ResourceLoader, { ResourceType } from './resourceLoader';

test('ResourceLoader should have addResource, startPreloading and isLoadComplete function', () => {
  const resourceLoader = new ResourceLoader();

  expect(resourceLoader.addResource).toBeDefined();
  expect(resourceLoader.startPreloading).toBeDefined();
  expect(resourceLoader.isLoadComplete).toBeDefined();

  // no crash
  resourceLoader.addResource('./img/sprite.png', null, ResourceType.IMAGE);
  resourceLoader.startPreloading();
  expect(resourceLoader.resources.length).toBe(1);
});

test('ResourceLoader accepts resources to preload', (done) => {
  let partials = 0;
  const resourceLoader = new ResourceLoader(
    () => {
      partials += 1;
    }, // some resources are loaded
    () => {
      expect(partials).toBe(2);
      expect(resourceLoader.isLoadComplete()).toBeTruthy();
      done();
    }, // all resources are loaded
  );
  // add some resources to load
  resourceLoader.addResource('./img/sprite.png', null, ResourceType.IMAGE);
  resourceLoader.addResource('./img/back.png', null, ResourceType.IMAGE);
  resourceLoader.addResource('./img/unknown.res', null, 99);
  expect(resourceLoader.resources.length).toBe(2);
  // shouldn't be loaded right away
  expect(resourceLoader.isLoadComplete()).toBeFalsy();
  // load 'em
  resourceLoader.startPreloading();
});


text:
/**
 * Input/output package
 */
package kr.jihee.text_toolkit.io;

import java.awt.image.RenderedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.util.Optional;
import java.util.function.Predicate;
import java.util.stream.Stream;
import java.util.stream.Stream.Builder;

import javax.imageio.ImageIO;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import kr.jihee.text_toolkit.lang.JFunction.Thrower;
import kr.jihee.text_toolkit.util.JTime;

/**
 * Class for handling files
 *
 * @author Jihee
 */
public class JFile {
	protected static Logger log = LogManager.getLogger(JFile.class);

	public static File asFile(String path) {
		Optional<File> local = Optional.of(new File(path)).filter(File::exists);
		if (local.isPresent())
			return local.get();
		else
			return Optional.ofNullable(Object.class.getResource(path)).map(URL::getPath).map(File::new).orElse(null);
	}

	public static InputStream asStream(String path) throws FileNotFoundException {
		Optional<File> local = Optional.of(new File(path)).filter(File::exists);
		if (local.isPresent())
			return new FileInputStream(local.get());
		else
			return Optional.ofNullable(Object.class.getResourceAsStream(path)).orElseThrow(FileNotFoundException::new);
	}

	public static File getTempFile(String project, String prefix, String suffix) {
		File parent = new File(System.getProperty("java.io.tmpdir"), project);
		if (!parent.exists())
			parent.mkdirs();
		try {
			return File.createTempFile(prefix, suffix, parent);
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}

	public static File getTempFile(String project, String prefix) {
		return getTempFile(project, prefix, ".log");
	}

	public static File getTempFile(String project) {
		return getTempFile(project, String.format("[%s] ", JTime.now()), ".log");
	}

	public static Stream<File> list(File path, Predicate<File> filter) {
		try {
			return Files.list(path.toPath()).map(p -> p.toFile()).filter(filter);
		} catch (Throwable e) {
			Thrower.throwing(e);
			return Stream.empty();
		}
	}

	public static Stream<File> listDirs(File path) {
		return list(path, p -> p.isDirectory());
	}

	public static Stream<File> listFiles(File path) {
		return list(path, p -> p.isFile());
	}

	public static Stream<File> listAllDirs(File path) {
		Builder<File> builder = Stream.builder();
		listDirs(path).peek(builder::add).forEach(sub -> listAllDirs(sub).forEach(builder::add));
		return builder.build();
	}

	public static Stream<File> listAllFiles(File path) {
		Builder<File> builder = Stream.builder();
		listFiles(path).forEach(builder::add);
		listAllDirs(path).forEach(sub -> listFiles(sub).forEach(builder::add));
		return builder.build();
	}

	public static boolean writeImage(RenderedImage im, String formatName, File output) {
		try {
			return ImageIO.write(im, formatName, output);
		} catch (Throwable e) {
			Thrower.throwing(e);
			return false;
		}
	}
}


text:
@interface TableViewControllerForISTableViewCell : UITableViewController {

}

@end


text:
The Game:  Rise of the Kobold King.  Tremble before its majesty.

## ** PLEASE, PLEASE, _PLEASE_ ** Clone this code into:
`C:\CodersOfTheRoundTable\RiseOfTheKoboldKing`

## Abstract, anyone?
For the humble outsider looking in:  This is the product of a bunch of nerds in a nerd class (known as the Coders of the Round Table) producing fairly unskilled but totally awesome code.

## A Brief Definition:
Kobolds are a figment of German Mithology.  We're creating a game around that.  It should be pretty awesome.

We're using Unity, Blender, and Visual Studio, except for the unfortunate fellows with Macs, who have been stuck with MonoDevelop.

This class is lead/directed/manhandled by Mr. @Muaadeeb (major kudos to him).  The current organizational structure is:

| Position               | Full Name (s)                | GitHub username           |
|------------------------|------------------------------|---------------------------|
| OWNER 1:               | Tim Indlegue                 | @Muaadeeb                 |
| OWNER 2:               | Sam Indlegue                 | @Saindlegue               |
| Team Leader:           | Grant Shneider               | @AgntBluSqurrl            |
| Tech Lead:             | Lucas Niewohner              | @Hermanoid                |
| Art Peoples:           | Keanu Ellefson,  Jacob Maier | @Keanuellefson, Unknown   |
| Scribe:                | Zach Mancuso                 | @zedmain?                 |
| Business Analysis (BA) | Landen Fogle                 | @landenf                  |


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<title>Highway Framework: Class Members - Properties</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

Highway Framework
    Release 1.0.1.0

The fastest and smoothest way to great architecture

Main Page

Namespaces

Classes

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Class List

Class Index

Class Hierarchy

Class Members

All

Functions

Variables

Properties

Events

 All Classes Namespaces Functions Variables Properties Events

Context
: Highway.Data.EventManagement.EventManager
, Highway.Data.Interfaces.IAsyncRepository
, Highway.Data.Interfaces.IRepository
, Highway.Data.QueryObjects.QueryBase
, Highway.Data.Interfaces.IEventManager
, Highway.Data.AsyncRepository
, Highway.Data.Repository

ContextQuery
: Highway.Data.QueryObjects.Command
, Highway.Data.QueryObjects.Query< T >
, Highway.Data.QueryObjects.Scalar< T >

ContinueExecution
: Highway.Data.Interceptors.InterceptorResult

CreatedBy
: Highway.Data.Interfaces.IAuditableEntity

CreatedDate
: Highway.Data.Interfaces.IAuditableEntity

EventManager
: Highway.Data.Interfaces.IAsyncRepository
, Highway.Data.Repository
, Highway.Data.AsyncRepository
, Highway.Data.ObjectDataContext
, Highway.Data.DataContext
, Highway.Data.Interfaces.IRepository
, Highway.Data.Interfaces.IDataContext

Message
: Highway.Data.Interceptors.InterceptorResult

ModifiedBy
: Highway.Data.Interfaces.IAuditableEntity

ModifiedDate
: Highway.Data.Interfaces.IAuditableEntity

Priority
: Highway.Data.Interfaces.IInterceptor< in T >
, Highway.Data.Interceptors.AuditableInterceptor

<address class="footer">
Generated on Wed Aug 8 2012 20:21:37 for Highway Framework by

 1.8.1.1
</address>


text:
package de.etecture.opensource.dynamicresources.metadata;

import de.etecture.opensource.dynamicresources.api.FilterValueGenerator;

/**
 * represents the metadata for a filter.
 *
 * @param <T>
 * @author rhk
 * @version
 * @since
 */
public interface ResourceMethodFilter<T> {

    /**
     * returns the ResourceMethod to which this filter belongs to.
     *
     * @return
     */
    ResourceMethod getResourceMethod();

    /**
     * returns the type of the filter
     *
     * @return
     */
    Class<T> getType();

    /**
     * returns the name of the filter
     *
     * @return
     */
    String getName();

    /**
     * returns the description of the filter.
     *
     * @return
     */
    String getDescription();

    /**
     * returns the default value, this filter should use if the filter is not
     * specified in the request.
     *
     * @return
     */
    String getDefaultValue();

    /**
     * returns true, if the value is a valid value for this filter.
     *
     * @param value
     * @return
     */
    boolean isValidValue(T value);

    /**
     * returns the class of the {@link FilterValueGenerator} that is responsible
     * to generate appropriate values for this filter.
     *
     * @return
     */
    Class<? extends FilterValueGenerator> getValueGenerator();
}


text:
MAF_WITH_UNIPROT_FIELDS = [
    'Hugo_Symbol',
    'Entrez_Gene_Id',
    'Center',
    'NCBI_Build',
    'Chromosome',
    'Start_Position',
    'End_Position',
    'Strand',
    'Variant_Classification',
    'Variant_Type',
    'Reference_Allele',
    'Tumor_Seq_Allele1',
    'Tumor_Seq_Allele2',
    'dbSNP_RS',
    'dbSNP_Val_Status',
    'Tumor_Sample_Barcode',
    'Matched_Norm_Sample_Barcode',
    'Match_Norm_Seq_Allele1',
    'Match_Norm_Seq_Allele2',
    'Tumor_Validation_Allele1',
    'Tumor_Validation_Allele2',
    'Match_Norm_Validation_Allele1',
    'Match_Norm_Validation_Allele2',
    'Verification_Status',
    'Validation_Status',
    'Mutation_Status',
    'Sequencing_Phase',
    'Sequence_Source',
    'Validation_Method',
    'Score',
    'BAM_File',
    'Sequencer',
    'chromosome_name',
    'start',
    'stop',
    'reference',
    'variant',
    'type',
    'gene_name',
    'transcript_name',
    'transcript_species',
    'transcript_source',
    'transcript_version',
    'strand',
    'transcript_status',
    'trv_type',
    'c_position',
    'amino_acid_change',
    'ucsc_cons',
    'domain',
    'all_domains',
    'deletion_substructures',
    'transcript_error',
    'Uniprot Sprot ID',
    'Uniprot Trembl ID',
    'Mutation Annotation (uniprot isoform1)',
    'Mutation Annotation (Others)',
    'ANNOVAR'
]

INCLUDE_FIELDS = [
    'Variant_Classification',
    'Variant_Type',
    'Reference_Allele',
    'Tumor_Seq_Allele1',
    'Tumor_Seq_Allele2',
    'Match_Norm_Seq_Allele1',
    'Match_Norm_Seq_Allele2',
    'Tumor_Sample_Barcode',
    'c_position',
    'ucsc_cons'
]


text:
<!DOCTYPE HTML>

		<meta http-equiv="Content-Type" content="html/html; charset=utf-8" />
		<title>ESTSimulatedNearableManager Class Reference</title>
		<meta id="xcode-display" name="xcode-display" content="render"/>
		<link rel="stylesheet" type="text/css" href="../css/styles.css" media="all" />
		<link rel="stylesheet" type="text/css" media="print" href="../css/stylesPrint.css" />
		<meta name="generator" content="appledoc 2.2 (build 963)" />

EstimoteSDK

				Estimote

ESTSimulatedNearableManager Class Reference

					<button aria-label="Show Table of Contents" role="checkbox" class="open" id="table_of_contents">Table of Contents</button>

					<select id="jumpTo">
	<option value="top">Jump To…</option>

	<option value="overview">Overview</option>

	<option value="tasks">Tasks</option>

	<option value="properties">Properties</option>

	<option value="//api/name/nearables">    nearables</option>

	<option value="instance_methods">Instance Methods</option>

	<option value="//api/name/addNearableToSimulation:withType:zone:rssi:">    - addNearableToSimulation:withType:zone:rssi:</option>

	<option value="//api/name/addNearablesToSimulationWithPath:">    - addNearablesToSimulationWithPath:</option>

	<option value="//api/name/initWithDelegate:">    - initWithDelegate:</option>

	<option value="//api/name/initWithDelegate:pathForJSON:">    - initWithDelegate:pathForJSON:</option>

	<option value="//api/name/nearableManager:didEnterIdentifierRegion:">    - nearableManager:didEnterIdentifierRegion:</option>

	<option value="//api/name/nearableManager:didExitIdentifierRegion:">    - nearableManager:didExitIdentifierRegion:</option>

	<option value="//api/name/nearableManager:didRangeNearable:">    - nearableManager:didRangeNearable:</option>

	<option value="//api/name/nearableManager:didRangeNearables:withType:">    - nearableManager:didRangeNearables:withType:</option>

	<option value="//api/name/simulateDidEnterRegionForNearable:">    - simulateDidEnterRegionForNearable:</option>

	<option value="//api/name/simulateDidExitRegionForNearable:">    - simulateDidExitRegionForNearable:</option>

	<option value="//api/name/simulateZone:forNearable:">    - simulateZone:forNearable:</option>

	<option value="//api/name/startRangingForIdentifier:">    - startRangingForIdentifier:</option>

	<option value="//api/name/startRangingForType:">    - startRangingForType:</option>

	<option value="//api/name/stopRanging">    - stopRanging</option>

	<option value="//api/name/stopRangingForIdentifier:">    - stopRangingForIdentifier:</option>

	<option value="//api/name/stopRangingForType:">    - stopRangingForType:</option>

</select>

Overview

Tasks

Ranging delegate methods

Properties

nearables

Instance Methods

addNearableToSimulation:withType:zone:rssi:

addNearablesToSimulationWithPath:

initWithDelegate:

initWithDelegate:pathForJSON:

nearableManager:didEnterIdentifierRegion:

nearableManager:didExitIdentifierRegion:

nearableManager:didRangeNearable:

nearableManager:didRangeNearables:withType:

simulateDidEnterRegionForNearable:

simulateDidExitRegionForNearable:

simulateZone:forNearable:

startRangingForIdentifier:

startRangingForType:

stopRanging

stopRangingForIdentifier:

stopRangingForType:

Index

Hierarchy

ESTSimulatedNearableManager Class Reference

	Inherits from
	ESTNearableManager : NSObject

	Conforms to
	ESTNearableManagerDelegate

	Declared in
	ESTSimulatedNearableManager.h
ESTSimulatedNearableManager.m

Overview

ESTSimulatedNearableManager is a class for simulating Nearables (ESTNearable) objects.

Tasks

Other Methods

		  nearables

	property

		– initWithDelegate:

		– initWithDelegate:pathForJSON:

		– addNearableToSimulation:withType:zone:rssi:

		– addNearablesToSimulationWithPath:

		– simulateZone:forNearable:

		– simulateDidEnterRegionForNearable:

		– simulateDidExitRegionForNearable:

Ranging delegate methods

		– startRangingForIdentifier:

		– stopRangingForIdentifier:

		– startRangingForType:

		– stopRangingForType:

		– stopRanging

		– nearableManager:didRangeNearable:

		– nearableManager:didRangeNearables:withType:

		– nearableManager:didEnterIdentifierRegion:

		– nearableManager:didExitIdentifierRegion:

Properties

nearables

Array with simulated ESTNearable objects.

@property (nonatomic, strong, readonly) NSMutableArray *nearables

Declared In

		ESTSimulatedNearableManager.h

Instance Methods

addNearableToSimulation:withType:zone:rssi:

Add single nearable by specifying params. ESTNearable object
will be inserted into nearables array.

- (void)addNearableToSimulation:(NSString *)identifier withType:(ESTNearableType)type zone:(ESTNearableZone)zone rssi:(NSInteger)rssi

Parameters

identifier

Identifier for ESTNearable object.

type

Nearable type

zone

Nearable zone

Declared In

		ESTSimulatedNearableManager.h

addNearablesToSimulationWithPath:

If you used initWithDelegate: initializer to create this class
and later you want to range nearables with type, use this method
to set array of nearables.

- (void)addNearablesToSimulationWithPath:(NSString *)path

Parameters

path

Path for json file with description of nearables you want to simulate.

Declared In

		ESTSimulatedNearableManager.h

initWithDelegate:

Initializer with delegate.

- (instancetype)initWithDelegate:(id<ESTNearableManagerDelegate>)delegate

Parameters

delegate

Set delegate for ESTNearableManagerDelegate updates.

Return Value

Instance of this object.

Declared In

		ESTSimulatedNearableManager.h

initWithDelegate:pathForJSON:

Use this initializer if you want to specify nearables in JSON.
Providing only filename is sufficient, but remember that your file
should be *.json type and accessible from MainBundle.
By default, order of nearables in the list will be reflected in nearables array,
which means, this class do not provide simulation of fluctuating RSSI or proximity.
However, you can set those values in JSON file, they will be parsed into ESTNearable object.

- (instancetype)initWithDelegate:(id<ESTNearableManagerDelegate>)delegate pathForJSON:(NSString *)path

Parameters

delegate

Set delegate for ESTNearableManagerDelegate updates.

pathForJSON

Path for json file with description of nearables you want to simulate.

Return Value

Instance of this object.

Declared In

		ESTSimulatedNearableManager.h

nearableManager:didEnterIdentifierRegion:

Tells the delegate that the user entered region of specified nearable identifier.

- (void)nearableManager:(ESTNearableManager *)manager didEnterIdentifierRegion:(NSString *)identifier

Parameters

manager

The nearable manager object reporting the event.

region

The nearable identifier region that was entered.

Declared In

		ESTNearableManager.h

nearableManager:didExitIdentifierRegion:

Tells the delegate that the user left the region of specified nearable identifier.

- (void)nearableManager:(ESTNearableManager *)manager didExitIdentifierRegion:(NSString *)identifier

Parameters

manager

The nearable manager object reporting the event.

region

The nearable identifier region that was exited.

Declared In

		ESTNearableManager.h

nearableManager:didRangeNearable:

Tells the delegate that nearable with particular identifier is in range.

- (void)nearableManager:(ESTNearableManager *)manager didRangeNearable:(ESTNearable *)nearable

Parameters

manager

The nearable manager object reporting the event.

nearables

An ESTNearable object representing the nearables currently in range. You can use the information in these objects to determine the range of nearable and its identifying information.

Declared In

		ESTNearableManager.h

nearableManager:didRangeNearables:withType:

Tells the delegate that one or more nearables are in range.

- (void)nearableManager:(ESTNearableManager *)manager didRangeNearables:(NSArray *)nearables withType:(ESTNearableType)type

Parameters

manager

The nearable manager object reporting the event.

nearables

An array of ESTNearable objects representing the nearables currently in range. You can use the information in these objects to determine the range of each nearables and its identifying information.

type

The nearable type that was used to range the nearables.

Declared In

		ESTNearableManager.h

simulateDidEnterRegionForNearable:

Simulate enter region event for your nearable.
Ranging will automatically start after calling this method.
Callback method is nearableManager:didEnterIdentifierRegion from ESTNearableManagerDelegate protocol.
If you do not implement didEnterIdentifierRegion code will crash,
it’s not checking whether delegate implemented method or not.
This is ‘by design’. During testing you probably want to know
when your class don’t implement ESTNearableManager delegates.

- (void)simulateDidEnterRegionForNearable:(ESTNearable *)nearable

Parameters

nearable

Nearable object for this event.

Declared In

		ESTSimulatedNearableManager.h

simulateDidExitRegionForNearable:

Simulate exit region event for your nearable.
Ranging will automatically stop after calling this method.
Callback method is nearableManager:didExitIdentifierRegion from ESTNearableManagerDelegate protocol.
If you do not implement didExitIdentifierRegion code will crash,
it’s not checking whether delegate implemented method or not.
This is ‘by design’. During testing you probably want to know
when your class don’t implement ESTNearableManager delegates.

- (void)simulateDidExitRegionForNearable:(ESTNearable *)nearable

Parameters

nearable

Nearable object for this event.

Declared In

		ESTSimulatedNearableManager.h

simulateZone:forNearable:

Set desired zone for your simulated ESTNearableObject.

- (void)simulateZone:(ESTNearableZone)zone forNearable:(NSString *)identifier

Parameters

zone

ESTNearableZone to set.

nearable

ESTNearable object you want to change.

Declared In

		ESTSimulatedNearableManager.h

startRangingForIdentifier:

Starts the delivery of notifications for nearables with specified identifier.

- (void)startRangingForIdentifier:(NSString *)identifier

Parameters

identifier

The identifier of nearables. This parameter must not be nil

Discussion

Once registered, the nearable manager reports any encountered nearable to its delegate by calling the [ESTNearableManagerDelegate nearableManager:didRangeNearable:] method. If there is an error registering the specified nearable type, the nearable manager calls its delegate’s [ESTNearableManagerDelegate nearableManager:rangingFailedWithError:] method and provides the appropriate error information.

See Also

- stopRangingForType:

Declared In

		ESTNearableManager.h

startRangingForType:

Starts the delivery of notifications for nearables with specified type.

- (void)startRangingForType:(ESTNearableType)type

Parameters

type

The type of nearables. This parameter must not be nil

Discussion

Once registered, the nearable manager reports any encountered nearable to its delegate by calling the [ESTNearableManagerDelegate nearableManager:didRangeNearables:withType:] method. If there is an error registering the specified nearable type, the nearable manager calls its delegate’s [ESTNearableManagerDelegate nearableManager:rangingFailedWithError:] method and provides the appropriate error information.

See Also

- stopRangingForType:

Declared In

		ESTNearableManager.h

stopRanging

Stops ranging all types and identifiers that were ranged.

- (void)stopRanging

Discussion

If there is nothing currently being ranged, this method has no effect.

See Also

- stopRangingForIdentifier:

- stopRangingForType:

Declared In

		ESTNearableManager.h

stopRangingForIdentifier:

Stops the delivery of notifications for the specified nearable identifier.

- (void)stopRangingForIdentifier:(NSString *)identifier

Parameters

type

The type of nearables. This parameter must not be nil

See Also

nearableManager:- startRangingForType:

Declared In

		ESTNearableManager.h

stopRangingForType:

Stops the delivery of notifications for the specified nearable type.

- (void)stopRangingForType:(ESTNearableType)type

Parameters

type

The type of nearables. This parameter must not be nil

See Also

- startRangingForType:

Declared In

		ESTNearableManager.h

Index

Hierarchy

© 2015 Estimote. All rights reserved. (Last updated: 2015-09-10)

						Generated by appledoc 2.2 (build 963).