text:
/*--------------------------------------------------------
   MDIDEMO.C -- Multiple-Document Interface Demonstration
                (c) Charles Petzold, 1998
  --------------------------------------------------------*/

#include <windows.h>
#include "resource.h"

#define INIT_MENU_POS    0
#define HELLO_MENU_POS   2
#define RECT_MENU_POS    1

#define IDM_FIRSTCHILD   50000

LRESULT CALLBACK FrameWndProc  (HWND, UINT, WPARAM, LPARAM) ;
BOOL    CALLBACK CloseEnumProc (HWND, LPARAM) ;
LRESULT CALLBACK HelloWndProc  (HWND, UINT, WPARAM, LPARAM) ;
LRESULT CALLBACK RectWndProc   (HWND, UINT, WPARAM, LPARAM) ;

     // structure for storing data unique to each Hello child window

typedef struct tagHELLODATA
{
     UINT     iColor ;
     COLORREF clrText ;
}
HELLODATA, * PHELLODATA ;

     // structure for storing data unique to each Rect child window

typedef struct tagRECTDATA
{
     short cxClient ;
     short cyClient ;
}
RECTDATA, * PRECTDATA ;

     // global variables

TCHAR     szAppName[]    = TEXT ("MDIDemo") ;
TCHAR     szFrameClass[] = TEXT ("MdiFrame") ;
TCHAR     szHelloClass[] = TEXT ("MdiHelloChild") ;
TCHAR     szRectClass[]  = TEXT ("MdiRectChild") ;
HINSTANCE hInst ;
HMENU     hMenuInit, hMenuHello, hMenuRect ;
HMENU     hMenuInitWindow, hMenuHelloWindow, hMenuRectWindow ;

int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance,
                    PSTR szCmdLine, int iCmdShow)
{
     HACCEL   hAccel ;
     HWND     hwndFrame, hwndClient ;
     MSG      msg ;
     WNDCLASS wndclass ;

     hInst = hInstance ;

          // Register the frame window class

     wndclass.style         = CS_HREDRAW | CS_VREDRAW ;
     wndclass.lpfnWndProc   = FrameWndProc ;
     wndclass.cbClsExtra    = 0 ;
     wndclass.cbWndExtra    = 0 ;
     wndclass.hInstance     = hInstance ;
     wndclass.hIcon         = LoadIcon (NULL, IDI_APPLICATION) ;
     wndclass.hCursor       = LoadCursor (NULL, IDC_ARROW) ;
     wndclass.hbrBackground = (HBRUSH) (COLOR_APPWORKSPACE + 1) ;
     wndclass.lpszMenuName  = NULL ;
     wndclass.lpszClassName = szFrameClass ;

     if (!RegisterClass (&wndclass))
     {
          MessageBox (NULL, TEXT ("This program requires Windows NT!"),
                      szAppName, MB_ICONERROR) ;
          return 0 ;
     }

          // Register the Hello child window class

     wndclass.style         = CS_HREDRAW | CS_VREDRAW ;
     wndclass.lpfnWndProc   = HelloWndProc ;
     wndclass.cbClsExtra    = 0 ;
     wndclass.cbWndExtra    = sizeof (HANDLE) ;
     wndclass.hInstance     = hInstance ;
     wndclass.hIcon         = LoadIcon (NULL, IDI_APPLICATION) ;
     wndclass.hCursor       = LoadCursor (NULL, IDC_ARROW) ;
     wndclass.hbrBackground = (HBRUSH) GetStockObject (WHITE_BRUSH) ;
     wndclass.lpszMenuName  = NULL ;
     wndclass.lpszClassName = szHelloClass ;

     RegisterClass (&wndclass) ;

          // Register the Rect child window class

     wndclass.style         = CS_HREDRAW | CS_VREDRAW ;
     wndclass.lpfnWndProc   = RectWndProc ;
     wndclass.cbClsExtra    = 0 ;
     wndclass.cbWndExtra    = sizeof (HANDLE) ;
     wndclass.hInstance     = hInstance ;
     wndclass.hIcon         = LoadIcon (NULL, IDI_APPLICATION) ;
     wndclass.hCursor       = LoadCursor (NULL, IDC_ARROW) ;
     wndclass.hbrBackground = (HBRUSH) GetStockObject (WHITE_BRUSH) ;
     wndclass.lpszMenuName  = NULL ;
     wndclass.lpszClassName = szRectClass ;

     RegisterClass (&wndclass) ;

          // Obtain handles to three possible menus & submenus

     hMenuInit  = LoadMenu (hInstance, TEXT ("MdiMenuInit")) ;
     hMenuHello = LoadMenu (hInstance, TEXT ("MdiMenuHello")) ;
     hMenuRect  = LoadMenu (hInstance, TEXT ("MdiMenuRect")) ;

     hMenuInitWindow  = GetSubMenu (hMenuInit,   INIT_MENU_POS) ;
     hMenuHelloWindow = GetSubMenu (hMenuHello, HELLO_MENU_POS) ;
     hMenuRectWindow  = GetSubMenu (hMenuRect,   RECT_MENU_POS) ;

          // Load accelerator table

     hAccel = LoadAccelerators (hInstance, szAppName) ;

          // Create the frame window

     hwndFrame = CreateWindow (szFrameClass, TEXT ("MDI Demonstration"),
                               WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN,
                               CW_USEDEFAULT, CW_USEDEFAULT,
                               CW_USEDEFAULT, CW_USEDEFAULT,
                               NULL, hMenuInit, hInstance, NULL) ;

     hwndClient = GetWindow (hwndFrame, GW_CHILD) ;

     ShowWindow (hwndFrame, iCmdShow) ;
     UpdateWindow (hwndFrame) ;

          // Enter the modified message loop

     while (GetMessage (&msg, NULL, 0, 0))
     {
          if (!TranslateMDISysAccel (hwndClient, &msg) &&
              !TranslateAccelerator (hwndFrame, hAccel, &msg))
          {
               TranslateMessage (&msg) ;
               DispatchMessage (&msg) ;
          }
     }
          // Clean up by deleting unattached menus

     DestroyMenu (hMenuHello) ;
     DestroyMenu (hMenuRect) ;

     return msg.wParam ;
     }

LRESULT CALLBACK FrameWndProc (HWND hwnd, UINT message,
                               WPARAM wParam, LPARAM lParam)
{
     static HWND        hwndClient ;
     CLIENTCREATESTRUCT clientcreate ;
     HWND               hwndChild ;
     MDICREATESTRUCT    mdicreate ;

     switch (message)
     {
     case WM_CREATE:           // Create the client window

          clientcreate.hWindowMenu  = hMenuInitWindow ;
          clientcreate.idFirstChild = IDM_FIRSTCHILD ;

          hwndClient = CreateWindow (TEXT ("MDICLIENT"), NULL,
                                     WS_CHILD | WS_CLIPCHILDREN | WS_VISIBLE,
                                     0, 0, 0, 0, hwnd, (HMENU) 1, hInst,
                                     (PSTR) &clientcreate) ;
          return 0 ;

     case WM_COMMAND:
          switch (LOWORD (wParam))
          {
          case IDM_FILE_NEWHELLO:       // Create a Hello child window

               mdicreate.szClass = szHelloClass ;
               mdicreate.szTitle = TEXT ("Hello") ;
               mdicreate.hOwner  = hInst ;
               mdicreate.x       = CW_USEDEFAULT ;
               mdicreate.y       = CW_USEDEFAULT ;
               mdicreate.cx      = CW_USEDEFAULT ;
               mdicreate.cy      = CW_USEDEFAULT ;
               mdicreate.style   = 0 ;
               mdicreate.lParam  = 0 ;

               hwndChild = (HWND) SendMessage (hwndClient,
                                   WM_MDICREATE, 0,
                                   (LPARAM) (LPMDICREATESTRUCT) &mdicreate) ;
               return 0 ;

          case IDM_FILE_NEWRECT:        // Create a Rect child window

               mdicreate.szClass = szRectClass ;
               mdicreate.szTitle = TEXT ("Rectangles") ;
               mdicreate.hOwner  = hInst ;
               mdicreate.x       = CW_USEDEFAULT ;
               mdicreate.y       = CW_USEDEFAULT ;
               mdicreate.cx      = CW_USEDEFAULT ;
               mdicreate.cy      = CW_USEDEFAULT ;
               mdicreate.style   = 0 ;
               mdicreate.lParam  = 0 ;

               hwndChild = (HWND) SendMessage (hwndClient,
                                   WM_MDICREATE, 0,
                                   (LPARAM) (LPMDICREATESTRUCT) &mdicreate) ;
               return 0 ;

          case IDM_FILE_CLOSE:          // Close the active window

               hwndChild = (HWND) SendMessage (hwndClient,
                                               WM_MDIGETACTIVE, 0, 0) ;

               if (SendMessage (hwndChild, WM_QUERYENDSESSION, 0, 0))
                    SendMessage (hwndClient, WM_MDIDESTROY,
                                 (WPARAM) hwndChild, 0) ;
               return 0 ;

          case IDM_APP_EXIT:            // Exit the program

               SendMessage (hwnd, WM_CLOSE, 0, 0) ;
               return 0 ;

               // messages for arranging windows

          case IDM_WINDOW_TILE:
               SendMessage (hwndClient, WM_MDITILE, 0, 0) ;
               return 0 ;

          case IDM_WINDOW_CASCADE:
               SendMessage (hwndClient, WM_MDICASCADE, 0, 0) ;
               return 0 ;

          case IDM_WINDOW_ARRANGE:
               SendMessage (hwndClient, WM_MDIICONARRANGE, 0, 0) ;
               return 0 ;

          case IDM_WINDOW_CLOSEALL:     // Attempt to close all children

               EnumChildWindows (hwndClient, CloseEnumProc, 0) ;
               return 0 ;

          default:             // Pass to active child...

               hwndChild = (HWND) SendMessage (hwndClient,
                                               WM_MDIGETACTIVE, 0, 0) ;

               if (IsWindow (hwndChild))
                    SendMessage (hwndChild, WM_COMMAND, wParam, lParam) ;

               break ;        // ...and then to DefFrameProc
          }
          break ;

     case WM_QUERYENDSESSION:
     case WM_CLOSE:                      // Attempt to close all children

          SendMessage (hwnd, WM_COMMAND, IDM_WINDOW_CLOSEALL, 0) ;

          if (NULL != GetWindow (hwndClient, GW_CHILD))
               return 0 ;

          break ;   // i.e., call DefFrameProc

     case WM_DESTROY:
          PostQuitMessage (0) ;
          return 0 ;
     }
          // Pass unprocessed messages to DefFrameProc (not DefWindowProc)

     return DefFrameProc (hwnd, hwndClient, message, wParam, lParam) ;
}

BOOL CALLBACK CloseEnumProc (HWND hwnd, LPARAM lParam)
{
     if (GetWindow (hwnd, GW_OWNER))         // Check for icon title
          return TRUE ;

     SendMessage (GetParent (hwnd), WM_MDIRESTORE, (WPARAM) hwnd, 0) ;

     if (!SendMessage (hwnd, WM_QUERYENDSESSION, 0, 0))
          return TRUE ;

     SendMessage (GetParent (hwnd), WM_MDIDESTROY, (WPARAM) hwnd, 0) ;
     return TRUE ;
}

LRESULT CALLBACK HelloWndProc (HWND hwnd, UINT message,
                               WPARAM wParam, LPARAM lParam)
{
     static COLORREF clrTextArray[] = { RGB (0,   0, 0), RGB (255, 0,   0),
                                        RGB (0, 255, 0), RGB (  0, 0, 255),
                                        RGB (255, 255, 255) } ;
     static HWND     hwndClient, hwndFrame ;
     HDC             hdc ;
     HMENU           hMenu ;
     PHELLODATA      pHelloData ;
     PAINTSTRUCT     ps ;
     RECT            rect ;

     switch (message)
     {
     case WM_CREATE:
               // Allocate memory for window private data

          pHelloData = (PHELLODATA) HeapAlloc (GetProcessHeap (),
                              HEAP_ZERO_MEMORY, sizeof (HELLODATA)) ;

          pHelloData->iColor  = IDM_COLOR_BLACK ;
          pHelloData->clrText = RGB (0, 0, 0) ;
          SetWindowLong (hwnd, 0, (long) pHelloData) ;

               // Save some window handles

          hwndClient = GetParent (hwnd) ;
          hwndFrame  = GetParent (hwndClient) ;
          return 0 ;

     case WM_COMMAND:
          switch (LOWORD (wParam))
          {
          case IDM_COLOR_BLACK:
          case IDM_COLOR_RED:
          case IDM_COLOR_GREEN:
          case IDM_COLOR_BLUE:
          case IDM_COLOR_WHITE:
                    // Change the text color

               pHelloData = (PHELLODATA) GetWindowLong (hwnd, 0) ;

               hMenu = GetMenu (hwndFrame) ;

               CheckMenuItem (hMenu, pHelloData->iColor, MF_UNCHECKED) ;
               pHelloData->iColor = wParam ;
               CheckMenuItem (hMenu, pHelloData->iColor, MF_CHECKED) ;

               pHelloData->clrText = clrTextArray[wParam - IDM_COLOR_BLACK] ;

               InvalidateRect (hwnd, NULL, FALSE) ;
          }
          return 0 ;

     case WM_PAINT:
               // Paint the window

          hdc = BeginPaint (hwnd, &ps) ;

          pHelloData = (PHELLODATA) GetWindowLong (hwnd, 0) ;
          SetTextColor (hdc, pHelloData->clrText) ;

          GetClientRect (hwnd, &rect) ;

          DrawText (hdc, TEXT ("Hello, World!"), -1, &rect,
                    DT_SINGLELINE | DT_CENTER | DT_VCENTER) ;

          EndPaint (hwnd, &ps) ;
          return 0 ;

     case WM_MDIACTIVATE:
               // Set the Hello menu if gaining focus

          if (lParam == (LPARAM) hwnd)
               SendMessage (hwndClient, WM_MDISETMENU,
                            (WPARAM) hMenuHello, (LPARAM) hMenuHelloWindow) ;

               // Check or uncheck menu item

          pHelloData = (PHELLODATA) GetWindowLong (hwnd, 0) ;
          CheckMenuItem (hMenuHello, pHelloData->iColor,
                    (lParam == (LPARAM) hwnd) ? MF_CHECKED : MF_UNCHECKED) ;

               // Set the Init menu if losing focus

          if (lParam != (LPARAM) hwnd)
               SendMessage (hwndClient, WM_MDISETMENU, (WPARAM) hMenuInit,
                            (LPARAM) hMenuInitWindow) ;

          DrawMenuBar (hwndFrame) ;
          return 0 ;

     case WM_QUERYENDSESSION:
     case WM_CLOSE:
          if (IDOK != MessageBox (hwnd, TEXT ("OK to close window?"),
                                  TEXT ("Hello"),
                                  MB_ICONQUESTION | MB_OKCANCEL))
               return 0 ;

          break ;   // i.e., call DefMDIChildProc

     case WM_DESTROY:
          pHelloData = (PHELLODATA) GetWindowLong (hwnd, 0) ;
          HeapFree (GetProcessHeap (), 0, pHelloData) ;
          return 0 ;
     }
          // Pass unprocessed message to DefMDIChildProc

     return DefMDIChildProc (hwnd, message, wParam, lParam) ;
}

LRESULT CALLBACK RectWndProc (HWND hwnd, UINT message,
                              WPARAM wParam, LPARAM lParam)
{
     static HWND hwndClient, hwndFrame ;
     HBRUSH      hBrush ;
     HDC         hdc ;
     PRECTDATA   pRectData ;
     PAINTSTRUCT ps ;
     int         xLeft, xRight, yTop, yBottom ;
     short       nRed, nGreen, nBlue ;

     switch (message)
     {
     case WM_CREATE:
               // Allocate memory for window private data

          pRectData = (PRECTDATA) HeapAlloc (GetProcessHeap (),
                                   HEAP_ZERO_MEMORY, sizeof (RECTDATA)) ;

          SetWindowLong (hwnd, 0, (long) pRectData) ;

               // Start the timer going

          SetTimer (hwnd, 1, 250, NULL) ;

               // Save some window handles

          hwndClient = GetParent (hwnd) ;
          hwndFrame  = GetParent (hwndClient) ;
          return 0 ;

     case WM_SIZE:             // If not minimized, save the window size

          if (wParam != SIZE_MINIMIZED)
          {
               pRectData = (PRECTDATA) GetWindowLong (hwnd, 0) ;

               pRectData->cxClient = LOWORD (lParam) ;
               pRectData->cyClient = HIWORD (lParam) ;
          }

          break ;        // WM_SIZE must be processed by DefMDIChildProc

     case WM_TIMER:            // Display a random rectangle

          pRectData = (PRECTDATA) GetWindowLong (hwnd, 0) ;

          xLeft   = rand () % pRectData->cxClient ;
          xRight  = rand () % pRectData->cxClient ;
          yTop    = rand () % pRectData->cyClient ;
          yBottom = rand () % pRectData->cyClient ;
          nRed    = rand () & 255 ;
          nGreen  = rand () & 255 ;
          nBlue   = rand () & 255 ;

          hdc = GetDC (hwnd) ;
          hBrush = CreateSolidBrush (RGB (nRed, nGreen, nBlue)) ;
          SelectObject (hdc, hBrush) ;

          Rectangle (hdc, min (xLeft, xRight), min (yTop, yBottom),
               max (xLeft, xRight), max (yTop, yBottom)) ;

          ReleaseDC (hwnd, hdc) ;
          DeleteObject (hBrush) ;
          return 0 ;

     case WM_PAINT:            // Clear the window

          InvalidateRect (hwnd, NULL, TRUE) ;
          hdc = BeginPaint (hwnd, &ps) ;
          EndPaint (hwnd, &ps) ;
          return 0 ;

     case WM_MDIACTIVATE:      // Set the appropriate menu
          if (lParam == (LPARAM) hwnd)
               SendMessage (hwndClient, WM_MDISETMENU, (WPARAM) hMenuRect,
                            (LPARAM) hMenuRectWindow) ;
          else
               SendMessage (hwndClient, WM_MDISETMENU, (WPARAM) hMenuInit,
                            (LPARAM) hMenuInitWindow) ;

          DrawMenuBar (hwndFrame) ;
          return 0 ;

     case WM_DESTROY:
          pRectData = (PRECTDATA) GetWindowLong (hwnd, 0) ;
          HeapFree (GetProcessHeap (), 0, pRectData) ;
          KillTimer (hwnd, 1) ;
          return 0 ;
     }
          // Pass unprocessed message to DefMDIChildProc

     return DefMDIChildProc (hwnd, message, wParam, lParam) ;
}


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Diagnostics;

namespace Microsoft.CodeAnalysis.CSharp.Diagnostics.TypeStyle
{
    [DiagnosticAnalyzer(LanguageNames.CSharp)]
    internal sealed class CSharpUseExplicitTypeDiagnosticAnalyzer : CSharpTypeStyleDiagnosticAnalyzerBase
    {
        private static readonly LocalizableString s_Title =
            new LocalizableResourceString(nameof(CSharpFeaturesResources.Use_explicit_type), CSharpFeaturesResources.ResourceManager, typeof(CSharpFeaturesResources));

        private static readonly LocalizableString s_Message =
            new LocalizableResourceString(nameof(CSharpFeaturesResources.Use_explicit_type_instead_of_var), CSharpFeaturesResources.ResourceManager, typeof(CSharpFeaturesResources));

        protected override CSharpTypeStyleHelper Helper => CSharpUseExplicitTypeHelper.Instance;

        public CSharpUseExplicitTypeDiagnosticAnalyzer()
            : base(diagnosticId: IDEDiagnosticIds.UseExplicitTypeDiagnosticId,
                   title: s_Title,
                   message: s_Message)
        {
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php
  $directory_content  = array_filter(glob('*'), 'is_dir');
    foreach ($directory_content as $directory) {
      $directory_content_files = array_diff(scandir($directory), array('..', '.'));

      foreach ($directory_content_files as $directory_files){
          include $directory . '/' . $directory_files;
          $directory_file = basename($directory_files,'.php');
          echo $directory . '=>' . $directory_file . "<br>";
      }

    }

    new Ikigami\Controller\Controller();
    new Ikigami\Modal\Modal();
    new Ikigami\View\View();
?>


text:
goog.provide('webfont.UserAgent');

/**
 * A user agent string representation.
 *
 * This currently keeps a string and parsed `Version` representation
 * of version strings. This is done for backwards compatibility with
 * older versions of Typekit's KitJS when loaded through the Web Font
 * Loader. The old string based API is deprecated and will eventually
 * be removed.
 *
 * @export
 * @param {string} name
 * @param {webfont.Version} version
 * @param {string} engine
 * @param {webfont.Version} engineVersion
 * @param {string} platform
 * @param {webfont.Version} platformVersion
 * @param {number|undefined} documentMode
 * @param {!webfont.BrowserInfo} browserInfo
 * @constructor
 */
webfont.UserAgent = function(
    name,
    version,
    engine,
    engineVersion,
    platform,
    platformVersion,
    documentMode,
    browserInfo) {
  this.name_ = name;
  this.version_ = version;
  this.engine_ = engine;
  this.engineVersion_ = engineVersion;
  this.platform_ = platform;
  this.platformVersion_ = platformVersion;
  this.documentMode_ = documentMode;
  this.browserInfo_ = browserInfo;
};

goog.scope(function () {
  var UserAgent = webfont.UserAgent;

  /**
   * @export
   * @return {string}
   */
  UserAgent.prototype.getName = function() {
    return this.name_;
  };

  /**
   * @return {webfont.Version}
   */
  UserAgent.prototype.getVersion = function() {
    return this.version_;
  };

  /**
   * @export
   * @return {string}
   */
  UserAgent.prototype.getEngine = function() {
    return this.engine_;
  };

  /**
   * @return {webfont.Version}
   */
  UserAgent.prototype.getEngineVersion = function() {
    return this.engineVersion_;
  };

  /**
   * @export
   * @return {string}
   */
  UserAgent.prototype.getPlatform = function() {
    return this.platform_;
  };

  /**
   * @return {webfont.Version}
   */
  UserAgent.prototype.getPlatformVersion = function() {
    return this.platformVersion_;
  };

  /**
   * @export
   * @return {number|undefined}
   */
  UserAgent.prototype.getDocumentMode = function() {
    return this.documentMode_;
  };

  /**
   * @export
   * @return {webfont.BrowserInfo}
   */
  UserAgent.prototype.getBrowserInfo = function() {
    return this.browserInfo_;
  };
});


text:
@class NSDate, NSString;

@interface FBSessionManualTokenCachingStrategy : FBSessionTokenCachingStrategy
{
    NSString *_accessToken;
    NSDate *_expirationDate;
}

@property(copy) NSString *accessToken; // @synthesize accessToken=_accessToken;
- (void)cacheTokenInformation:(id)arg1;
- (void)clearToken;
- (void)dealloc;
@property(copy) NSDate *expirationDate; // @synthesize expirationDate=_expirationDate;
- (id)fetchTokenInformation;

@end


text:
<?php

namespace LiveTest;

class InvalidArgumentException extends \LiveTest\TestCase\Exception
{
    private $argument;

    public function __construct($message, $argument, $code = null, $previous = null)
    {
        $this->argument = $argument;
        parent::__construct($message, $code, $previous);
    }

    public function getArgument()
    {
        return $this->argument;
    }
}


text:
import errno
import os

from flask import current_app, abort
import ujson
import werkzeug.utils

def safe_mkdirs(path):
  if os.path.exists(path):
    return

  try:
    os.mkdir(path)
  except OSError as e:
    # Check for race conditions. If for some reason two threads/greenlets/whatever
    # tries to create the same dir at the same time, we will have an error thrown.
    if not (e.errno == errno.EEXIST and os.path.isdir(path)):
      raise

# ujson for both speed and compactness
def jsonify(**params):
  response = current_app.make_response(ujson.dumps(params))
  response.mimetype = "application/json"
  return response

# Project access control helpers

from functools import wraps
from kvkit import NotFoundError
from flask.ext.login import current_user
from .models import Project, User

def hook_user_to_projects(user):
  for email in user.emails:
    for project in Project.index("unregistered_owners", email):
      project.unregistered_owners.remove(email)
      project.owners.append(user.key)
      project.save()

    for project in Project.index("unregistered_collaborators", email):
      project.unregistered_collaborators.remove(email)
      project.collaborators.append(user.key)
      project.save()

def project_access_required(fn):
  """This will allow anyone who is currently registered in that project to
  access the project. Denying the rest. It requires a project_id. It will also
  resolve a project and pass that instance into the function as oppose to just
  passing project_id. Furthermore, if an user is found to be in unregistered,
  he will be moved into owner or participant list.

  This is a fairly heavy operation for now. We will probably need to speed it
  up in the future.
  """
  @wraps(fn)
  def wrapped(*args, **kwargs):
    project_id = kwargs.pop("project_id")
    if project_id is None:
      raise ValueError("Project_id is required! This is probably a programming error.")

    if not current_user.is_authenticated():
      return abort(403)

    try:
      project = Project.get(project_id)
    except NotFoundError:
      return abort(404)

    # Move users from unregistered to registered if found.
    for email in current_user.emails:
      for userkey in project.owners:
        if email in User.get(userkey).emails:
          return fn(project=project, *args, **kwargs)

      for userkey in project.collaborators:
        if email in User.get(userkey).emails:
          return fn(project=project, *args, **kwargs)

    return abort(403)
  return wrapped

def project_managers_required(fn):
  @wraps(fn)
  def wrapped(*args, **kwargs):
    project_id = kwargs.pop("project_id")
    if project_id is None:
      raise ValueError("Project_id is required! This is probably a programming error.")
    if not current_user.is_authenticated():
      return abort(403)

    try:
      project = Project.get(project_id)
    except NotFoundError:
      return abort(404)

    for email in current_user.emails:
      for userkey in project.owners:
        if email in User.get(userkey).emails:
          return fn(project=project, *args, **kwargs)

    return abort(403)
  return wrapped

from flask import request
from kvkit import ValidationError

def ensure_good_request(required_parameters, accepted_parameters=None, allow_json_none=False):
  """Ensure that the request is good. aborts with 400 otherwise.

  accepted_parameters and required_parameters are both sets. If accepted_parameters is None,
  it is then the same as required_parameters. len(required_parameters) <= len(accepted_parameters)
  """

  if accepted_parameters is None:
    accepted_parameters = required_parameters

  def decorator(f):
    @wraps(f)
    def fn(*args, **kwargs):
      if request.json:
        if len(request.json) > len(accepted_parameters) or len(request.json) < len(required_parameters):
          return abort(400)

        parameters_provided = set(request.json.keys())
        if not (parameters_provided >= required_parameters) or not (parameters_provided <= accepted_parameters):
          return abort(400)
      else:
        if not allow_json_none:
          return abort(400)

      try:
        return f(*args, **kwargs)
      except ValidationError:
        return abort(400)
    return fn

  return decorator

# Helper for markdown

import misaka
MARKDOWN_EXTENSIONS = misaka.EXT_FENCED_CODE | misaka.EXT_STRIKETHROUGH
HTML_FLAGS = misaka.HTML_ESCAPE | misaka.HTML_SMARTYPANTS | misaka.HTML_SAFELINK
def markdown_to_html(s):
  return misaka.html(s, MARKDOWN_EXTENSIONS, HTML_FLAGS)

def markdown_to_db(s):
  return {"markdown": s, "html": markdown_to_html(s)}

def parse_path(path, project_key):
  """Parses a path that is passed from the client securely.

  Returns a filesystem path as well as a key for db and if it is a directory.
  """
  path = path.lstrip("/")
  is_directory = (path[-1] == "")
  path = [werkzeug.utils.secure_filename(p.strip()) for p in path.split("/") if p.strip() not in ("..", ".")]
  if is_directory:
    path += "/"

  fspath = os.join(current_app.config["APP_FOLDER"], project_key, path)
  key = project_key + "`/" + path
  return key, fspath, is_directory

def secure_path(path):
  # SECURITY: please review
  path = path.lstrip(os.path.sep)

  temp = []
  for p in path.split(os.path.sep):
    p = werkzeug.utils.secure_filename(p)
    if p:
      temp.append(p)

  path = os.path.join(*temp)
  return path


text:
(function () {
	'use strict';

	angular.module('modulo.artigo', []);

})();


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using FakePoll.Helpers;
using Newtonsoft.Json.Linq;

namespace FakePoll
{
    class Program
    {
        static void Main(string[] args)
        {
            var stopwatch = Stopwatch.StartNew();
            Task.Run(ActionAsync).Wait();
            Console.WriteLine("Czas pracy " + stopwatch.Elapsed);
            Console.WriteLine("Nacisnij dowolny przycisk aby wyjsc z programu.");
            Console.ReadKey();
        }

        private static async Task ActionAsync()
        {
            Console.Write("Podaj ID ankiety:");
            var id = Console.ReadLine();
            var httpClient = HttpClientHelper.CreateHttpClient(WebProxy.GetDefaultProxy(), 10);

            var poll = await StrawpollRequests.GetPollAsync(httpClient, id);
            if (!poll.Votes.Any())
                throw new Exception("Podales niepoprawne ID ankiety!");

            for (int i = 0; i < poll.Votes.Count(); i++)
                Console.WriteLine($"ID:{i} Vote:{poll.Votes.ElementAt(i).Name}");

            Console.Write($"Wpisz ID vota:");

            int voteId = 0;
            if (!int.TryParse(Console.ReadLine(), out voteId) && voteId >= poll.Votes.Count())
                throw new Exception("Podałeś niepoprawne ID vota!");

            Console.Write("Podaj sciezke do pliku z proxy:");
            var proxyPath = Console.ReadLine();

            if (proxyPath == null)
                throw new NullReferenceException("Podana sciezka jest bledna!");

            if (!File.Exists(proxyPath))
                throw new Exception("Podany plik nie istnieje!");

            Console.Write("Max liczba glosow:");
            int max = 0;
            if (!int.TryParse(Console.ReadLine(), out max))
                throw new Exception("Podałeś niepoprawna liczbe głosow!");

            var lines = File.ReadAllLines(proxyPath);
            int total = lines.Length;
            int success = 0;
            int fail = 0;
            int threads = 0;

            Console.Write("Wpisz ilosc watkow:");
            if (!int.TryParse(Console.ReadLine(), out threads))
                throw new Exception("Podales nieporawna liczbe watkow!");

            var options = new ParallelOptions
            {
                MaxDegreeOfParallelism = threads,
            };

            Parallel.ForEach(lines, options, address =>
            {
                Task.Run(async () =>
                {
                    if (success <= max)
                    {
                        Console.WriteLine($"SUCKES:{success} FAIL:{fail} WOLNE:{Math.Abs((success + fail) - total)} WSZYSTKIE:{total}");
                        if (await ProxyHelpers.CheckProxyAsync(address))
                        {
                            try
                            {
                                    var client = HttpClientHelper.CreateHttpClient(new WebProxy(address), 10);
                                    var info = await StrawpollRequests.GetPollAsync(client, id);
                                    if (await StrawpollRequests.Vote(client, id, poll.Votes.ElementAt(voteId).ID, info.Token))
                                       success++;
                            }
                            catch (Exception)
                            {
                                fail++;
                            }
                        }
                        else
                        {
                            Console.WriteLine("Proxy nie odpowiada!");
                            fail++;
                        }
                    }
                }).Wait();
            });
        }
    }
}


text:
;(function() {
  /* START alipay page */
  var alipay_validator = new FormValidator('js-alipay-form', [{
    name: 'email',
    display: 'email',
    rules: 'required|valid_email'
  }, {
    name: 'username',
    rules: 'required|min_length[4]|max_length[15]'
  }], function(errors, event) {
    var validateNotes = {
      email: document.getElementById('js-alipay-email-vd-msg'),
      username: document.getElementById('js-alipay-username-vd-msg')
    };
    validateNotes.email.innerText = '';
    validateNotes.username.innerText = '';
    if (errors.length > 0) {
      errors.forEach(function(e) {
        validateNotes[e.name].innerText = e.message;
      });
    }
  });

  function alipay_switchPayType(e) {
    var submitElement = document.getElementById('js-alipay-form-submit');
    submitElement.value = e.target.dataset.svalue;
  }

  var alipay_paytypeElements = document.getElementsByClassName('js-alipay-form-paytype');
  alipay_paytypeElements.forEach(function (e) { e.onchange = alipay_switchPayType; });

  /* END alipay page */
})();


text:
using System;
using EasyRoslynScript;
using VMLab.Graph;
using VMLab.Helpers;
using CredentialSet = VMLab.Script.Fluent.CredentialSet;
using Template = VMLab.Script.Fluent.Template;
using VM = VMLab.Script.Fluent.VM;

namespace VMLab.Script
{
    public static class GraphScriptMethods
    {
        public static IGraphManager GraphManager { private get; set; }
        public static IConfig Config { private get; set; }

        public static VM VM(this IScriptContext context, string name)
        {
            return new VM(name, GraphManager, Config);
        }

        public static CredentialSet CredentialSet(this IScriptContext context, string name)
        {
            return new CredentialSet(name, GraphManager);
        }

        public static Template Template(this IScriptContext context, string name, string version)
        {
            return new Template(name, version, GraphManager, Config);
        }

        public static void Action(this IScriptContext context, string name, Action<ISession> action)
        {
            GraphManager.NewAction(name, action);
        }

        public static void Action(this IScriptContext context, string description, string name, Action<ISession> action)
        {
            GraphManager.NewAction(name, description, action);
        }

        public static void LockAction(this IScriptContext context, string action)
        {
            GraphManager.NewActionLock(action);
        }
    }
}


text:
package com.epam.ta.reportportal.core.item.identity;

import com.epam.ta.reportportal.dao.TestItemRepository;
import com.epam.ta.reportportal.entity.item.Parameter;
import com.epam.ta.reportportal.entity.item.TestItem;
import com.epam.ta.reportportal.entity.launch.Launch;
import com.google.common.base.Strings;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.StringJoiner;
import java.util.stream.Collectors;

/**
 * Generates the unique identifier for test item based
 * on Base64 encoding and includes information about project,
 * name of item's launch, full path of item's parent names,
 * item name and parameters.
 *
 * @author Pavel_Bortnik
 */
@Service
public class TestItemUniqueIdGenerator implements UniqueIdGenerator {

	private static final String TRAIT = "auto:";

	private TestItemRepository testItemRepository;

	@Autowired
	public void setTestItemRepository(TestItemRepository testItemRepository) {
		this.testItemRepository = testItemRepository;
	}

	@Override
	public String generate(TestItem testItem, List<Long> parentIds, Launch launch) {
		String forEncoding = prepareForEncoding(testItem, parentIds, launch);
		return TRAIT + DigestUtils.md5Hex(forEncoding);
	}

	@Override
	public boolean validate(String encoded) {
		return !Strings.isNullOrEmpty(encoded) && encoded.startsWith(TRAIT);
	}

	private String prepareForEncoding(TestItem testItem, List<Long> parentIds, Launch launch) {
		Long projectId = launch.getProjectId();
		String launchName = launch.getName();
		List<String> pathNames = getPathNames(parentIds);
		String itemName = testItem.getName();
		StringJoiner joiner = new StringJoiner(";");
		joiner.add(projectId.toString()).add(launchName);
		if (!CollectionUtils.isEmpty(pathNames)) {
			joiner.add(String.join(";", pathNames));
		}
		joiner.add(itemName);
		Set<Parameter> parameters = testItem.getParameters();
		if (!CollectionUtils.isEmpty(parameters)) {
			joiner.add(parameters.stream()
					.map(parameter -> (!Strings.isNullOrEmpty(parameter.getKey()) ? parameter.getKey() + "=" : "") + parameter.getValue())
					.collect(Collectors.joining(",")));
		}
		return joiner.toString();
	}

	private List<String> getPathNames(List<Long> parentIds) {
		return testItemRepository.findAllById(parentIds)
				.stream()
				.sorted(Comparator.comparingLong(TestItem::getItemId))
				.map(TestItem::getName)
				.collect(Collectors.toList());
	}
}


text:
package org.killbill.billing.plugin.ingenico.api;

import java.util.UUID;

import org.joda.time.DateTime;
import org.killbill.billing.plugin.api.PluginCallContext;

/**
 * Created by otaviosoares on 30/11/16.
 */
public class IngenicoCallContext extends PluginCallContext {

    private static final String INGENICO_PLUGIN = "Ingenico plugin";

    public IngenicoCallContext(final DateTime utcNow, final UUID kbTenantId) {
        super(INGENICO_PLUGIN, utcNow, kbTenantId);
    }
}


text:
import datetime
from typing import List, Optional, TYPE_CHECKING, Union

from .. import _serialization

if TYPE_CHECKING:
    # pylint: disable=unused-import,ungrouped-imports
    from .. import models as _models

class CommunicationError(_serialization.Model):
    """The Communication Services error.

    Variables are only populated by the server, and will be ignored when sending a request.

    All required parameters must be populated in order to send to Azure.

    :ivar code: The error code. Required.
    :vartype code: str
    :ivar message: The error message. Required.
    :vartype message: str
    :ivar target: The error target.
    :vartype target: str
    :ivar details: Further details about specific errors that led to this error.
    :vartype details: list[~azure.communication.phonenumbers.models.CommunicationError]
    :ivar inner_error: The inner error if any.
    :vartype inner_error: ~azure.communication.phonenumbers.models.CommunicationError
    """

    _validation = {
        "code": {"required": True},
        "message": {"required": True},
        "target": {"readonly": True},
        "details": {"readonly": True},
        "inner_error": {"readonly": True},
    }

    _attribute_map = {
        "code": {"key": "code", "type": "str"},
        "message": {"key": "message", "type": "str"},
        "target": {"key": "target", "type": "str"},
        "details": {"key": "details", "type": "[CommunicationError]"},
        "inner_error": {"key": "innererror", "type": "CommunicationError"},
    }

    def __init__(self, *, code: str, message: str, **kwargs):
        """
        :keyword code: The error code. Required.
        :paramtype code: str
        :keyword message: The error message. Required.
        :paramtype message: str
        """
        super().__init__(**kwargs)
        self.code = code
        self.message = message
        self.target = None
        self.details = None
        self.inner_error = None

class CommunicationErrorResponse(_serialization.Model):
    """The Communication Services error.

    All required parameters must be populated in order to send to Azure.

    :ivar error: The Communication Services error. Required.
    :vartype error: ~azure.communication.phonenumbers.models.CommunicationError
    """

    _validation = {
        "error": {"required": True},
    }

    _attribute_map = {
        "error": {"key": "error", "type": "CommunicationError"},
    }

    def __init__(self, *, error: "_models.CommunicationError", **kwargs):
        """
        :keyword error: The Communication Services error. Required.
        :paramtype error: ~azure.communication.phonenumbers.models.CommunicationError
        """
        super().__init__(**kwargs)
        self.error = error

class PhoneNumberCapabilities(_serialization.Model):
    """Capabilities of a phone number.

    All required parameters must be populated in order to send to Azure.

    :ivar calling: Capability value for calling. Required. Known values are: "none", "inbound",
     "outbound", and "inbound+outbound".
    :vartype calling: str or ~azure.communication.phonenumbers.models.PhoneNumberCapabilityType
    :ivar sms: Capability value for SMS. Required. Known values are: "none", "inbound", "outbound",
     and "inbound+outbound".
    :vartype sms: str or ~azure.communication.phonenumbers.models.PhoneNumberCapabilityType
    """

    _validation = {
        "calling": {"required": True},
        "sms": {"required": True},
    }

    _attribute_map = {
        "calling": {"key": "calling", "type": "str"},
        "sms": {"key": "sms", "type": "str"},
    }

    def __init__(
        self,
        *,
        calling: Union[str, "_models.PhoneNumberCapabilityType"],
        sms: Union[str, "_models.PhoneNumberCapabilityType"],
        **kwargs
    ):
        """
        :keyword calling: Capability value for calling. Required. Known values are: "none", "inbound",
         "outbound", and "inbound+outbound".
        :paramtype calling: str or ~azure.communication.phonenumbers.models.PhoneNumberCapabilityType
        :keyword sms: Capability value for SMS. Required. Known values are: "none", "inbound",
         "outbound", and "inbound+outbound".
        :paramtype sms: str or ~azure.communication.phonenumbers.models.PhoneNumberCapabilityType
        """
        super().__init__(**kwargs)
        self.calling = calling
        self.sms = sms

class PhoneNumberCapabilitiesRequest(_serialization.Model):
    """Capabilities of a phone number.

    :ivar calling: Capability value for calling. Known values are: "none", "inbound", "outbound",
     and "inbound+outbound".
    :vartype calling: str or ~azure.communication.phonenumbers.models.PhoneNumberCapabilityType
    :ivar sms: Capability value for SMS. Known values are: "none", "inbound", "outbound", and
     "inbound+outbound".
    :vartype sms: str or ~azure.communication.phonenumbers.models.PhoneNumberCapabilityType
    """

    _attribute_map = {
        "calling": {"key": "calling", "type": "str"},
        "sms": {"key": "sms", "type": "str"},
    }

    def __init__(
        self,
        *,
        calling: Optional[Union[str, "_models.PhoneNumberCapabilityType"]] = None,
        sms: Optional[Union[str, "_models.PhoneNumberCapabilityType"]] = None,
        **kwargs
    ):
        """
        :keyword calling: Capability value for calling. Known values are: "none", "inbound",
         "outbound", and "inbound+outbound".
        :paramtype calling: str or ~azure.communication.phonenumbers.models.PhoneNumberCapabilityType
        :keyword sms: Capability value for SMS. Known values are: "none", "inbound", "outbound", and
         "inbound+outbound".
        :paramtype sms: str or ~azure.communication.phonenumbers.models.PhoneNumberCapabilityType
        """
        super().__init__(**kwargs)
        self.calling = calling
        self.sms = sms

class PhoneNumberCost(_serialization.Model):
    """The incurred cost for a single phone number.

    All required parameters must be populated in order to send to Azure.

    :ivar amount: The cost amount. Required.
    :vartype amount: float
    :ivar currency_code: The ISO 4217 currency code for the cost amount, e.g. USD. Required.
    :vartype currency_code: str
    :ivar billing_frequency: The frequency with which the cost gets billed. Required. "monthly"
    :vartype billing_frequency: str or ~azure.communication.phonenumbers.models.BillingFrequency
    """

    _validation = {
        "amount": {"required": True},
        "currency_code": {"required": True},
        "billing_frequency": {"required": True},
    }

    _attribute_map = {
        "amount": {"key": "amount", "type": "float"},
        "currency_code": {"key": "currencyCode", "type": "str"},
        "billing_frequency": {"key": "billingFrequency", "type": "str"},
    }

    def __init__(
        self, *, amount: float, currency_code: str, billing_frequency: Union[str, "_models.BillingFrequency"], **kwargs
    ):
        """
        :keyword amount: The cost amount. Required.
        :paramtype amount: float
        :keyword currency_code: The ISO 4217 currency code for the cost amount, e.g. USD. Required.
        :paramtype currency_code: str
        :keyword billing_frequency: The frequency with which the cost gets billed. Required. "monthly"
        :paramtype billing_frequency: str or ~azure.communication.phonenumbers.models.BillingFrequency
        """
        super().__init__(**kwargs)
        self.amount = amount
        self.currency_code = currency_code
        self.billing_frequency = billing_frequency

class PhoneNumberOperation(_serialization.Model):
    """Long running operation.

    Variables are only populated by the server, and will be ignored when sending a request.

    All required parameters must be populated in order to send to Azure.

    :ivar status: Status of operation. Required. Known values are: "notStarted", "running",
     "succeeded", and "failed".
    :vartype status: str or ~azure.communication.phonenumbers.models.PhoneNumberOperationStatus
    :ivar resource_location: URL for retrieving the result of the operation, if any.
    :vartype resource_location: str
    :ivar created_date_time: The date that the operation was created. Required.
    :vartype created_date_time: ~datetime.datetime
    :ivar error: The Communication Services error.
    :vartype error: ~azure.communication.phonenumbers.models.CommunicationError
    :ivar id: Id of operation. Required.
    :vartype id: str
    :ivar operation_type: The type of operation, e.g. Search. Required. Known values are:
     "purchase", "releasePhoneNumber", "search", and "updatePhoneNumberCapabilities".
    :vartype operation_type: str or
     ~azure.communication.phonenumbers.models.PhoneNumberOperationType
    :ivar last_action_date_time: The most recent date that the operation was changed.
    :vartype last_action_date_time: ~datetime.datetime
    """

    _validation = {
        "status": {"required": True},
        "created_date_time": {"required": True},
        "id": {"required": True},
        "operation_type": {"required": True},
        "last_action_date_time": {"readonly": True},
    }

    _attribute_map = {
        "status": {"key": "status", "type": "str"},
        "resource_location": {"key": "resourceLocation", "type": "str"},
        "created_date_time": {"key": "createdDateTime", "type": "iso-8601"},
        "error": {"key": "error", "type": "CommunicationError"},
        "id": {"key": "id", "type": "str"},
        "operation_type": {"key": "operationType", "type": "str"},
        "last_action_date_time": {"key": "lastActionDateTime", "type": "iso-8601"},
    }

    def __init__(
        self,
        *,
        status: Union[str, "_models.PhoneNumberOperationStatus"],
        created_date_time: datetime.datetime,
        id: str,  # pylint: disable=redefined-builtin
        operation_type: Union[str, "_models.PhoneNumberOperationType"],
        resource_location: Optional[str] = None,
        error: Optional["_models.CommunicationError"] = None,
        **kwargs
    ):
        """
        :keyword status: Status of operation. Required. Known values are: "notStarted", "running",
         "succeeded", and "failed".
        :paramtype status: str or ~azure.communication.phonenumbers.models.PhoneNumberOperationStatus
        :keyword resource_location: URL for retrieving the result of the operation, if any.
        :paramtype resource_location: str
        :keyword created_date_time: The date that the operation was created. Required.
        :paramtype created_date_time: ~datetime.datetime
        :keyword error: The Communication Services error.
        :paramtype error: ~azure.communication.phonenumbers.models.CommunicationError
        :keyword id: Id of operation. Required.
        :paramtype id: str
        :keyword operation_type: The type of operation, e.g. Search. Required. Known values are:
         "purchase", "releasePhoneNumber", "search", and "updatePhoneNumberCapabilities".
        :paramtype operation_type: str or
         ~azure.communication.phonenumbers.models.PhoneNumberOperationType
        """
        super().__init__(**kwargs)
        self.status = status
        self.resource_location = resource_location
        self.created_date_time = created_date_time
        self.error = error
        self.id = id
        self.operation_type = operation_type
        self.last_action_date_time = None

class PhoneNumberPurchaseRequest(_serialization.Model):
    """The phone number search purchase request.

    :ivar search_id: The search id.
    :vartype search_id: str
    """

    _attribute_map = {
        "search_id": {"key": "searchId", "type": "str"},
    }

    def __init__(self, *, search_id: Optional[str] = None, **kwargs):
        """
        :keyword search_id: The search id.
        :paramtype search_id: str
        """
        super().__init__(**kwargs)
        self.search_id = search_id

class PhoneNumberSearchRequest(_serialization.Model):
    """Represents a phone number search request to find phone numbers. Found phone numbers are temporarily held for a following purchase.

    All required parameters must be populated in order to send to Azure.

    :ivar phone_number_type: The type of phone numbers to search for, e.g. geographic, or tollFree.
     Required. Known values are: "geographic" and "tollFree".
    :vartype phone_number_type: str or ~azure.communication.phonenumbers.models.PhoneNumberType
    :ivar assignment_type: The assignment type of the phone numbers to search for. A phone number
     can be assigned to a person, or to an application. Required. Known values are: "person" and
     "application".
    :vartype assignment_type: str or
     ~azure.communication.phonenumbers.models.PhoneNumberAssignmentType
    :ivar capabilities: Capabilities of a phone number. Required.
    :vartype capabilities: ~azure.communication.phonenumbers.models.PhoneNumberCapabilities
    :ivar area_code: The area code of the desired phone number, e.g. 425.
    :vartype area_code: str
    :ivar quantity: The quantity of desired phone numbers. The default value is 1.
    :vartype quantity: int
    """

    _validation = {
        "phone_number_type": {"required": True},
        "assignment_type": {"required": True},
        "capabilities": {"required": True},
        "quantity": {"maximum": 2147483647, "minimum": 1},
    }

    _attribute_map = {
        "phone_number_type": {"key": "phoneNumberType", "type": "str"},
        "assignment_type": {"key": "assignmentType", "type": "str"},
        "capabilities": {"key": "capabilities", "type": "PhoneNumberCapabilities"},
        "area_code": {"key": "areaCode", "type": "str"},
        "quantity": {"key": "quantity", "type": "int"},
    }

    def __init__(
        self,
        *,
        phone_number_type: Union[str, "_models.PhoneNumberType"],
        assignment_type: Union[str, "_models.PhoneNumberAssignmentType"],
        capabilities: "_models.PhoneNumberCapabilities",
        area_code: Optional[str] = None,
        quantity: int = 1,
        **kwargs
    ):
        """
        :keyword phone_number_type: The type of phone numbers to search for, e.g. geographic, or
         tollFree. Required. Known values are: "geographic" and "tollFree".
        :paramtype phone_number_type: str or ~azure.communication.phonenumbers.models.PhoneNumberType
        :keyword assignment_type: The assignment type of the phone numbers to search for. A phone
         number can be assigned to a person, or to an application. Required. Known values are: "person"
         and "application".
        :paramtype assignment_type: str or
         ~azure.communication.phonenumbers.models.PhoneNumberAssignmentType
        :keyword capabilities: Capabilities of a phone number. Required.
        :paramtype capabilities: ~azure.communication.phonenumbers.models.PhoneNumberCapabilities
        :keyword area_code: The area code of the desired phone number, e.g. 425.
        :paramtype area_code: str
        :keyword quantity: The quantity of desired phone numbers. The default value is 1.
        :paramtype quantity: int
        """
        super().__init__(**kwargs)
        self.phone_number_type = phone_number_type
        self.assignment_type = assignment_type
        self.capabilities = capabilities
        self.area_code = area_code
        self.quantity = quantity

class PhoneNumberSearchResult(_serialization.Model):
    """The result of a phone number search operation.

    All required parameters must be populated in order to send to Azure.

    :ivar search_id: The search id. Required.
    :vartype search_id: str
    :ivar phone_numbers: The phone numbers that are available. Can be fewer than the desired search
     quantity. Required.
    :vartype phone_numbers: list[str]
    :ivar phone_number_type: The phone number's type, e.g. geographic, or tollFree. Required. Known
     values are: "geographic" and "tollFree".
    :vartype phone_number_type: str or ~azure.communication.phonenumbers.models.PhoneNumberType
    :ivar assignment_type: Phone number's assignment type. Required. Known values are: "person" and
     "application".
    :vartype assignment_type: str or
     ~azure.communication.phonenumbers.models.PhoneNumberAssignmentType
    :ivar capabilities: Capabilities of a phone number. Required.
    :vartype capabilities: ~azure.communication.phonenumbers.models.PhoneNumberCapabilities
    :ivar cost: The incurred cost for a single phone number. Required.
    :vartype cost: ~azure.communication.phonenumbers.models.PhoneNumberCost
    :ivar search_expires_by: The date that this search result expires and phone numbers are no
     longer on hold. A search result expires in less than 15min, e.g. 2020-11-19T16:31:49.048Z.
     Required.
    :vartype search_expires_by: ~datetime.datetime
    """

    _validation = {
        "search_id": {"required": True},
        "phone_numbers": {"required": True},
        "phone_number_type": {"required": True},
        "assignment_type": {"required": True},
        "capabilities": {"required": True},
        "cost": {"required": True},
        "search_expires_by": {"required": True},
    }

    _attribute_map = {
        "search_id": {"key": "searchId", "type": "str"},
        "phone_numbers": {"key": "phoneNumbers", "type": "[str]"},
        "phone_number_type": {"key": "phoneNumberType", "type": "str"},
        "assignment_type": {"key": "assignmentType", "type": "str"},
        "capabilities": {"key": "capabilities", "type": "PhoneNumberCapabilities"},
        "cost": {"key": "cost", "type": "PhoneNumberCost"},
        "search_expires_by": {"key": "searchExpiresBy", "type": "iso-8601"},
    }

    def __init__(
        self,
        *,
        search_id: str,
        phone_numbers: List[str],
        phone_number_type: Union[str, "_models.PhoneNumberType"],
        assignment_type: Union[str, "_models.PhoneNumberAssignmentType"],
        capabilities: "_models.PhoneNumberCapabilities",
        cost: "_models.PhoneNumberCost",
        search_expires_by: datetime.datetime,
        **kwargs
    ):
        """
        :keyword search_id: The search id. Required.
        :paramtype search_id: str
        :keyword phone_numbers: The phone numbers that are available. Can be fewer than the desired
         search quantity. Required.
        :paramtype phone_numbers: list[str]
        :keyword phone_number_type: The phone number's type, e.g. geographic, or tollFree. Required.
         Known values are: "geographic" and "tollFree".
        :paramtype phone_number_type: str or ~azure.communication.phonenumbers.models.PhoneNumberType
        :keyword assignment_type: Phone number's assignment type. Required. Known values are: "person"
         and "application".
        :paramtype assignment_type: str or
         ~azure.communication.phonenumbers.models.PhoneNumberAssignmentType
        :keyword capabilities: Capabilities of a phone number. Required.
        :paramtype capabilities: ~azure.communication.phonenumbers.models.PhoneNumberCapabilities
        :keyword cost: The incurred cost for a single phone number. Required.
        :paramtype cost: ~azure.communication.phonenumbers.models.PhoneNumberCost
        :keyword search_expires_by: The date that this search result expires and phone numbers are no
         longer on hold. A search result expires in less than 15min, e.g. 2020-11-19T16:31:49.048Z.
         Required.
        :paramtype search_expires_by: ~datetime.datetime
        """
        super().__init__(**kwargs)
        self.search_id = search_id
        self.phone_numbers = phone_numbers
        self.phone_number_type = phone_number_type
        self.assignment_type = assignment_type
        self.capabilities = capabilities
        self.cost = cost
        self.search_expires_by = search_expires_by

class PurchasedPhoneNumber(_serialization.Model):
    """Represents a purchased phone number.

    All required parameters must be populated in order to send to Azure.

    :ivar id: The id of the phone number, e.g. 11234567890. Required.
    :vartype id: str
    :ivar phone_number: String of the E.164 format of the phone number, e.g. +11234567890.
     Required.
    :vartype phone_number: str
    :ivar country_code: The ISO 3166-2 code of the phone number's country, e.g. US. Required.
    :vartype country_code: str
    :ivar phone_number_type: The phone number's type, e.g. Geographic, TollFree. Required. Known
     values are: "geographic" and "tollFree".
    :vartype phone_number_type: str or ~azure.communication.phonenumbers.models.PhoneNumberType
    :ivar capabilities: Capabilities of a phone number. Required.
    :vartype capabilities: ~azure.communication.phonenumbers.models.PhoneNumberCapabilities
    :ivar assignment_type: The assignment type of the phone number. A phone number can be assigned
     to a person, or to an application. Required. Known values are: "person" and "application".
    :vartype assignment_type: str or
     ~azure.communication.phonenumbers.models.PhoneNumberAssignmentType
    :ivar purchase_date: The date and time that the phone number was purchased. Required.
    :vartype purchase_date: ~datetime.datetime
    :ivar cost: The incurred cost for a single phone number. Required.
    :vartype cost: ~azure.communication.phonenumbers.models.PhoneNumberCost
    """

    _validation = {
        "id": {"required": True},
        "phone_number": {"required": True},
        "country_code": {"required": True},
        "phone_number_type": {"required": True},
        "capabilities": {"required": True},
        "assignment_type": {"required": True},
        "purchase_date": {"required": True},
        "cost": {"required": True},
    }

    _attribute_map = {
        "id": {"key": "id", "type": "str"},
        "phone_number": {"key": "phoneNumber", "type": "str"},
        "country_code": {"key": "countryCode", "type": "str"},
        "phone_number_type": {"key": "phoneNumberType", "type": "str"},
        "capabilities": {"key": "capabilities", "type": "PhoneNumberCapabilities"},
        "assignment_type": {"key": "assignmentType", "type": "str"},
        "purchase_date": {"key": "purchaseDate", "type": "iso-8601"},
        "cost": {"key": "cost", "type": "PhoneNumberCost"},
    }

    def __init__(
        self,
        *,
        id: str,  # pylint: disable=redefined-builtin
        phone_number: str,
        country_code: str,
        phone_number_type: Union[str, "_models.PhoneNumberType"],
        capabilities: "_models.PhoneNumberCapabilities",
        assignment_type: Union[str, "_models.PhoneNumberAssignmentType"],
        purchase_date: datetime.datetime,
        cost: "_models.PhoneNumberCost",
        **kwargs
    ):
        """
        :keyword id: The id of the phone number, e.g. 11234567890. Required.
        :paramtype id: str
        :keyword phone_number: String of the E.164 format of the phone number, e.g. +11234567890.
         Required.
        :paramtype phone_number: str
        :keyword country_code: The ISO 3166-2 code of the phone number's country, e.g. US. Required.
        :paramtype country_code: str
        :keyword phone_number_type: The phone number's type, e.g. Geographic, TollFree. Required. Known
         values are: "geographic" and "tollFree".
        :paramtype phone_number_type: str or ~azure.communication.phonenumbers.models.PhoneNumberType
        :keyword capabilities: Capabilities of a phone number. Required.
        :paramtype capabilities: ~azure.communication.phonenumbers.models.PhoneNumberCapabilities
        :keyword assignment_type: The assignment type of the phone number. A phone number can be
         assigned to a person, or to an application. Required. Known values are: "person" and
         "application".
        :paramtype assignment_type: str or
         ~azure.communication.phonenumbers.models.PhoneNumberAssignmentType
        :keyword purchase_date: The date and time that the phone number was purchased. Required.
        :paramtype purchase_date: ~datetime.datetime
        :keyword cost: The incurred cost for a single phone number. Required.
        :paramtype cost: ~azure.communication.phonenumbers.models.PhoneNumberCost
        """
        super().__init__(**kwargs)
        self.id = id
        self.phone_number = phone_number
        self.country_code = country_code
        self.phone_number_type = phone_number_type
        self.capabilities = capabilities
        self.assignment_type = assignment_type
        self.purchase_date = purchase_date
        self.cost = cost

class PurchasedPhoneNumbers(_serialization.Model):
    """The list of purchased phone numbers.

    All required parameters must be populated in order to send to Azure.

    :ivar phone_numbers: Represents a list of phone numbers. Required.
    :vartype phone_numbers: list[~azure.communication.phonenumbers.models.PurchasedPhoneNumber]
    :ivar next_link: Represents the URL link to the next page of phone number results.
    :vartype next_link: str
    """

    _validation = {
        "phone_numbers": {"required": True},
    }

    _attribute_map = {
        "phone_numbers": {"key": "phoneNumbers", "type": "[PurchasedPhoneNumber]"},
        "next_link": {"key": "nextLink", "type": "str"},
    }

    def __init__(
        self, *, phone_numbers: List["_models.PurchasedPhoneNumber"], next_link: Optional[str] = None, **kwargs
    ):
        """
        :keyword phone_numbers: Represents a list of phone numbers. Required.
        :paramtype phone_numbers: list[~azure.communication.phonenumbers.models.PurchasedPhoneNumber]
        :keyword next_link: Represents the URL link to the next page of phone number results.
        :paramtype next_link: str
        """
        super().__init__(**kwargs)
        self.phone_numbers = phone_numbers
        self.next_link = next_link


text:
package org.apache.nifi.remote.io.socket.ssl;

import java.io.IOException;
import java.io.OutputStream;

import org.apache.nifi.stream.io.BufferedOutputStream;
import org.apache.nifi.stream.io.ByteCountingOutputStream;
import org.apache.nifi.remote.protocol.CommunicationsOutput;

public class SSLSocketChannelOutput implements CommunicationsOutput {

    private final OutputStream out;
    private final ByteCountingOutputStream countingOut;

    public SSLSocketChannelOutput(final SSLSocketChannel channel) {
        countingOut = new ByteCountingOutputStream(new SSLSocketChannelOutputStream(channel));
        out = new BufferedOutputStream(countingOut);
    }

    @Override
    public OutputStream getOutputStream() throws IOException {
        return out;
    }

    @Override
    public long getBytesWritten() {
        return countingOut.getBytesWritten();
    }
}


text:
package org.apache.syncope.core.flowable.task;

import org.apache.commons.lang3.tuple.Pair;
import org.apache.syncope.common.lib.request.PasswordPatch;
import org.apache.syncope.common.lib.request.UserUR;
import org.apache.syncope.core.flowable.impl.FlowableRuntimeUtils;
import org.apache.syncope.core.persistence.api.dao.UserDAO;
import org.apache.syncope.core.persistence.api.entity.user.User;
import org.apache.syncope.core.provisioning.api.PropagationByResource;
import org.apache.syncope.core.provisioning.api.data.UserDataBinder;
import org.apache.syncope.core.workflow.api.WorkflowException;
import org.flowable.engine.delegate.DelegateExecution;

public class PasswordReset extends FlowableServiceTask {

    protected final UserDataBinder dataBinder;

    protected final UserDAO userDAO;

    public PasswordReset(final UserDataBinder dataBinder, final UserDAO userDAO) {
        this.dataBinder = dataBinder;
        this.userDAO = userDAO;
    }

    @Override
    protected void doExecute(final DelegateExecution execution) {
        User user = execution.getVariable(FlowableRuntimeUtils.USER, User.class);
        String token = execution.getVariable(FlowableRuntimeUtils.TOKEN, String.class);
        String password = execution.getVariable(FlowableRuntimeUtils.PASSWORD, String.class);

        if (!user.checkToken(token)) {
            throw new WorkflowException(new IllegalArgumentException("Wrong token: " + token + " for " + user));
        }

        user.removeToken();

        UserUR req = new UserUR.Builder(user.getKey()).
                password(new PasswordPatch.Builder().
                        onSyncope(true).
                        resources(userDAO.findAllResourceKeys(user.getKey())).
                        value(password).build()).
                build();

        Pair<PropagationByResource<String>, PropagationByResource<Pair<String, String>>> propInfo =
                dataBinder.update(user, req);

        // report updated user and propagation by resource as result
        execution.setVariable(FlowableRuntimeUtils.USER, user);
        execution.setVariable(FlowableRuntimeUtils.USER_UR, req);
        execution.setVariable(FlowableRuntimeUtils.PROP_BY_RESOURCE, propInfo.getLeft());
        execution.setVariable(FlowableRuntimeUtils.PROP_BY_LINKEDACCOUNT, propInfo.getRight());
    }
}


text:
package net.etalia.crepuscolo.queue;

import net.etalia.crepuscolo.domain.BaseEntity;
import net.etalia.jalia.annotations.JsonDefaultFields;

@JsonDefaultFields("name,email,age")
public class DummyBean extends BaseEntity {

	private String name;
	private String email;
	private int age;

	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}

	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}

	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}

}


text:
.. _calculation:

===========
Calculation
===========

There's two general approaches to calculate positions from signal sources,
without the cooperation of the signal sources or mobile networks.

1. Determine the location of signal sources from :term:`observations`,
   then compare / trilaterate user locations.

2. Generate signal fingerprints for a fine-grained grid of the world.
   Find best match for a observed fingerprint.

The second approach has a much better accuracy, but relies on a lot more
available and constantly updated data. For most of the world this
approach is not practical, so we currently focus on approach one.

In theory one would assume that one could use signal strength data to
infer a distance measure from it. The further a device is away from the
signal source, the weaker the signal should get.

Unfortunately the signal strength is more dependent on the device type,
how a user holds a device and changing environmental factors like trucks in
the way. Even worse modern networks adjust their signal strength to the number
of devices inside their reception area. This makes this data practically
useless while looking up a users position via a single reading.

In aggregate over many data points this information can still be valuable
in determining the actual position of the signal source. While observing
multiple signals at once, their relative strengths can also be used, as
this keeps some of the changing factors constant, like the device type.

One other approach is using time of flight data as a distance metric.
While there are some reflection and multipath problems it's a much more
accurate distance predictor. Fine grained enough timing data is
unfortunately almost never available to the application or operating
system layer in client devices. Some LTE networks and really modern
WiFi networks with support for 802.11v are the rare exception to this.
But these are so rare, that we currently ignore timing data.

Accuracy
========

Depending on the signal standard, we can promise different sorts of accuracy.

Underlying this is the assumption that we have enough data about the
area at all. With no or too little data we'll have to fallback to less
accurate data sources. WiFi is the most accurate, followed by cell based
estimation using single cells, multiple cells or cell location areas.
If all else fails GeoIP serves as a general fallback.

WiFi
----

WiFi networks have a fairly limited range, with buildings in the way often
only in the tens or low hundreds of meters. But caching layers in the
operating system and time differences between when a WiFi scan happened
and when this is made available to the calling app can lead to WiFi networks
still being visible up to some kilometers away from their actual position
if the device moves in the meantime.

This means position estimates based on WiFi networks are usually accurate
to low hundreds of meters. If a lot of networks are available in the area
accuracy tends to increase to 100 meter or less.

One challenge that's particular severe in WiFi networks are all the
constantly moving WiFi networks, for example those installed on buses
or trains or in the form of hotspot enabled mobile phones or tablets.
So movement detection and detecting inconsistencies between observed
data and the database world view are important considerations.

GSM
---

For GSM networks we will likely have access to the unique cell id of the
serving cell only. In GSM networks the phone does not know the full cell
ids of any neighboring cells, unless it associates with the new cell as
part of a hand-over, forgetting the cell id of the old cell.

So we are limited to a basic :term:`Cell-ID` approach, meaning we assume
that the user is at the center of the current GSM cell area and use the
cell radius as the accuracy.

GSM cells are restricted to a maximum range of 35km, but there are rare
exceptions using the GSM extended range of 120km.

In more populated places the cell sizes are typically much smaller, but
generally accuracy will be in the tens of kilometer range.

WCDMA / UMTS
------------

In WCDMA networks neighboring cell information can be available. But
limitations in chipset drivers, the radio interface layer and the
operating systems often hide this data from application code. Or
only partially expose the cell identifiers, for example only exposing
the carrier and primary scrambling code of the neighboring cells.

So in most cases we are limited to the same approach as for GSM cells.
The typical cell sizes of UMTS cells are much smaller, which practically
leads to a better accuracy. But WCDMA cells in rural areas can have a
larger radius than GSM cells and we observed cells sizes of 60-70km.

In urban areas we should typically see accuracy in the 1 to 10 kilometer
range.

LTE
---

LTE networks are similar to WCDMA networks and the same restriction on
neighboring cells applies. Instead of a primary scrambling code LTE uses
a physical cell id, which for our purposes has similar characteristics.

LTE cells are again often even smaller than WCDMA cells which leads to
better accuracies.

LTE networks also expose a time based distance metric in the form of
the timing advance. While we currently don't use this information, in
the future it has the potential to significantly improve position
estimates based on multiple cells.

GeoIP
-----

The accuracy of GeoIP depends a lot on the country or region the user
is in. In the US GeoIP can be fairly accurate and often places the
user in the right city or metropolitan area. In many other parts of
the world GeoIP is only accurate to the region level.

Typical GeoIP accuracies are either in the 50km range for city based
estimates or multiple hundred kilometers for region based estimates.

IP version 6 has the chance to improve this situation, as the need for
private carrier networks and network address translation decreases.
But so far this hasn't made any measurable impact and most traffic
is still restricted to IP version 4.


text:
package com.ndtt.domain;

import java.util.ArrayList;
import java.util.List;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.data.mongodb.core.mapping.Document;

import com.ndtt.cascade.CascadeSave;

import lombok.Data;

@Data
@Document(collection = "unit")
public class SingleUnit {
	@Id
	private String id;
	private String name;
	private String address;
	private String type;
	private int level;
	private List<String> owners;
	private Coordinates coordinate;
	@DBRef
	@CascadeSave
	private List<SingleUnit> childUnits;

	@CascadeSave
	@DBRef
	private List<Action> actions;

	public void addChild(SingleUnit unit){
		if (childUnits == null)
			childUnits = new ArrayList<SingleUnit>();
		childUnits.add(unit);
	}

	public void addAction(Action action) {
		if (actions == null) {
			actions = new ArrayList<Action>();
		}

		actions.add(action);
	}

	@Override
	public String toString() {
		return "SingleUnit [id=" + id + ", name=" + name + ", address=" + address + ", type=" + type + ", level="
				+ level + ", owners=" + owners + ", coordinate=" + coordinate + ", childUnits=" + childUnits
				+ ", actions=" + actions + "]";
	}

}


text:
<component name="ArtifactManager">
  <artifact type="exploded-war" name="orientation:war exploded">
    <output-path>$PROJECT_DIR$/out/artifacts/orientation_war_exploded</output-path>
    <root id="root">
      <element id="javaee-facet-resources" facet="orientation/web/Web" />
      <element id="directory" name="WEB-INF">
        <element id="directory" name="classes">
          <element id="module-output" name="orientation" />
        </element>
        <element id="directory" name="lib">
          <element id="library" level="project" name="Struts 2-2.3.20.1" />
          <element id="library" level="project" name="Hibernate 5.2.3-5.2.3" />
          <element id="library" level="project" name="mysql:mysql-connector-mxj:5.0.12" />
          <element id="library" level="project" name="org.apache.tomcat:tomcat-servlet-api:7.0.22" />
          <element id="library" level="project" name="com.google.code.gson:gson:2.8.0" />
          <element id="library" level="project" name="mail" />
        </element>
      </element>
    </root>
  </artifact>
</component>


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:card_view="http://schemas.android.com/apk/res-auto"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="wrap_content">

  <android.support.v7.widget.CardView
    android:id="@+id/card_view"
    android:layout_gravity="center"
    android:layout_width="fill_parent"
    android:layout_height="230dp"
    android:layout_margin="5dp"
    card_view:cardCornerRadius="2dp"
    card_view:contentPadding="10dp">

    <RelativeLayout
      android:layout_width="fill_parent"
      android:layout_height="fill_parent">

      <TextView
        android:id="@+id/company_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textStyle="bold"
        android:layout_alignParentTop="true"/>

      <TextView
        android:id="@+id/company_country"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_below="@+id/company_name"/>

      <TextView
        android:id="@+id/company_street"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_below="@+id/company_country"/>

      <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="TEL."
        android:id="@+id/tv_phone"
        android:layout_below="@+id/company_street"/>

      <TextView
        android:id="@+id/company_phone"
        android:clickable="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_below="@+id/tv_phone"/>

      <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="CELL."
        android:id="@+id/tv_cell"
        android:layout_below="@+id/company_phone"/>

      <TextView
        android:id="@+id/company_cell"
        android:clickable="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_below="@+id/tv_cell"/>
    </RelativeLayout>
  </android.support.v7.widget.CardView>

</LinearLayout>


text:
import java.util.Arrays;
import java.util.Random;

public class Fisher_Yates {

	/*Fisher-Yates Algorithm

	 Problem (informal): Given input array, return permuted array such that elements are uniformly distributed (pseudorandomly)

	 Algorithm: For each index i, swap element at i with element at random index 0 <= j <= i

	 Complexity:
	 	* Time - O(n) since only one iteration
	 	* Space - O(n) to choose random integer at each position

	 Notes:
	 	* shuffle() - randomly permutes input array
	 	* swap() - swaps elements at indices i and j

	 Notes:
	 	* Simple but effective shuffling algorithm

	 */

	public static void main(String[] args) {
		Integer[] arr = {1, 4, 3, 2, 64, 3, 2, 4, 5, 5, 2, 12, 14, 5, 3, 0, -1};
		arr = shuffle(arr);
		System.out.println(Arrays.toString(arr));

	}

	public static <E extends Comparable<E>> E[] shuffle(E[] arr){
		Random rng = new Random();
		for(int i = arr.length - 1 ; i > 0 ; i--){
			int j = rng.nextInt(i+1); //random element in range [0, i]
			swap(arr, i, j);
		}
		return arr;
	}

	public static <E> void swap(E[] arr, int i, int j){
		E temp = arr[i];
		arr[i] = arr[j];
		arr[j] = temp;
	}

}


text:
package org.apache.nifi.web.dao.impl;

import org.apache.commons.lang3.StringUtils;
import org.apache.nifi.bundle.BundleCoordinate;
import org.apache.nifi.components.ConfigurableComponent;
import org.apache.nifi.components.PropertyDescriptor;
import org.apache.nifi.controller.FlowController;
import org.apache.nifi.controller.StandardFlowSnippet;
import org.apache.nifi.controller.Template;
import org.apache.nifi.controller.TemplateUtils;
import org.apache.nifi.controller.exception.ProcessorInstantiationException;
import org.apache.nifi.controller.serialization.FlowEncodingVersion;
import org.apache.nifi.groups.ProcessGroup;
import org.apache.nifi.parameter.Parameter;
import org.apache.nifi.parameter.ParameterContext;
import org.apache.nifi.parameter.ParameterParser;
import org.apache.nifi.parameter.ParameterReference;
import org.apache.nifi.parameter.ParameterTokenList;
import org.apache.nifi.parameter.ExpressionLanguageAwareParameterParser;
import org.apache.nifi.web.NiFiCoreException;
import org.apache.nifi.web.ResourceNotFoundException;
import org.apache.nifi.web.api.dto.BundleDTO;
import org.apache.nifi.web.api.dto.ControllerServiceDTO;
import org.apache.nifi.web.api.dto.FlowSnippetDTO;
import org.apache.nifi.web.api.dto.ProcessGroupDTO;
import org.apache.nifi.web.api.dto.ProcessorConfigDTO;
import org.apache.nifi.web.api.dto.ProcessorDTO;
import org.apache.nifi.web.api.dto.TemplateDTO;
import org.apache.nifi.web.dao.TemplateDAO;
import org.apache.nifi.web.util.SnippetUtils;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;

/**
 *
 */
public class StandardTemplateDAO extends ComponentDAO implements TemplateDAO {

    private FlowController flowController;
    private SnippetUtils snippetUtils;

    private Template locateTemplate(String templateId) {
        // get the template
        Template template = flowController.getFlowManager().getRootGroup().findTemplate(templateId);

        // ensure the template exists
        if (template == null) {
            throw new ResourceNotFoundException(String.format("Unable to locate template with id '%s'.", templateId));
        }

        return template;
    }

    @Override
    public void verifyCanAddTemplate(String name, String groupId) {
        final ProcessGroup processGroup = flowController.getFlowManager().getGroup(groupId);
        if (processGroup == null) {
            throw new ResourceNotFoundException("Could not find Process Group with ID " + groupId);
        }

        processGroup.verifyCanAddTemplate(name);
    }

    @Override
    public void verifyCanInstantiate(final String groupId, final FlowSnippetDTO snippetDTO) {
        final ProcessGroup processGroup = flowController.getFlowManager().getGroup(groupId);
        if (processGroup == null) {
            throw new ResourceNotFoundException("Could not find Process Group with ID " + groupId);
        }

        verifyComponentTypes(snippetDTO);
        verifyParameterReferences(snippetDTO, processGroup.getParameterContext());
    }

    /**
     * Verifies that the Processors and Controller Services within the template do not make any illegal references to Parameters. I.e., if a Parameter is referenced from a non-sensitive property,
     * the Parameter itself must not be sensitive. Likewise, if a Parameter is referenced from a sensitive property, the Parameter itself must be sensitive.
     *
     * @param snippet the contents of the snippet
     * @param parameterContext the Parameter Context
     */
    private void verifyParameterReferences(final FlowSnippetDTO snippet, final ParameterContext parameterContext) {
        if (parameterContext == null) {
            return; // no parameters are referenced because there is no parameter context.
        }

        final ParameterParser parameterParser = new ExpressionLanguageAwareParameterParser();

        for (final ProcessorDTO processor : snippet.getProcessors()) {
            final BundleDTO bundleDto = processor.getBundle();
            final BundleCoordinate bundleCoordinate = new BundleCoordinate(bundleDto.getGroup(), bundleDto.getArtifact(), bundleDto.getVersion());
            final ConfigurableComponent component = flowController.getExtensionManager().getTempComponent(processor.getType(), bundleCoordinate);

            final ProcessorConfigDTO config = processor.getConfig();
            for (final Map.Entry<String, String> entry : config.getProperties().entrySet()) {
                final String propertyName = entry.getKey();
                final ParameterTokenList references = parameterParser.parseTokens(entry.getValue());

                final PropertyDescriptor descriptor = component.getPropertyDescriptor(propertyName);
                verifyParameterReference(descriptor, references, parameterContext);
            }
        }

        for (final ControllerServiceDTO service : snippet.getControllerServices()) {
            final BundleDTO bundleDto = service.getBundle();
            final BundleCoordinate bundleCoordinate = new BundleCoordinate(bundleDto.getGroup(), bundleDto.getArtifact(), bundleDto.getVersion());
            final ConfigurableComponent component = flowController.getExtensionManager().getTempComponent(service.getType(), bundleCoordinate);

            for (final Map.Entry<String, String> entry : service.getProperties().entrySet()) {
                final String propertyName = entry.getKey();
                final ParameterTokenList references = parameterParser.parseTokens(entry.getValue());

                final PropertyDescriptor descriptor = component.getPropertyDescriptor(propertyName);
                verifyParameterReference(descriptor, references, parameterContext);
            }
        }
    }

    private void verifyParameterReference(final PropertyDescriptor descriptor, final ParameterTokenList parameterTokenList, final ParameterContext parameterContext) {
        if (descriptor == null || parameterTokenList == null) {
            return;
        }

        final List<ParameterReference> references = parameterTokenList.toReferenceList();
        for (final ParameterReference reference : references) {
            final String parameterName = reference.getParameterName();
            final Optional<Parameter> parameter = parameterContext.getParameter(parameterName);
            if (!parameter.isPresent()) {
                continue;
            }

            final boolean parameterSensitive = parameter.get().getDescriptor().isSensitive();
            if (descriptor.isSensitive() && !parameterSensitive) {
                throw new IllegalStateException("Cannot instantiate template within this Process Group because template references the '" + parameterName
                    + "' Parameter in a sensitive property, but the Parameter is not sensitive");
            }
            if (!descriptor.isSensitive() && parameterSensitive) {
                throw new IllegalStateException("Cannot instantiate template within this Process Group because template references the '" + parameterName
                    + "' Parameter in a non-sensitive property, but the Parameter is sensitive");
            }
        }
    }

    private void verifyComponentTypes(FlowSnippetDTO snippetDto) {
        final StandardFlowSnippet flowSnippet = new StandardFlowSnippet(snippetDto, flowController.getExtensionManager());
        flowSnippet.verifyComponentTypesInSnippet();
    }

    @Override
    public Template importTemplate(TemplateDTO templateDTO, String groupId) {
        return createTemplate(templateDTO, groupId);
    }

    @Override
    public Template createTemplate(final TemplateDTO templateDTO, final String groupId) {
        final ProcessGroup processGroup = flowController.getFlowManager().getGroup(groupId);
        if (processGroup == null) {
            throw new ResourceNotFoundException("Could not find Process Group with ID " + groupId);
        }

        verifyCanAddTemplate(templateDTO.getName(), groupId);

        TemplateUtils.scrubTemplate(templateDTO);
        TemplateUtils.escapeParameterReferences(templateDTO);

        final Template template = new Template(templateDTO);
        processGroup.addTemplate(template);

        return template;
    }

    @Override
    public FlowSnippetDTO instantiateTemplate(String groupId, Double originX, Double originY, String encodingVersion,
                                              FlowSnippetDTO requestSnippet, String idGenerationSeed) {

        ProcessGroup group = locateProcessGroup(flowController, groupId);

        try {
            // copy the template which pre-processes all ids
            FlowSnippetDTO snippet = snippetUtils.copy(requestSnippet, group, idGenerationSeed, false);

            // calculate scaling factors based on the template encoding version attempt to parse the encoding version.
            // get the major version, or 0 if no version could be parsed
            final FlowEncodingVersion templateEncodingVersion = FlowEncodingVersion.parse(encodingVersion);
            int templateEncodingMajorVersion = templateEncodingVersion != null ? templateEncodingVersion.getMajorVersion() : 0;

            // based on the major version < 1, use the default scaling factors.  Otherwise, don't scale (use factor of 1.0)
            double factorX = templateEncodingMajorVersion < 1 ? FlowController.DEFAULT_POSITION_SCALE_FACTOR_X : 1.0;
            double factorY = templateEncodingMajorVersion < 1 ? FlowController.DEFAULT_POSITION_SCALE_FACTOR_Y : 1.0;

            // reposition and scale the template contents
            org.apache.nifi.util.SnippetUtils.moveAndScaleSnippet(snippet, originX, originY, factorX, factorY);

            // find all the child process groups in each process group in the top level of this snippet
            final List<ProcessGroupDTO> childProcessGroups  = org.apache.nifi.util.SnippetUtils.findAllProcessGroups(snippet);
            // scale (but don't reposition) child process groups
            childProcessGroups.forEach(processGroup -> org.apache.nifi.util.SnippetUtils.scaleSnippet(processGroup.getContents(), factorX, factorY));

            // instantiate the template into this group
            flowController.getFlowManager().instantiateSnippet(group, snippet);

            return snippet;
        } catch (ProcessorInstantiationException pie) {
            throw new NiFiCoreException(String.format("Unable to instantiate template because processor type '%s' is unknown to this NiFi.",
                    StringUtils.substringAfterLast(pie.getMessage(), ".")));
        }
    }

    @Override
    public void deleteTemplate(String templateId) {
        // ensure the template exists
        final Template template = locateTemplate(templateId);

        // remove the specified template
        template.getProcessGroup().removeTemplate(template);
    }

    @Override
    public Template getTemplate(String templateId) {
        return locateTemplate(templateId);
    }

    @Override
    public Set<Template> getTemplates() {
        final Set<Template> templates = new HashSet<>();
        templates.addAll(flowController.getFlowManager().getRootGroup().findAllTemplates());
        return templates;
    }

    /*
     * setters
     */
    public void setFlowController(FlowController flowController) {
        this.flowController = flowController;
    }

    public void setSnippetUtils(SnippetUtils snippetUtils) {
        this.snippetUtils = snippetUtils;
    }

}


text:
package be.kdg.agenda.controller;

import be.kdg.model.agendamodel.afspraken.Afspraak;
import be.kdg.model.agendamodel.afspraken.AfspraakManager;
import be.kdg.model.agendamodel.afspraken.Datum;
import be.kdg.model.agendamodel.users.UserManager;
import java.util.List;

public class CalendarController
{
    private UserManager userManager;
    private AfspraakManager afspraakManager;

    public CalendarController()
    {
        this.userManager = new UserManager();
        this.afspraakManager = new AfspraakManager();
    }

    public boolean checkUsernamePassword(String username, String password)
    {
        return userManager.checkUsernamePassword(username, password);
    }

    public void addAfspraak(Afspraak afspraak)
    {
        afspraakManager.addAfspraak(afspraak);
    }

    public List<Afspraak> zoekAfspraak(Datum date, String username)
    {
        return afspraakManager.zoekAfspraak(date, username);
    }

    public void removeAfspraak(Afspraak afspraak)
    {
        afspraakManager.removeAfspraak(afspraak);
    }
}


text:
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#pragma once

#include <vespa/searchlib/fef/properties.h>
#include <vespa/searchlib/common/mapnames.h>

namespace search::engine {

/**
 * A simple wrapper class used to hold multiple named collections of
 * properties.
 **/
class PropertiesMap
{
private:
    using Props = search::fef::Properties;
    using PropsMap = vespalib::hash_map<vespalib::string, Props>;

    static Props _emptyProperties;
    PropsMap     _propertiesMap;

    /**
     * Obtain a named collection of properties. This method will
     * return an empty collection of properties if the properties did
     * not exist.
     *
     * @param name name of properties
     * @return the properties
     **/
    const Props &lookup(vespalib::stringref name) const;

public:
    typedef PropsMap::const_iterator ITR;

    PropertiesMap();
    PropertiesMap(uint32_t sz);
    PropertiesMap(const PropertiesMap &) = delete;
    PropertiesMap & operator=(const PropertiesMap &) = delete;
    ~PropertiesMap();

    /**
     * Obtain a named collection of properties. This method will
     * create the properties if they did not exist yet.
     *
     * @param name name of properties
     * @return the properties
     **/
    Props &lookupCreate(vespalib::stringref name);

    /**
     * Obtain the number of named collection of properties held by
     * this object.
     *
     * @return number of named collections of properties
     **/
    uint32_t size() const { return _propertiesMap.size(); }

    /**
     * Iterate the map.
     *
     * @return begin iterator
     **/
    ITR begin() const { return _propertiesMap.begin(); }

    /**
     * Iterate the map.
     *
     * @return end iterator
     **/
    ITR end() const { return _propertiesMap.end(); }

    /**
     * Obtain rank properties (used to tune ranking evaluation)
     *
     * @return rank properties
     **/
    const Props &rankProperties() const {
        return lookup(MapNames::RANK);
    }

    /**
     * Obtain feature overrides (used to hardwire the values of
     * features during ranking evaluation)
     *
     * @return feature overrides
     **/
    const Props &featureOverrides() const {
        return lookup(MapNames::FEATURE);
    }

    /**
     * Obtain properties used to define additional highlight terms to
     * be used during dynamic summary generation.
     *
     * @return highlight terms properties
     **/
    const Props &highlightTerms() const {
        return lookup(MapNames::HIGHLIGHTTERMS);
    }

    /**
     * Obtain match properties (used to tune match evaluation)
     *
     * @return match properties
     **/
    const Props &matchProperties() const {
        return lookup(MapNames::MATCH);
    }

    /**
     * Obtain cache properties (used to tune cache usage)
     *
     * @return cache properties
     **/
    const Props &cacheProperties() const {
        return lookup(MapNames::CACHES);
    }

    /**
     * Obtain model overrides
     *
     * @return model properties
     **/
    const Props &modelOverrides() const {
        return lookup(MapNames::MODEL);
    }

    /**
     * Obtain trace
     *
     * @return trace
     **/
    const Props &trace() const {
        return lookup(MapNames::TRACE);
    }
};

}


text:
package de.oliver_heger.linedj.platform.audio.model

/**
  * An ''Ordering'' implementation for [[SongData]] which orders songs based on
  * the albums they belong to.
  *
  * This ordering can be used for instance to bring all the songs of an artist
  * into a logic order. It applies the following criteria:
  *
  * First the inception year of the album is evaluated. Older albums are
  * sorted before newer ones. Albums for which the inception year is unknown
  * are sorted after albums with a defined inception year.
  *
  * Albums with the same inception year are sorted by their names in alphabetic
  * order (ignoring case).
  *
  * The songs belonging to an album are sorted by using
  * [[SongTrackNoOrdering]].
  */
object SongAlbumOrdering extends Ordering[SongData] {
  override def compare(x: SongData, y: SongData): Int = {
    val c = extractInceptionYear(x) - extractInceptionYear(y)
    if (c != 0) c
    else {
      val c1 = x.album compareToIgnoreCase y.album
      if (c1 != 0) c1
      else SongTrackNoOrdering.compare(x, y)
    }
  }

  /**
    * Obtains the inception year from the given song data. Ensures that songs
    * without a year are sorted after others.
    *
    * @param s the ''SongData''
    * @return the inception year of this song
    */
  private def extractInceptionYear(s: SongData): Int =
    s.metaData.inceptionYear getOrElse Integer.MAX_VALUE
}


text:
$(document).ready(function(){

	$('.social-icon').each(function(i){
		setTimeout(function(){
			$('.social-icon').eq(i).addClass('is-visible');
		}, 200 * i);

	})
})


text:
class AddClientTimestampToPayments < ActiveRecord::Migration
  def change
    add_column :payments, :client_timestamp, :integer, :limit => 8
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<metadata>
  <groupId>rubygems</groupId>
  <artifactId>jar-dependencies</artifactId>
  <versioning>
    <release>0.1.15</release>
    <versions>
      <version>0.1.15</version>
    </versions>
    <lastUpdated>20150622160200</lastUpdated>
  </versioning>
</metadata>


text:
//
//  WBViewController.m
//  HttpDemo
//
//  Created by 韩学鹏 on 15/6/29.
//  Copyright (c) 2015年 韩学鹏. All rights reserved.
//

#import "WBViewController.h"
#import "MBProgressHUD+Extensions.h"

@interface WBViewController () <NSURLConnectionDataDelegate>
@end

@implementation WBViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];

    // Do any additional setup after loading the view.
    //显示需要手动隐藏的信息框
    UIButton *sendBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [sendBtn setTitle:@"显示需要手动隐藏的信息框" forState:UIControlStateNormal];
    sendBtn.frame = CGRectMake(80, 90, 180, 25);
    [sendBtn addTarget:self action:@selector(btnFunc0) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:sendBtn];

    //显示自动隐藏的信息框
    UIButton *sendBtn1 = [UIButton buttonWithType:UIButtonTypeSystem];
    [sendBtn1 setTitle:@"显示自动隐藏的信息框" forState:UIControlStateNormal];
    sendBtn1.frame = CGRectMake(100, 150, 150, 25);
    [sendBtn1 addTarget:self action:@selector(btnFunc1) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:sendBtn1];

    //显示带自定义图片的信息框
    UIButton *sendBtn2 = [UIButton buttonWithType:UIButtonTypeSystem];
    [sendBtn2 setTitle:@"显示带自定义图片的信息框" forState:UIControlStateNormal];
    sendBtn2.frame = CGRectMake(80, 210, 180, 25);
    [sendBtn2 addTarget:self action:@selector(btnFunc2) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:sendBtn2];
}

/**
 *  显示需要手动隐藏的信息框
 */
- (void)btnFunc0 {
    //显示一个加载框
    MBProgressHUD *hud = [MBProgressHUD showMessage:@"提示信息" animated:YES];
    hud.dimBackground = YES;   //显示暗色背景

    //发送HTTP请求
    NSString *str = @"http://www.weather.com.cn/adat/sk/101010100.html";
    NSURL *url = [NSURL URLWithString:str];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

        UIView *view = [UIApplication sharedApplication].windows.lastObject;
        [MBProgressHUD hideHUDForView:view animated:YES];
    }];

}

/**
 *  显示自动隐藏的信息框
 */
- (void)btnFunc1 {
    [MBProgressHUD showMessage:@"提示信息" animated:YES afterDelay:2];

}

/**
 *  显示带自定义图片的信息框
 */
- (void)btnFunc2 {
    [MBProgressHUD showMessage:@"提示信息" icon:@"error" animated:YES afterDelay:2];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end