text:
package com.nghianh.giaitriviet.util;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.DownloadManager;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.ShareActionProvider;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.webkit.URLUtil;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.Toast;
import android.widget.VideoView;

import com.nghianh.giaitriviet.Config;
import com.nghianh.giaitriviet.R;
import com.squareup.picasso.Picasso;

public class MediaActivity extends AppCompatActivity {

    public static boolean HIDE_TOOLBAR_OLD_DEVICES = true;

    public static String DOWNLOAD_ON_OPEN = "download_on_open";
    public static String TYPE = "type";
    public static String URL = "url";
    public static int TYPE_VID = 1;
    public static int TYPE_IMG = 2;
    public static int TYPE_AUDIO = 3;

    private boolean systemUIVisible;

    int type;
    String url;
    String downloadqueue;
    Toolbar mToolbar;
    ProgressDialog pDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        View mDecorView = getWindow().getDecorView();
        mDecorView.setOnSystemUiVisibilityChangeListener(mOnSystemUiVisibilityChangeListener);

        setContentView(R.layout.activity_media);
        mToolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        hideSystemUI();

        final ImageView imageView = (ImageView) findViewById(R.id.imageView);
        final VideoView videoView = (VideoView) findViewById(R.id.videoView);

        Bundle extras = getIntent().getExtras();
        url = extras.getString(URL);
        type = extras.getInt(TYPE);

        if (extras.containsKey(DOWNLOAD_ON_OPEN) && extras.getBoolean(DOWNLOAD_ON_OPEN)) {
            file_download(url, MediaActivity.this);
            Toast.makeText(this, getResources().getString(R.string.downloading), Toast.LENGTH_LONG);
        }

        if (Config.PLAY_EXTERNAL) {
            //Try opening it in another player and quitting the media activity
            openExternal(url);
            this.finish();
        }

        if (type == TYPE_VID || type == TYPE_AUDIO) {
            videoView.setVisibility(View.VISIBLE);

            pDialog = new ProgressDialog(this);
            if (type == TYPE_VID)
                pDialog.setTitle(getResources().getString(R.string.opening_video));
            else
                pDialog.setTitle(getResources().getString(R.string.opening_audio));
            pDialog.setMessage(getResources().getString(R.string.loading));
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();

            try {
                MediaController mediacontroller = new MediaController(this);
                mediacontroller.setAnchorView(videoView);
                Uri video = Uri.parse(url);
                videoView.setMediaController(mediacontroller);
                videoView.setVideoURI(video);
            } catch (Exception e) {
                Log.printStackTrace(e);
            }

            videoView.requestFocus();
            videoView.setOnPreparedListener(new OnPreparedListener() {
                public void onPrepared(MediaPlayer mp) {
                    pDialog.dismiss();
                    videoView.start();
                }
            });

            videoView.setOnErrorListener(new OnErrorListener() {

                @Override
                public boolean onError(MediaPlayer mp, int what, int extra) {
                    //'Handle' the error
                    Log.e("INFO", "Can't play media. Code: " + what + " Extra: " + extra + ". Proceeding to open in another player.");
                    pDialog.dismiss();

                    //Try opening it in another player
                    openExternal(url);

                    return true;
                }

            });

        } else if (type == TYPE_IMG) {
            imageView.setVisibility(View.VISIBLE);

            imageView.setImageDrawable(null);
            Picasso.with(this).load(url).into(imageView);

            imageView.setOnClickListener(new View.OnClickListener() {
                public void onClick(View arg0) {
                    if (systemUIVisible)
                        hideSystemUI();
                    else
                        showSystemUI();
                }
            });
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_media, menu);
        MenuItem item = menu.findItem(R.id.miShare);
        ShareActionProvider shareAction = (ShareActionProvider) MenuItemCompat.getActionProvider(item);

        if (url != null) {
            Intent shareIntent = new Intent();
            shareIntent.setAction(Intent.ACTION_SEND);
            shareIntent.putExtra(Intent.EXTRA_TEXT, url);

            shareIntent.setType("text/plain");

            shareAction.setShareIntent(shareIntent);
        }

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
            case R.id.download:
                file_download(url, MediaActivity.this);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    //Open the file with an intent instead of viewing it.
    public void openExternal(String url) {
        String extension = MimeTypeMap.getFileExtensionFromUrl(url);
        String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
        Intent mediaIntent = new Intent(Intent.ACTION_VIEW);
        mediaIntent.setDataAndType(Uri.parse(url), mimeType);
        startActivity(mediaIntent);
        finish();
    }

    //Download the shown media file
    public void file_download(String url, Context context) {

        String packageName = "com.android.providers.downloads";
        int state = this.getPackageManager().getApplicationEnabledSetting(packageName);

        //check if the download manager is disabled
        if (state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED ||
                state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER
                || state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {

            //If it is disabled, allow the user to enable it.
            Toast.makeText(this, R.string.downloadmanager_disabled, Toast.LENGTH_LONG).show();

            try {
                //Open the specific App Info page:
                Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                intent.setData(Uri.parse("package:" + packageName));
                startActivity(intent);

            } catch (ActivityNotFoundException e) {
                //e.printStackTrace();

                //Open the generic Apps page:
                Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_APPLICATIONS_SETTINGS);
                startActivity(intent);

            }

        } else {
            //If the download manager is enabled, check for permissions

            //check if there are sufficient permissions to download a file
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M && (
                    checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ||
                            checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {

                requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);

                downloadqueue = url;

            } else {
                url = url.replace(" ", "%20");
                DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
                DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
                String name = URLUtil.guessFileName(url, null, MimeTypeMap.getFileExtensionFromUrl(url));
                String title = "File";
                if (type == TYPE_IMG) {
                    title = getResources().getString(R.string.file_image);
                }
                if (type == TYPE_VID) {
                    title = getResources().getString(R.string.file_video);
                }
                if (type == TYPE_AUDIO) {
                    title = getResources().getString(R.string.file_audio);
                }

                request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE)
                        .setAllowedOverRoaming(false)
                        .setDescription(getResources().getString(R.string.downloading))
                        .setTitle(title)
                        .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
                        .setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, name);
                downloadManager.enqueue(request);
            }
        }

    }

    private View.OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener = new View.OnSystemUiVisibilityChangeListener() {
        @Override
        public void onSystemUiVisibilityChange(int visibility) {
            if ((visibility & View.SYSTEM_UI_FLAG_FULLSCREEN) == View.VISIBLE) {
                showSystemUI();
            } else {
                hideSystemUI();
            }
        }
    };

    @SuppressLint("NewApi")
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case 1:
                boolean foundfalse = false;
                for (int i = 0; i < grantResults.length; i++) {
                    if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                        foundfalse = true;
                    }
                }
                if (!foundfalse) {
                    file_download(downloadqueue, this);
                } else {
                    // Permission Denied
                    Toast.makeText(MediaActivity.this, getResources().getString(R.string.permissions_required), Toast.LENGTH_SHORT)
                            .show();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    @SuppressLint("InlinedApi")
    private void showSystemUI() {
        getSupportActionBar().show();
        if (android.os.Build.VERSION.SDK_INT >= 19)
            getWindow().getDecorView().setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        systemUIVisible = true;
    }

    @SuppressLint("InlinedApi")
    private void hideSystemUI() {

        if (getSupportActionBar() != null) {
            if (!(HIDE_TOOLBAR_OLD_DEVICES && android.os.Build.VERSION.SDK_INT <= 19)) {
                getSupportActionBar().hide();
            }
        }

        if (android.os.Build.VERSION.SDK_INT >= 19) {
            getWindow().getDecorView().setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE |
                            View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION |
                            View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN |
                            View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
                            View.SYSTEM_UI_FLAG_FULLSCREEN |
                            View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
        }

        systemUIVisible = false;
    }

}


text:
/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  *
© Copyright (c) 2020 STMicroelectronics.
  * All rights reserved.

  *
  * This software component is licensed by ST under BSD 3-Clause license,
  * the "License"; You may not use this file except in compliance with the
  * License. You may obtain a copy of the License at:
  *                        opensource.org/licenses/BSD-3-Clause
  *
  ******************************************************************************
  */
/* USER CODE END Header */

/* Includes ------------------------------------------------------------------*/
#include "main.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */

/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/
UART_HandleTypeDef huart4;
UART_HandleTypeDef huart1;
UART_HandleTypeDef huart2;
UART_HandleTypeDef huart3;

/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_UART4_Init(void);
static void MX_USART1_UART_Init(void);
static void MX_USART2_UART_Init(void);
static void MX_USART3_UART_Init(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{
  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_UART4_Init();
  MX_USART1_UART_Init();
  MX_USART2_UART_Init();
  MX_USART3_UART_Init();
  /* USER CODE BEGIN 2 */

  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Initializes the CPU, AHB and APB busses clocks
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI_DIV2;
  RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL16;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }
  /** Initializes the CPU, AHB and APB busses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
  {
    Error_Handler();
  }
}

/**
  * @brief UART4 Initialization Function
  * @param None
  * @retval None
  */
static void MX_UART4_Init(void)
{

  /* USER CODE BEGIN UART4_Init 0 */

  /* USER CODE END UART4_Init 0 */

  /* USER CODE BEGIN UART4_Init 1 */

  /* USER CODE END UART4_Init 1 */
  huart4.Instance = UART4;
  huart4.Init.BaudRate = 115200;
  huart4.Init.WordLength = UART_WORDLENGTH_8B;
  huart4.Init.StopBits = UART_STOPBITS_1;
  huart4.Init.Parity = UART_PARITY_NONE;
  huart4.Init.Mode = UART_MODE_TX_RX;
  huart4.Init.HwFlowCtl = UART_HWCONTROL_NONE;
  huart4.Init.OverSampling = UART_OVERSAMPLING_16;
  if (HAL_UART_Init(&huart4) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN UART4_Init 2 */

  /* USER CODE END UART4_Init 2 */

}

/**
  * @brief USART1 Initialization Function
  * @param None
  * @retval None
  */
static void MX_USART1_UART_Init(void)
{

  /* USER CODE BEGIN USART1_Init 0 */

  /* USER CODE END USART1_Init 0 */

  /* USER CODE BEGIN USART1_Init 1 */

  /* USER CODE END USART1_Init 1 */
  huart1.Instance = USART1;
  huart1.Init.BaudRate = 115200;
  huart1.Init.WordLength = UART_WORDLENGTH_8B;
  huart1.Init.StopBits = UART_STOPBITS_1;
  huart1.Init.Parity = UART_PARITY_NONE;
  huart1.Init.Mode = UART_MODE_TX_RX;
  huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;
  huart1.Init.OverSampling = UART_OVERSAMPLING_16;
  if (HAL_UART_Init(&huart1) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN USART1_Init 2 */

  /* USER CODE END USART1_Init 2 */

}

/**
  * @brief USART2 Initialization Function
  * @param None
  * @retval None
  */
static void MX_USART2_UART_Init(void)
{

  /* USER CODE BEGIN USART2_Init 0 */

  /* USER CODE END USART2_Init 0 */

  /* USER CODE BEGIN USART2_Init 1 */

  /* USER CODE END USART2_Init 1 */
  huart2.Instance = USART2;
  huart2.Init.BaudRate = 115200;
  huart2.Init.WordLength = UART_WORDLENGTH_8B;
  huart2.Init.StopBits = UART_STOPBITS_1;
  huart2.Init.Parity = UART_PARITY_NONE;
  huart2.Init.Mode = UART_MODE_TX_RX;
  huart2.Init.HwFlowCtl = UART_HWCONTROL_NONE;
  huart2.Init.OverSampling = UART_OVERSAMPLING_16;
  if (HAL_UART_Init(&huart2) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN USART2_Init 2 */

  /* USER CODE END USART2_Init 2 */

}

/**
  * @brief USART3 Initialization Function
  * @param None
  * @retval None
  */
static void MX_USART3_UART_Init(void)
{

  /* USER CODE BEGIN USART3_Init 0 */

  /* USER CODE END USART3_Init 0 */

  /* USER CODE BEGIN USART3_Init 1 */

  /* USER CODE END USART3_Init 1 */
  huart3.Instance = USART3;
  huart3.Init.BaudRate = 115200;
  huart3.Init.WordLength = UART_WORDLENGTH_8B;
  huart3.Init.StopBits = UART_STOPBITS_1;
  huart3.Init.Parity = UART_PARITY_NONE;
  huart3.Init.Mode = UART_MODE_TX_RX;
  huart3.Init.HwFlowCtl = UART_HWCONTROL_NONE;
  huart3.Init.OverSampling = UART_OVERSAMPLING_16;
  if (HAL_UART_Init(&huart3) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN USART3_Init 2 */

  /* USER CODE END USART3_Init 2 */

}

/**
  * @brief GPIO Initialization Function
  * @param None
  * @retval None
  */
static void MX_GPIO_Init(void)
{

  /* GPIO Ports Clock Enable */
  __HAL_RCC_GPIOD_CLK_ENABLE();
  __HAL_RCC_GPIOA_CLK_ENABLE();
  __HAL_RCC_GPIOB_CLK_ENABLE();
  __HAL_RCC_GPIOC_CLK_ENABLE();

}

/* USER CODE BEGIN 4 */

/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */

  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     tex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/

redpajama_set_name: RedPajamaGithub


text:
CK_VISIBLE_PUBLIC HCkMime CkMime_Create(void);
CK_VISIBLE_PUBLIC void CkMime_Dispose(HCkMime handle);
CK_VISIBLE_PUBLIC void CkMime_getBoundary(HCkMime cHandle, HCkString retval);
CK_VISIBLE_PUBLIC void CkMime_putBoundary(HCkMime cHandle, const char *newVal);
CK_VISIBLE_PUBLIC const char *CkMime_boundary(HCkMime cHandle);
CK_VISIBLE_PUBLIC void CkMime_getCharset(HCkMime cHandle, HCkString retval);
CK_VISIBLE_PUBLIC void CkMime_putCharset(HCkMime cHandle, const char *newVal);
CK_VISIBLE_PUBLIC const char *CkMime_charset(HCkMime cHandle);
CK_VISIBLE_PUBLIC void CkMime_getContentType(HCkMime cHandle, HCkString retval);
CK_VISIBLE_PUBLIC void CkMime_putContentType(HCkMime cHandle, const char *newVal);
CK_VISIBLE_PUBLIC const char *CkMime_contentType(HCkMime cHandle);
CK_VISIBLE_PUBLIC void CkMime_getCurrentDateTime(HCkMime cHandle, HCkString retval);
CK_VISIBLE_PUBLIC const char *CkMime_currentDateTime(HCkMime cHandle);
CK_VISIBLE_PUBLIC void CkMime_getDebugLogFilePath(HCkMime cHandle, HCkString retval);
CK_VISIBLE_PUBLIC void CkMime_putDebugLogFilePath(HCkMime cHandle, const char *newVal);
CK_VISIBLE_PUBLIC const char *CkMime_debugLogFilePath(HCkMime cHandle);
CK_VISIBLE_PUBLIC void CkMime_getDisposition(HCkMime cHandle, HCkString retval);
CK_VISIBLE_PUBLIC void CkMime_putDisposition(HCkMime cHandle, const char *newVal);
CK_VISIBLE_PUBLIC const char *CkMime_disposition(HCkMime cHandle);
CK_VISIBLE_PUBLIC void CkMime_getEncoding(HCkMime cHandle, HCkString retval);
CK_VISIBLE_PUBLIC void CkMime_putEncoding(HCkMime cHandle, const char *newVal);
CK_VISIBLE_PUBLIC const char *CkMime_encoding(HCkMime cHandle);
CK_VISIBLE_PUBLIC void CkMime_getFilename(HCkMime cHandle, HCkString retval);
CK_VISIBLE_PUBLIC void CkMime_putFilename(HCkMime cHandle, const char *newVal);
CK_VISIBLE_PUBLIC const char *CkMime_filename(HCkMime cHandle);
CK_VISIBLE_PUBLIC void CkMime_getLastErrorHtml(HCkMime cHandle, HCkString retval);
CK_VISIBLE_PUBLIC const char *CkMime_lastErrorHtml(HCkMime cHandle);
CK_VISIBLE_PUBLIC void CkMime_getLastErrorText(HCkMime cHandle, HCkString retval);
CK_VISIBLE_PUBLIC const char *CkMime_lastErrorText(HCkMime cHandle);
CK_VISIBLE_PUBLIC void CkMime_getLastErrorXml(HCkMime cHandle, HCkString retval);
CK_VISIBLE_PUBLIC const char *CkMime_lastErrorXml(HCkMime cHandle);
CK_VISIBLE_PUBLIC BOOL CkMime_getLastMethodSuccess(HCkMime cHandle);
CK_VISIBLE_PUBLIC void CkMime_putLastMethodSuccess(HCkMime cHandle, BOOL newVal);
CK_VISIBLE_PUBLIC void CkMime_getMicalg(HCkMime cHandle, HCkString retval);
CK_VISIBLE_PUBLIC void CkMime_putMicalg(HCkMime cHandle, const char *newVal);
CK_VISIBLE_PUBLIC const char *CkMime_micalg(HCkMime cHandle);
CK_VISIBLE_PUBLIC void CkMime_getName(HCkMime cHandle, HCkString retval);
CK_VISIBLE_PUBLIC void CkMime_putName(HCkMime cHandle, const char *newVal);
CK_VISIBLE_PUBLIC const char *CkMime_name(HCkMime cHandle);
CK_VISIBLE_PUBLIC int CkMime_getNumEncryptCerts(HCkMime cHandle);
CK_VISIBLE_PUBLIC int CkMime_getNumHeaderFields(HCkMime cHandle);
CK_VISIBLE_PUBLIC int CkMime_getNumParts(HCkMime cHandle);
CK_VISIBLE_PUBLIC int CkMime_getNumSignerCerts(HCkMime cHandle);
CK_VISIBLE_PUBLIC void CkMime_getOaepHash(HCkMime cHandle, HCkString retval);
CK_VISIBLE_PUBLIC void CkMime_putOaepHash(HCkMime cHandle, const char *newVal);
CK_VISIBLE_PUBLIC const char *CkMime_oaepHash(HCkMime cHandle);
CK_VISIBLE_PUBLIC BOOL CkMime_getOaepPadding(HCkMime cHandle);
CK_VISIBLE_PUBLIC void CkMime_putOaepPadding(HCkMime cHandle, BOOL newVal);
CK_VISIBLE_PUBLIC void CkMime_getPkcs7CryptAlg(HCkMime cHandle, HCkString retval);
CK_VISIBLE_PUBLIC void CkMime_putPkcs7CryptAlg(HCkMime cHandle, const char *newVal);
CK_VISIBLE_PUBLIC const char *CkMime_pkcs7CryptAlg(HCkMime cHandle);
CK_VISIBLE_PUBLIC int CkMime_getPkcs7KeyLength(HCkMime cHandle);
CK_VISIBLE_PUBLIC void CkMime_putPkcs7KeyLength(HCkMime cHandle, int newVal);
CK_VISIBLE_PUBLIC void CkMime_getProtocol(HCkMime cHandle, HCkString retval);
CK_VISIBLE_PUBLIC void CkMime_putProtocol(HCkMime cHandle, const char *newVal);
CK_VISIBLE_PUBLIC const char *CkMime_protocol(HCkMime cHandle);
CK_VISIBLE_PUBLIC void CkMime_getSigningAlg(HCkMime cHandle, HCkString retval);
CK_VISIBLE_PUBLIC void CkMime_putSigningAlg(HCkMime cHandle, const char *newVal);
CK_VISIBLE_PUBLIC const char *CkMime_signingAlg(HCkMime cHandle);
CK_VISIBLE_PUBLIC void CkMime_getSigningHashAlg(HCkMime cHandle, HCkString retval);
CK_VISIBLE_PUBLIC void CkMime_putSigningHashAlg(HCkMime cHandle, const char *newVal);
CK_VISIBLE_PUBLIC const char *CkMime_signingHashAlg(HCkMime cHandle);
CK_VISIBLE_PUBLIC BOOL CkMime_getUnwrapExtras(HCkMime cHandle);
CK_VISIBLE_PUBLIC void CkMime_putUnwrapExtras(HCkMime cHandle, BOOL newVal);
CK_VISIBLE_PUBLIC BOOL CkMime_getUseMmDescription(HCkMime cHandle);
CK_VISIBLE_PUBLIC void CkMime_putUseMmDescription(HCkMime cHandle, BOOL newVal);
CK_VISIBLE_PUBLIC BOOL CkMime_getUseXPkcs7(HCkMime cHandle);
CK_VISIBLE_PUBLIC void CkMime_putUseXPkcs7(HCkMime cHandle, BOOL newVal);
CK_VISIBLE_PUBLIC BOOL CkMime_getUtf8(HCkMime cHandle);
CK_VISIBLE_PUBLIC void CkMime_putUtf8(HCkMime cHandle, BOOL newVal);
CK_VISIBLE_PUBLIC BOOL CkMime_getVerboseLogging(HCkMime cHandle);
CK_VISIBLE_PUBLIC void CkMime_putVerboseLogging(HCkMime cHandle, BOOL newVal);
CK_VISIBLE_PUBLIC void CkMime_getVersion(HCkMime cHandle, HCkString retval);
CK_VISIBLE_PUBLIC const char *CkMime_version(HCkMime cHandle);
CK_VISIBLE_PUBLIC void CkMime_AddContentLength(HCkMime cHandle);
CK_VISIBLE_PUBLIC BOOL CkMime_AddDecryptCert(HCkMime cHandle, HCkCert cert);
CK_VISIBLE_PUBLIC BOOL CkMime_AddDetachedSignature(HCkMime cHandle, HCkCert cert);
CK_VISIBLE_PUBLIC BOOL CkMime_AddDetachedSignature2(HCkMime cHandle, HCkCert cert, BOOL transferHeaderFields);
CK_VISIBLE_PUBLIC BOOL CkMime_AddDetachedSignaturePk(HCkMime cHandle, HCkCert cert, HCkPrivateKey privateKey);
CK_VISIBLE_PUBLIC BOOL CkMime_AddDetachedSignaturePk2(HCkMime cHandle, HCkCert cert, HCkPrivateKey privateKey, BOOL transferHeaderFields);
CK_VISIBLE_PUBLIC BOOL CkMime_AddEncryptCert(HCkMime cHandle, HCkCert cert);
CK_VISIBLE_PUBLIC BOOL CkMime_AddHeaderField(HCkMime cHandle, const char *name, const char *value);
CK_VISIBLE_PUBLIC BOOL CkMime_AddPfxSourceData(HCkMime cHandle, HCkByteData pfxFileData, const char *pfxPassword);
CK_VISIBLE_PUBLIC BOOL CkMime_AddPfxSourceFile(HCkMime cHandle, const char *pfxFilePath, const char *password);
CK_VISIBLE_PUBLIC BOOL CkMime_AppendPart(HCkMime cHandle, HCkMime mime);
CK_VISIBLE_PUBLIC BOOL CkMime_AppendPartFromFile(HCkMime cHandle, const char *filename);
CK_VISIBLE_PUBLIC BOOL CkMime_AsnBodyToXml(HCkMime cHandle, HCkString outStr);
CK_VISIBLE_PUBLIC const char *CkMime_asnBodyToXml(HCkMime cHandle);
CK_VISIBLE_PUBLIC void CkMime_ClearEncryptCerts(HCkMime cHandle);
CK_VISIBLE_PUBLIC BOOL CkMime_ContainsEncryptedParts(HCkMime cHandle);
CK_VISIBLE_PUBLIC BOOL CkMime_ContainsSignedParts(HCkMime cHandle);
CK_VISIBLE_PUBLIC void CkMime_Convert8Bit(HCkMime cHandle);
CK_VISIBLE_PUBLIC BOOL CkMime_ConvertToMultipartAlt(HCkMime cHandle);
CK_VISIBLE_PUBLIC BOOL CkMime_ConvertToMultipartMixed(HCkMime cHandle);
CK_VISIBLE_PUBLIC BOOL CkMime_ConvertToSigned(HCkMime cHandle, HCkCert cert);
CK_VISIBLE_PUBLIC BOOL CkMime_ConvertToSignedPk(HCkMime cHandle, HCkCert cert, HCkPrivateKey privateKey);
CK_VISIBLE_PUBLIC BOOL CkMime_Decrypt(HCkMime cHandle);
CK_VISIBLE_PUBLIC BOOL CkMime_Decrypt2(HCkMime cHandle, HCkCert cert, HCkPrivateKey privateKey);
CK_VISIBLE_PUBLIC BOOL CkMime_DecryptUsingCert(HCkMime cHandle, HCkCert cert);
CK_VISIBLE_PUBLIC BOOL CkMime_DecryptUsingPfxData(HCkMime cHandle, HCkByteData pfxData, const char *password);
CK_VISIBLE_PUBLIC BOOL CkMime_DecryptUsingPfxFile(HCkMime cHandle, const char *pfxFilePath, const char *pfxPassword);
CK_VISIBLE_PUBLIC BOOL CkMime_Encrypt(HCkMime cHandle, HCkCert cert);
CK_VISIBLE_PUBLIC BOOL CkMime_EncryptN(HCkMime cHandle);
CK_VISIBLE_PUBLIC HCkStringArray CkMime_ExtractPartsToFiles(HCkMime cHandle, const char *dirPath);
CK_VISIBLE_PUBLIC HCkCert CkMime_FindIssuer(HCkMime cHandle, HCkCert cert);
CK_VISIBLE_PUBLIC BOOL CkMime_GetBodyBd(HCkMime cHandle, HCkBinData binDat);
CK_VISIBLE_PUBLIC BOOL CkMime_GetBodyBinary(HCkMime cHandle, HCkByteData outData);
CK_VISIBLE_PUBLIC BOOL CkMime_GetBodyDecoded(HCkMime cHandle, HCkString outStr);
CK_VISIBLE_PUBLIC const char *CkMime_getBodyDecoded(HCkMime cHandle);
CK_VISIBLE_PUBLIC BOOL CkMime_GetBodyEncoded(HCkMime cHandle, HCkString outStr);
CK_VISIBLE_PUBLIC const char *CkMime_getBodyEncoded(HCkMime cHandle);
CK_VISIBLE_PUBLIC HCkCert CkMime_GetEncryptCert(HCkMime cHandle, int index);
CK_VISIBLE_PUBLIC BOOL CkMime_GetEntireBody(HCkMime cHandle, HCkString outStr);
CK_VISIBLE_PUBLIC const char *CkMime_getEntireBody(HCkMime cHandle);
CK_VISIBLE_PUBLIC BOOL CkMime_GetEntireHead(HCkMime cHandle, HCkString outStr);
CK_VISIBLE_PUBLIC const char *CkMime_getEntireHead(HCkMime cHandle);
CK_VISIBLE_PUBLIC BOOL CkMime_GetHeaderField(HCkMime cHandle, const char *fieldName, HCkString outStr);
CK_VISIBLE_PUBLIC const char *CkMime_getHeaderField(HCkMime cHandle, const char *fieldName);
CK_VISIBLE_PUBLIC BOOL CkMime_GetHeaderFieldAttribute(HCkMime cHandle, const char *name, const char *attrName, HCkString outStr);
CK_VISIBLE_PUBLIC const char *CkMime_getHeaderFieldAttribute(HCkMime cHandle, const char *name, const char *attrName);
CK_VISIBLE_PUBLIC BOOL CkMime_GetHeaderFieldName(HCkMime cHandle, int index, HCkString outStr);
CK_VISIBLE_PUBLIC const char *CkMime_getHeaderFieldName(HCkMime cHandle, int index);
CK_VISIBLE_PUBLIC BOOL CkMime_GetHeaderFieldValue(HCkMime cHandle, int index, HCkString outStr);
CK_VISIBLE_PUBLIC const char *CkMime_getHeaderFieldValue(HCkMime cHandle, int index);
CK_VISIBLE_PUBLIC BOOL CkMime_GetMime(HCkMime cHandle, HCkString outStr);
CK_VISIBLE_PUBLIC const char *CkMime_getMime(HCkMime cHandle);
CK_VISIBLE_PUBLIC BOOL CkMime_GetMimeBd(HCkMime cHandle, HCkBinData bindat);
CK_VISIBLE_PUBLIC BOOL CkMime_GetMimeBytes(HCkMime cHandle, HCkByteData outBytes);
CK_VISIBLE_PUBLIC BOOL CkMime_GetMimeSb(HCkMime cHandle, HCkStringBuilder sb);
CK_VISIBLE_PUBLIC HCkMime CkMime_GetPart(HCkMime cHandle, int index);
CK_VISIBLE_PUBLIC BOOL CkMime_GetSignatureSigningTime(HCkMime cHandle, int index, SYSTEMTIME *outSysTime);
CK_VISIBLE_PUBLIC BOOL CkMime_GetSignatureSigningTimeStr(HCkMime cHandle, int index, HCkString outStr);
CK_VISIBLE_PUBLIC const char *CkMime_getSignatureSigningTimeStr(HCkMime cHandle, int index);
CK_VISIBLE_PUBLIC HCkCert CkMime_GetSignerCert(HCkMime cHandle, int index);
CK_VISIBLE_PUBLIC HCkCertChain CkMime_GetSignerCertChain(HCkMime cHandle, int index);
CK_VISIBLE_PUBLIC BOOL CkMime_GetStructure(HCkMime cHandle, const char *fmt, HCkString outStr);
CK_VISIBLE_PUBLIC const char *CkMime_getStructure(HCkMime cHandle, const char *fmt);
CK_VISIBLE_PUBLIC BOOL CkMime_GetXml(HCkMime cHandle, HCkString outStr);
CK_VISIBLE_PUBLIC const char *CkMime_getXml(HCkMime cHandle);
CK_VISIBLE_PUBLIC BOOL CkMime_HasSignatureSigningTime(HCkMime cHandle, int index);
CK_VISIBLE_PUBLIC BOOL CkMime_IsApplicationData(HCkMime cHandle);
CK_VISIBLE_PUBLIC BOOL CkMime_IsAttachment(HCkMime cHandle);
CK_VISIBLE_PUBLIC BOOL CkMime_IsAudio(HCkMime cHandle);
CK_VISIBLE_PUBLIC BOOL CkMime_IsEncrypted(HCkMime cHandle);
CK_VISIBLE_PUBLIC BOOL CkMime_IsHtml(HCkMime cHandle);
CK_VISIBLE_PUBLIC BOOL CkMime_IsImage(HCkMime cHandle);
CK_VISIBLE_PUBLIC BOOL CkMime_IsMultipart(HCkMime cHandle);
CK_VISIBLE_PUBLIC BOOL CkMime_IsMultipartAlternative(HCkMime cHandle);
CK_VISIBLE_PUBLIC BOOL CkMime_IsMultipartMixed(HCkMime cHandle);
CK_VISIBLE_PUBLIC BOOL CkMime_IsMultipartRelated(HCkMime cHandle);
CK_VISIBLE_PUBLIC BOOL CkMime_IsPlainText(HCkMime cHandle);
CK_VISIBLE_PUBLIC BOOL CkMime_IsSigned(HCkMime cHandle);
CK_VISIBLE_PUBLIC BOOL CkMime_IsText(HCkMime cHandle);
CK_VISIBLE_PUBLIC BOOL CkMime_IsUnlocked(HCkMime cHandle);
CK_VISIBLE_PUBLIC BOOL CkMime_IsVideo(HCkMime cHandle);
CK_VISIBLE_PUBLIC BOOL CkMime_IsXml(HCkMime cHandle);
CK_VISIBLE_PUBLIC BOOL CkMime_LoadMime(HCkMime cHandle, const char *mimeMsg);
CK_VISIBLE_PUBLIC BOOL CkMime_LoadMimeBd(HCkMime cHandle, HCkBinData bindat);
CK_VISIBLE_PUBLIC BOOL CkMime_LoadMimeBytes(HCkMime cHandle, HCkByteData binData);
CK_VISIBLE_PUBLIC BOOL CkMime_LoadMimeFile(HCkMime cHandle, const char *fileName);
CK_VISIBLE_PUBLIC BOOL CkMime_LoadMimeSb(HCkMime cHandle, HCkStringBuilder sb);
CK_VISIBLE_PUBLIC BOOL CkMime_LoadXml(HCkMime cHandle, const char *xml);
CK_VISIBLE_PUBLIC BOOL CkMime_LoadXmlFile(HCkMime cHandle, const char *fileName);
CK_VISIBLE_PUBLIC BOOL CkMime_NewMessageRfc822(HCkMime cHandle, HCkMime mimeObject);
CK_VISIBLE_PUBLIC BOOL CkMime_NewMultipartAlternative(HCkMime cHandle);
CK_VISIBLE_PUBLIC BOOL CkMime_NewMultipartMixed(HCkMime cHandle);
CK_VISIBLE_PUBLIC BOOL CkMime_NewMultipartRelated(HCkMime cHandle);
CK_VISIBLE_PUBLIC void CkMime_RemoveHeaderField(HCkMime cHandle, const char *fieldName, BOOL bAllOccurrences);
CK_VISIBLE_PUBLIC BOOL CkMime_RemovePart(HCkMime cHandle, int index);
CK_VISIBLE_PUBLIC BOOL CkMime_SaveBody(HCkMime cHandle, const char *filename);
CK_VISIBLE_PUBLIC BOOL CkMime_SaveLastError(HCkMime cHandle, const char *path);
CK_VISIBLE_PUBLIC BOOL CkMime_SaveMime(HCkMime cHandle, const char *filename);
CK_VISIBLE_PUBLIC BOOL CkMime_SaveXml(HCkMime cHandle, const char *filename);
CK_VISIBLE_PUBLIC void CkMime_SetBody(HCkMime cHandle, const char *str);
CK_VISIBLE_PUBLIC BOOL CkMime_SetBodyFromBinary(HCkMime cHandle, HCkByteData binData);
CK_VISIBLE_PUBLIC BOOL CkMime_SetBodyFromEncoded(HCkMime cHandle, const char *encoding, const char *str);
CK_VISIBLE_PUBLIC BOOL CkMime_SetBodyFromFile(HCkMime cHandle, const char *fileName);
CK_VISIBLE_PUBLIC BOOL CkMime_SetBodyFromHtml(HCkMime cHandle, const char *str);
CK_VISIBLE_PUBLIC BOOL CkMime_SetBodyFromPlainText(HCkMime cHandle, const char *str);
CK_VISIBLE_PUBLIC BOOL CkMime_SetBodyFromXml(HCkMime cHandle, const char *str);
#if defined(CK_CSP_INCLUDED)
CK_VISIBLE_PUBLIC BOOL CkMime_SetCSP(HCkMime cHandle, HCkCsp csp);
#endif
CK_VISIBLE_PUBLIC BOOL CkMime_SetHeaderField(HCkMime cHandle, const char *name, const char *value);
CK_VISIBLE_PUBLIC BOOL CkMime_SetVerifyCert(HCkMime cHandle, HCkCert cert);
CK_VISIBLE_PUBLIC BOOL CkMime_UnlockComponent(HCkMime cHandle, const char *unlockCode);
CK_VISIBLE_PUBLIC BOOL CkMime_UnwrapSecurity(HCkMime cHandle);
CK_VISIBLE_PUBLIC void CkMime_UrlEncodeBody(HCkMime cHandle, const char *charset);
CK_VISIBLE_PUBLIC BOOL CkMime_UseCertVault(HCkMime cHandle, HCkXmlCertVault vault);
CK_VISIBLE_PUBLIC BOOL CkMime_Verify(HCkMime cHandle);
#endif


text:
using Microsoft.AspNet.Mvc;

namespace Identity.vNext.MVC5.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }

        public IActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public IActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }

        public IActionResult Error()
        {
            return View("~/Views/Shared/Error.cshtml");
        }
    }
}


text:
"""Unit tests for the FieldSignatureMixin."""

import peewee
import pytest

from fleaker.peewee import ArchivedMixin, FieldSignatureMixin

@pytest.fixture
def folder_model(database):
    class Folder(FieldSignatureMixin, ArchivedMixin):
        # This class represents a Folder in a file system. Two Folders with
        # the same name cannot exist in the same Folder. If the Folder has
        # no Parent Folder, it exists in the top level of the file system.
        name = peewee.CharField(max_length=255, null=False)
        parent_folder = peewee.ForeignKeyField('self', null=True)

        class Meta:
            signature_fields = ('name', 'parent_folder')

    Folder._meta.database = database.database
    Folder.create_table(True)

    return Folder

def test_signature_fields_must_be_set(folder_model):
    """
    Ensure that an exception is raised if the signature_fields aren't set.
    """
    folder_model._meta.signature_fields = ()

    with pytest.raises(AttributeError):
        folder_model(name='etc').save()

def test_signature_functionality(folder_model):
    """Ensure that the FieldSignatureMixin works as expected."""
    # Create a Folder named 'etc' in the root of the file system.
    etc_folder = folder_model(name='etc')
    etc_folder.save()

    assert etc_folder.signature
    assert len(etc_folder.signature) == 40

    # No other Folders in the root may be named 'etc
    with pytest.raises(peewee.IntegrityError):
        folder_model(name='etc').save()

    # Let's test this with a child Folder of 'etc'
    apt_folder = folder_model(name='apt', parent_folder=etc_folder)
    apt_folder.save()

    assert apt_folder.signature
    assert len(apt_folder.signature) == 40

    # Can't have another named 'apt' in 'etc'
    with pytest.raises(peewee.IntegrityError):
        folder_model(name='apt', parent_folder=etc_folder).save()

    # If a Folder is archived, it's signature is nulled out
    etc_folder.archive_instance()

    assert etc_folder.signature is None


text:
module SessionsHelper

  #Logs in the given user
  def log_in(user)
    session[:user_id] = user.id
  end

  # Remembers a user in a persistent session.
  def remember(user)
    user.remember
    cookies.permanent.signed[:user_id] = user.id
    cookies.permanent[:remember_token] = user.remember_token
  end

  # Returns the current logged-in user (if any).
  def current_user
    if (user_id = session[:user_id])
      @current_user ||= User.find_by(id: user_id)
    elsif (user_id = cookies.signed[:user_id])
      user = User.find_by(id: user_id)
      if user && user.authenticated?(cookies[:remember_token])
        log_in user
        @current_user = user
      end
    end
  end

  # Returns true if the user is logged in, false otherwise.
  def logged_in?
    !current_user.nil?
  end

  # Forgets a persistent session
  def forget(user)
    user.forget
    cookies.delete(:user_id)
    cookies.delete(:remember_token)
  end

  # Logs out the current user.
  def log_out
    forget(current_user)
    session.delete(:user_id)
    @current_user = nil
  end
end


text:
class CreateHhs < ActiveRecord::Migration
  def change
    create_table :hhs do |t|

      t.timestamps null: false
    end
  end
end


text:
angular.module('refScheduler')
    .controller('tournamentCtrl', ['$scope', 'dataService', '$location', '$routeParams', function($scope, dataService, $location, $routeParams) {
    dataService.get('tournament/all')
        .then(function success(response){
            $scope.tournaments = response.data;
        }, function error(response) {
            $scope.errors = response.status;
        });

        if ($routeParams.id) {
            dataService.get('tournament/id/' + $routeParams.id)
                .then(function success(response) {
                    $scope.id = response.data.id;
                    $scope.name = response.data.name;
                    $scope.location = response.data.location
                    $scope.pitches = response.data.pitches
                }, function error(response) {
                    window.alert("Couldn't retrieve tournament");
                    $location.path("/tournament");
                });
        } else {
            $scope.id = '';
            $scope.name = '';
            $scope.location = '';
            $scope.pitches = '';
            $scope.uploadText = '';
        }

        $scope.submit = function() {
          var dateTime = new Date($scope.time);
          dataService.post('tournament',
            {
                id: $scope.id,
                name: $scope.name,
                location: $scope.location,
                pitches: $scope.pitches
            })
          .then(function success(response) {
                $location.path("/tournament");
          }, function error(response) {
                $scope.errors = response.status;
                window.alert("Create failed");
          });
        };

        $scope.submitAndCreateAnother = function() {
          var dateTime = new Date($scope.time);
          dataService.post('tournament',
            {
                id: $scope.id,
                name: $scope.name,
                location: $scope.location,
                pitches: $scope.pitches
            })
          .then(function success(response) {
                window.alert("Create successful");
                $scope.time = '';
          }, function error(response) {
                $scope.errors = response.status;
                window.alert("Create failed");
          });
        };

        $scope.upload = function() {
            dataService.post('tournament/upload', $scope.uploadText);
            $scope.uploadText = '';
        }

        $scope.delete = function(tournament) {
            dataService.delete('tournament/' + tournament.id)
            .then(function success(response) {
                $scope.tournaments.splice($scope.tournaments.indexOf(tournament), 1);
            }, function error(response) {
                window.alert("Delete failed!");
            });
        };
}]);


text:
package com.google.testing.compile;

import static com.google.common.truth.Truth.assertThat;

import com.google.common.collect.ImmutableList;

import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.Tree;
import com.sun.source.util.TreePath;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/**
 * A test for {@link DetailedEqualityScanner}
 */
@RunWith(JUnit4.class)
public class TreeDifferTest {
  @Rule public final ExpectedException expectedExn = ExpectedException.none();
  private static final CompilationUnitTree EXPECTED_TREE =
      MoreTrees.parseLinesToTree("package test;",
          "import java.util.Set;",
          "",
          "final class TestClass {",
          "    public String toString() {",
          "        Object variable = new Object();",
          "        return \"literal\" + variable;",
          "    }",
          "",
          "    public void nonsense() {",
          "        int[] numbers = {0, 1, 2, 3, 4};",
          "        loop: for (int x : numbers) {",
          "            if (x % 2 == 0) {",
          "                throw new IllegalStateException();",
          "            }",
          "            break loop;",
          "        }",
          "    }",
          "}");
  private static final CompilationUnitTree ACTUAL_TREE =
      MoreTrees.parseLinesToTree("package test;",
          "import java.util.List;",
          "",
          "final class TestClass {",
          "    public String toString() {",
          "        Object variable = new Object();",
          "        return \"literal\" + variable;",
          "    }",
          "",
          "    public void nonsense() {",
          "        int[] numberz = {0, 1, 2, 3, 4, 5};",
          "        loop: for (int x : numberz) {",
          "            if (x % 2 == 0) {",
          "                throw new RuntimeException();",
          "            }",
          "            break;",
          "        }",
          "    }",
          "    public int extraNonsense() {",
          "      return 0;",
          "    }",
          "}");
  private static final CompilationUnitTree ASSERT_TREE_WITH_MESSAGE =
      MoreTrees.parseLinesToTree("package test;",
          "final class TestClass {",
          "   private void fail() {",
          "      assert false : \"details\";",
          "   }",
          "}");
  private static final CompilationUnitTree ASSERT_TREE_WITHOUT_MESSAGE =
      MoreTrees.parseLinesToTree("package test;",
          "final class TestClass {",
          "   private void fail() {",
          "      assert false;",
          "   }",
          "}");

  // These are used to test null tree iterators.
  // getInitializers() on NewArrayTrees will return null if the array is dimension-defined.
  private static final CompilationUnitTree NEW_ARRAY_SIZE_THREE =
      MoreTrees.parseLinesToTree("package test;",
          "final class TestClass {",
          "  private static final int[] myArray = new int[3];",
          "}");

  private static final CompilationUnitTree NEW_ARRAY_SIZE_FOUR =
      MoreTrees.parseLinesToTree("package test;",
          "final class TestClass {",
          "  private static final int[] myArray = new int[4];",
          "}");

  private static final CompilationUnitTree NEW_ARRAY_STATIC_INITIALIZER =
      MoreTrees.parseLinesToTree("package test;",
          "final class TestClass {",
          "  private static final int[] myArray = {1, 2, 3};",
          "}");
  @Test
  public void scan_differingCompilationUnits() {
    TreeDifference diff = TreeDiffer.diffCompilationUnits(EXPECTED_TREE, ACTUAL_TREE);
    assertThat(diff.isEmpty()).isFalse();

    ImmutableList<SimplifiedDiff> extraNodesExpected = ImmutableList.of(
        new SimplifiedDiff(Tree.Kind.INT_LITERAL, ""),
        new SimplifiedDiff(Tree.Kind.METHOD, ""));

    ImmutableList<SimplifiedDiff> differingNodesExpected = ImmutableList.of(
        new SimplifiedDiff(Tree.Kind.MEMBER_SELECT,
            "Expected member identifier to be <Set> but was <List>."),
        new SimplifiedDiff(Tree.Kind.VARIABLE,
            "Expected variable name to be <numbers> but was <numberz>."),
        new SimplifiedDiff(Tree.Kind.IDENTIFIER,
            "Expected identifier to be <numbers> but was <numberz>."),
        new SimplifiedDiff(Tree.Kind.IDENTIFIER,
            "Expected identifier to be <IllegalStateException> but was <RuntimeException>."),
        new SimplifiedDiff(Tree.Kind.BREAK,
            "Expected label on break statement to be <loop> but was <null>."));
    assertThat(diff.getExtraExpectedNodes().isEmpty()).isTrue();
    assertThat(diff.getExtraActualNodes().size()).isEqualTo(extraNodesExpected.size());

    ImmutableList.Builder<SimplifiedDiff> extraNodesFound =
        new ImmutableList.Builder<SimplifiedDiff>();
    for (TreeDifference.OneWayDiff extraNode : diff.getExtraActualNodes()) {
      extraNodesFound.add(SimplifiedDiff.create(extraNode));
    }
    assertThat(extraNodesExpected).containsExactlyElementsIn(extraNodesFound.build()).inOrder();
    ImmutableList.Builder<SimplifiedDiff> differingNodesFound =
        new ImmutableList.Builder<SimplifiedDiff>();
    for (TreeDifference.TwoWayDiff differingNode : diff.getDifferingNodes()) {
      differingNodesFound.add(SimplifiedDiff.create(differingNode));
    }
    assertThat(differingNodesExpected)
        .containsExactlyElementsIn(differingNodesFound.build())
        .inOrder();
  }

  @Test
  public void scan_testExtraFields() {
    TreeDifference diff =
        TreeDiffer.diffCompilationUnits(ASSERT_TREE_WITH_MESSAGE, ASSERT_TREE_WITHOUT_MESSAGE);
    assertThat(diff.isEmpty()).isFalse();
    diff = TreeDiffer.diffCompilationUnits(ASSERT_TREE_WITHOUT_MESSAGE, ASSERT_TREE_WITH_MESSAGE);
    assertThat(diff.isEmpty()).isFalse();
  }

  @Test
  public void scan_sameCompilationUnit() {
    assertThat(TreeDiffer.diffCompilationUnits(EXPECTED_TREE, EXPECTED_TREE).isEmpty()).isTrue();
  }

  @Test
  public void scan_identicalMethods() {
    assertThat(TreeDiffer.diffSubtrees(baseToStringTree(), diffToStringTree())
        .isEmpty()).isTrue();
  }

  @Test
  public void scan_differentTypes() {
    TreeDifference diff = TreeDiffer.diffSubtrees(asPath(EXPECTED_TREE), diffToStringTree());
    assertThat(diff.isEmpty()).isFalse();
    for (TreeDifference.TwoWayDiff differingNode : diff.getDifferingNodes()) {
      assertThat(differingNode.getDetails()).contains("Expected node kind to be");
    }
  }

  @Test
  public void scan_testTwoNullIterableTrees() {
    TreeDifference diff =
        TreeDiffer.diffCompilationUnits(NEW_ARRAY_SIZE_THREE, NEW_ARRAY_SIZE_FOUR);
    assertThat(diff.isEmpty()).isFalse();
    for (TreeDifference.TwoWayDiff differingNode : diff.getDifferingNodes()) {
      assertThat(differingNode.getDetails())
          .contains("Expected literal value to be <3> but was <4>");
    }
  }

  @Test
  public void scan_testExpectedNullIterableTree() {
    TreeDifference diff =
        TreeDiffer.diffCompilationUnits(NEW_ARRAY_SIZE_THREE, NEW_ARRAY_STATIC_INITIALIZER);
    assertThat(diff.isEmpty()).isFalse();
  }

  @Test
  public void scan_testActualNullIterableTree() {
    TreeDifference diff =
        TreeDiffer.diffCompilationUnits(NEW_ARRAY_STATIC_INITIALIZER, NEW_ARRAY_SIZE_FOUR);
    assertThat(diff.isEmpty()).isFalse();
  }

  private TreePath asPath(CompilationUnitTree compilationUnit) {
    return MoreTrees.findSubtreePath(compilationUnit, Tree.Kind.COMPILATION_UNIT);
  }

  private TreePath baseToStringTree() {
    return MoreTrees.findSubtreePath(EXPECTED_TREE, Tree.Kind.METHOD, "toString");
  }

  private TreePath diffToStringTree() {
    return MoreTrees.findSubtreePath(ACTUAL_TREE, Tree.Kind.METHOD, "toString");
  }

  private static class SimplifiedDiff {
    private final Tree.Kind kind;
    private final String details;

    SimplifiedDiff(Tree.Kind kind, String details) {
      this.kind = kind;
      this.details = details;
    }

    Tree.Kind getKind() {
      return kind;
    }

    String getDetails() {
      return details;
    }

    static SimplifiedDiff create(TreeDifference.OneWayDiff other) {
      return new SimplifiedDiff(other.getNodePath().getLeaf().getKind(), other.getDetails());
    }

    static SimplifiedDiff create(TreeDifference.TwoWayDiff other) {
      return new SimplifiedDiff(
          other.getExpectedNodePath().getLeaf().getKind(), other.getDetails());
    }

    @Override
    public String toString() {
      return String.format("%s: %s", this.kind.toString(), this.details.toString());
    }

    @Override
    public boolean equals(Object o) {
      if (!(o instanceof SimplifiedDiff)) {
        return false;
      }

      // Checked by the above instanceof
      @SuppressWarnings("unchecked")
      SimplifiedDiff otherDiff = (SimplifiedDiff) o;
      return otherDiff.kind.equals(this.kind) && otherDiff.details.equals(this.details);
    }
  }
}


text:
using System;
using Terraria;
using OTA.Command;
using OTA;
using Microsoft.Xna.Framework;

namespace TDSM.Core.Command.Commands
{
    public class KillNpcCommand : CoreCommand
    {
        public override void Initialise()
        {
            AddCommand("killnpc")
                .WithAccessLevel(AccessLevel.OP)
                .WithPermissionNode("tdsm.killnpc")
                .WithDescription("Kill all non town NPC's")
                .Calls(this.KillNPC);

            AddCommand("killnpcs")
                .WithAccessLevel(AccessLevel.OP)
                .WithPermissionNode("tdsm.killnpc")
                .WithDescription("Kill all non town NPC's")
                .Calls(this.KillNPC);
        }

        void KillNPC(ISender sender, ArgumentList args)
        {
            if (Main.rand == null)
                Main.rand = new Random();

            if (Core._likeABoss) Core._likeABoss = false;

            int killed = 0;
            foreach (var npc in Main.npc)
            {
                if (npc != null && npc.active && !npc.townNPC && npc.whoAmI < 255)
                {
                    int damage = Int32.MaxValue;
                    npc.StrikeNPC(damage, 0, 0);
                    NetMessage.SendData((int)Packet.STRIKE_NPC, -1, -1, "", npc.whoAmI, damage);
                    NetMessage.SendData((int)Packet.NPC_INFO, -1, -1, "", npc.whoAmI, 0, 0, 0, 0, 0, 0);

                    killed++;
                }
            }

            sender.Message("Killed {0} npc(s)", Color.Green, killed);
        }
    }
}


text:
if [ ! -d ~/Sandbox/solarized ]; then
    git clone https://github.com/altercation/solarized.git ~/Sandbox/solarized
fi


text:
package net.mgsx.game.core.ui.events;

import com.badlogic.gdx.scenes.scene2d.Event;
import com.badlogic.gdx.utils.Pool.Poolable;

import net.mgsx.game.core.ui.accessors.Accessor;

public class AccessorHelpEvent extends Event implements Poolable
{
	private Accessor accessor;

	public AccessorHelpEvent(Accessor accessor) {
		super();
		this.accessor = accessor;
	}

	public Accessor getAccessor() {
		return accessor;
	}

}


text:
<?xml version="1.0" encoding="utf-8"?>
 <rotate xmlns:android="http://schemas.android.com/apk/res/android"
	android:pivotX="50%"
	android:pivotY="50%"
	android:fromDegrees="0"
	android:toDegrees="360"
	android:drawable="@drawable/sf__refresh_loader"
	android:duration="600"
/>
<!-- From: file:/Users/craigisakson/Documents/Android%20Code/df15-workspace/SalesforceSDK/res/drawable-xlarge/sf__progress_spinner.xml -->


text:
suite('Selection', function() {

  var wrap = ShadowDOMPolyfill.wrap;
  var div, a, b, c;

  teardown(function() {
    if (div && div.parentNode)
      div.parentNode.removeChild(div);
    div = a = b = c = undefined;
  });

  setup(function() {
    div = document.createElement('div');
    div.innerHTML = 'ab<c>c</c>';
    a = div.firstChild;
    b = a.nextSibling;
    c = div.lastChild;
    document.body.appendChild(div);
  });

  test('document.getSelection()', function() {
    var selection = document.getSelection();
    assert.instanceOf(selection, Selection);

    var doc = wrap(document);
    selection = doc.getSelection();
    assert.instanceOf(selection, Selection);
  });

  test('window.getSelection()', function() {
    var selection = window.getSelection();
    assert.instanceOf(selection, Selection);

    var win = wrap(window);
    selection = win.getSelection();
    assert.instanceOf(selection, Selection);
  });

  test('constructor', function() {
    var selection = window.getSelection();
    assert.equal(Selection, selection.constructor);
  });

  test('getSelection()', function() {
    var selection = getSelection();
    assert.instanceOf(selection, Selection);
  });

  test('basics', function() {
    var selection = window.getSelection();
    selection.selectAllChildren(div);

    assert.equal(selection.toString(), 'abc');

    assert.isFalse(selection.isCollapsed);
    assert.equal(selection.rangeCount, 1);

    // https://code.google.com/p/chromium/issues/detail?id=336821
    if (/WebKit/.test(navigator.userAgent))
      return;

    assert.equal(selection.anchorNode, div);
    assert.equal(selection.anchorOffset, 0);

    assert.equal(selection.focusNode, div);
    assert.equal(selection.focusOffset, 3);
  });

  test('getRangeAt', function() {
    var selection = window.getSelection();
    selection.selectAllChildren(div);
    var range = selection.getRangeAt(0);
    assert.instanceOf(range, Range);
  });

  test('collapse', function() {
    var selection = window.getSelection();

    for (var i = 0; i < 4; i++) {
      selection.selectAllChildren(div);
      selection.collapse(div, i);

      assert.isTrue(selection.isCollapsed);
      assert.equal(selection.toString(), '');

      // https://code.google.com/p/chromium/issues/detail?id=336821
      if (/WebKit/.test(navigator.userAgent))
        continue;

      assert.equal(selection.anchorNode, div);
      assert.equal(selection.anchorOffset, i);

      assert.equal(selection.focusNode, div);
      assert.equal(selection.focusOffset, i);
    }
  });

  test('extend', function() {
    // IE legacy document modes do not have extend.
    if (/Trident/.test(navigator.userAgent))
      return;

    var selection = window.getSelection();

    for (var i = 0; i < 4; i++) {
      selection.selectAllChildren(div);
      selection.extend(div, i);

      assert.equal(selection.isCollapsed, i === 0);
      assert.equal(selection.toString(), 'abc'.slice(0, i));

      // https://code.google.com/p/chromium/issues/detail?id=336821
      if (/WebKit/.test(navigator.userAgent))
        continue;

      assert.equal(selection.anchorNode, div);
      assert.equal(selection.anchorOffset, 0);

      assert.equal(selection.focusNode, div);
      assert.equal(selection.focusOffset, i);
    }
  });

  test('addRange', function() {
    var selection = window.getSelection();
    var range = document.createRange();
    range.selectNode(b);
    selection.addRange(range);

    // Uncertain why this fails in Blink. The same test passes without the
    // shadow dom polyfill in Blink.
    if (/WebKit/.test(navigator.userAgent))
      return;

    assert.equal(selection.toString(), 'b');
  });

  test('removeRange', function() {
    // Not implemented in Blink.
    if (/WebKit/.test(navigator.userAgent))
      return;

    var selection = window.getSelection();
    selection.selectAllChildren(div);
    var range = selection.getRangeAt(0);
    selection.removeRange(range);
    assert.equal(selection.toString(), '');
  });

  test('containsNode', function() {
    // IE legacy document modes do not have containsNode.
    if (/Trident/.test(navigator.userAgent))
      return;

    var selection = window.getSelection();
    selection.selectAllChildren(div);

    assert.isFalse(selection.containsNode(div));
    assert.isFalse(selection.containsNode(document));
    assert.isFalse(selection.containsNode(document.body));

    assert.isTrue(selection.containsNode(a, true));
    assert.isTrue(selection.containsNode(b, true));
    assert.isTrue(selection.containsNode(c, true));
  });

});


text:
#ifndef DALI_INTERNAL_PROGRAM_CONTROLLER_H
#define DALI_INTERNAL_PROGRAM_CONTROLLER_H

// INTERNAL INCLUDES
#include <dali/devel-api/common/owner-container.h>
#include <dali/graphics-api/graphics-controller.h>
#include <dali/internal/common/shader-data.h>
#include <dali/internal/render/shaders/program-cache.h>
#include <dali/internal/render/shaders/program.h>

namespace Dali
{
namespace Internal
{
class ShaderSaver;

/**
 * This class is the owner of shader programs
 */
class ProgramController : public ProgramCache
{
public:
  /**
   * Wrapper for a program and its hash code
   */
  class ProgramPair
  {
  public: // API
    /**
     * Constructor
     * @param program
     * @param shaderHash
     */
    ProgramPair(Program* program, size_t shaderHash)
    : mProgram(program),
      mShaderHash(shaderHash)
    {
    }

    /**
     * Destructor, non-virtual as not a base
     */
    ~ProgramPair()
    {
      delete mProgram;
    }

    /**
     * Inline getter for the program
     * @return the program
     */
    inline Program* GetProgram()
    {
      return mProgram;
    }

    /**
     * Inline getter for the hash
     * @return the hash
     */
    [[nodiscard]] inline size_t GetHash() const
    {
      return mShaderHash;
    }

    ProgramPair(const ProgramPair&) = delete;
    ProgramPair& operator=(const ProgramPair&) = delete;

  private: // Data
    Program* mProgram;
    size_t   mShaderHash;
  };

  /**
   * Constructor
   * graphicsController The graphics backend controller
   */
  explicit ProgramController(Graphics::Controller& graphicsController);

  /**
   * Destructor, non virtual as not a base class
   */
  ~ProgramController() override;

  ProgramController(const ProgramController& rhs) = delete;
  ProgramController& operator=(const ProgramController& rhs) = delete;

public: // API
  /**
   * Resets the program matrices. Must be called at the beginning of every frame
   */
  void ResetProgramMatrices();

private: // From ProgramCache
  /**
   * @copydoc ProgramCache::GetProgram
   */
  Program* GetProgram(size_t shaderHash) override;

  /**
   * @copydoc ProgramCache::AddProgram
   */
  void AddProgram(size_t shaderHash, Program* program) override;

private: // Data
  Graphics::Controller& mGraphicsController;

  using ProgramContainer = OwnerContainer<ProgramPair*>;
  using ProgramIterator  = ProgramContainer::Iterator;
  ProgramContainer mProgramCache;
};

} // namespace Internal

} // namespace Dali

#endif // DALI_INTERNAL_PROGRAM_CONTROLLER_H


text:
using System;
using UnityEngine;
using AGXUnity.Utils;

namespace AGXUnity
{
  [AddComponentMenu( "" )]
  public class PickHandler : UniqueGameObject<PickHandler>
  {
    [HideInInspector]
    public static Color ReferenceSphereColor { get { return Color.HSVToRGB( 0.02f, 0.78f, 0.95f ); } }

    [HideInInspector]
    public static Color ConnectedSphereColor { get { return Color.HSVToRGB( 0.02f, 0.78f, 0.95f ); } }

    [HideInInspector]
    public static Color ConnectingCylinderColor { get { return Color.HSVToRGB( 0.02f, 0.78f, 0.95f ); } }

    public static float FindDistanceFromCamera( Camera camera, Vector3 worldPoint )
    {
      return camera.WorldToViewportPoint( worldPoint ).z;
    }

    public static void SetComplianceDamping( Constraint constraint )
    {
      if ( constraint == null )
        return;

      RigidBody rb1 = constraint.AttachmentPair.ReferenceObject.GetComponentInParent<RigidBody>();
      if ( rb1 == null )
        return;

      float mass    = rb1.MassProperties.Mass.Value;
      float distVal = Vector3.SqrMagnitude( constraint.AttachmentPair.ReferenceFrame.Position - constraint.AttachmentPair.ConnectedFrame.Position ) + 0.1f;
      distVal       = distVal > 1.5f ? distVal * distVal : distVal;

      float translationalCompliance = 1.0E-3f / ( distVal * Mathf.Max( mass, 1.0f ) );
      float rotationalCompliance    = 1.0E-10f / ( Mathf.Max( mass, 1.0f ) );
      float damping                 = 10.0f / 60.0f;

      var rowParser = ConstraintUtils.ConstraintRowParser.Create( constraint );
      if ( rowParser == null )
        return;

      foreach ( var translationalRow in rowParser.TranslationalRows ) {
        if ( translationalRow == null )
          continue;

        translationalRow.RowData.Compliance = translationalCompliance;
        translationalRow.RowData.Damping = damping;
      }

      foreach ( var rotationalRow in rowParser.RotationalRows ) {
        if ( rotationalRow == null )
          continue;

        rotationalRow.RowData.Compliance = rotationalCompliance;
        rotationalRow.RowData.Damping = damping;
      }
    }

    [Flags]
    public enum DofTypes
    {
      Translation = 1 << 0,
      Rotation    = 1 << 1
    }

    public enum MouseButton
    {
      None   = -1,
      Left   =  0,
      Right  =  1,
      Middle =  2
    }

    [SerializeField]
    private KeyCode m_triggerKey = KeyCode.A;
    public KeyCode TriggerKey { get { return m_triggerKey; } set { m_triggerKey = value; } }

    [SerializeField]
    private MouseButton m_ballJointMouseButton = MouseButton.Left;
    public MouseButton BallJointMouseButton
    {
      get { return m_ballJointMouseButton; }
      set
      {
        m_ballJointMouseButton = OnMouseButton( m_ballJointMouseButton, value );
      }
    }

    [SerializeField]
    private MouseButton m_lockJointMouseButton = MouseButton.Middle;
    public MouseButton LockJointMouseButton
    {
      get { return m_lockJointMouseButton; }
      set
      {
        m_lockJointMouseButton = OnMouseButton( m_lockJointMouseButton, value );
      }
    }

    [SerializeField]
    private MouseButton m_angularLockJointMouseButton = MouseButton.Right;
    public MouseButton AngularLockJointMouseButton
    {
      get { return m_angularLockJointMouseButton; }
      set
      {
        m_angularLockJointMouseButton = OnMouseButton( m_angularLockJointMouseButton, value );
      }
    }

    [SerializeField]
    private GameObject m_mainCamera = null;
    public GameObject MainCamera
    {
      get { return m_mainCamera; }
      set { m_mainCamera = value; }
    }

    public DofTypes MouseButtonToDofTypes( MouseButton button )
    {
      return button == BallJointMouseButton ?
               DofTypes.Translation :
             button == LockJointMouseButton ?
               DofTypes.Translation | DofTypes.Rotation :
             button == AngularLockJointMouseButton ?
               DofTypes.Rotation :
               DofTypes.Translation;
    }

    [HideInInspector]
    public GameObject ConstraintGameObject { get; private set; }

    [HideInInspector]
    public Constraint Constraint { get { return ConstraintGameObject != null ? ConstraintGameObject.GetComponent<Constraint>() : null; } }

    private class MouseButtonState
    {
      private bool[] m_isDown = new bool[ 3 ];
      private Action<MouseButton>[] m_buttonUpListeners = new Action<MouseButton>[ 3 ] { null, null, null };

      public MouseButton ButtonDown { get { return (MouseButton)Array.IndexOf( m_isDown, true ); } }

      public void Update( Event current, bool swallowEvent )
      {
        if ( !current.isMouse )
          return;

        if ( current.type != EventType.MouseDown && current.type != EventType.MouseUp )
          return;

        if ( current.type == EventType.MouseDown )
          m_isDown[ current.button ] = true;
        else {
          m_isDown[ current.button ] = false;
          if ( m_buttonUpListeners[ current.button ] != null )
            m_buttonUpListeners[ current.button ]( (MouseButton)current.button );
          m_buttonUpListeners[ current.button ] = null;
        }

        if ( swallowEvent )
          current.Use();
      }

      public void Use( MouseButton button, Action<MouseButton> onButtonUp )
      {
        m_buttonUpListeners[ (int)button ] = onButtonUp;
      }
    }

    private MouseButtonState m_mouseButtonState = new MouseButtonState();
    private float m_distanceFromCamera = -1f;
    private Camera m_camera = null;
    private agxCollide.Geometry m_lineGeometry = null;
    private agxCollide.Line m_lineShape = null;

    protected override void OnEnable()
    {
      Simulation.Instance.StepCallbacks.PreStepForward += OnPreStepForwardCallback;
      Simulation.Instance.StepCallbacks.SimulationPre  += OnSimulationPre;
      if ( MainCamera != null )
        m_camera = MainCamera.GetComponent<Camera>();

      m_lineShape = new agxCollide.Line( new agx.Vec3(), new agx.Vec3( 0, 0, 1 ) );
      m_lineGeometry = new agxCollide.Geometry( m_lineShape );
      m_lineGeometry.setEnable( false );
      m_lineGeometry.setSensor( true );
      GetSimulation().add( m_lineGeometry );
    }

    protected override void OnDisable()
    {
      if ( Simulation.HasInstance ) {
        Simulation.Instance.StepCallbacks.PreStepForward -= OnPreStepForwardCallback;
        Simulation.Instance.StepCallbacks.SimulationPre  -= OnSimulationPre;

        GetSimulation().remove( m_lineGeometry );
      }

      if ( ConstraintGameObject != null )
        Destroy( ConstraintGameObject );

      ConstraintGameObject = null;
      m_distanceFromCamera = -1f;
      m_camera             = null;
      m_lineShape          = null;
      m_lineGeometry       = null;
    }

    private void OnGUI()
    {
      m_mouseButtonState.Update( Event.current, Input.GetKey( TriggerKey ) );
    }

    private void OnSimulationPre()
    {
      if ( ConstraintGameObject == null && m_lineGeometry.isEnabled() ) {
        var geometryContacts = new agxCollide.GeometryContactPtrVector();
        var numContacts = GetSimulation().getSpace().getGeometryContacts( geometryContacts, m_lineGeometry );
        if ( numContacts > 0 ) {
          var ray = m_camera.ScreenPointToRay( Input.mousePosition );
          var rayHandedOrigin = ray.origin.ToHandedVec3();
          var closestGeometryContact = geometryContacts[ 0 ];
          var closestDistance2 = rayHandedOrigin.distance2( closestGeometryContact.points().at( 0 ).point );
          for ( int i = 1; i < geometryContacts.Count; ++i ) {
            var gc = geometryContacts[ i ];
            var distance2 = rayHandedOrigin.distance2( gc.points().at( 0 ).point );
            if ( distance2 < closestDistance2 ) {
              closestDistance2 = distance2;
              closestGeometryContact = gc;
            }
          }

          var raycastBody = closestGeometryContact.rigidBody( 0 );
          RigidBody body = null;
          if ( raycastBody != null && raycastBody.getMotionControl() == agx.RigidBody.MotionControl.DYNAMICS ) {
            var bodies = FindObjectsOfType<RigidBody>();
            for ( int i = 0; body == null && i < bodies.Length; ++i )
              if ( bodies[ i ].Native != null && bodies[ i ].Native.getUuid().str() == raycastBody.getUuid().str() )
                body = bodies[ i ];
          }

          ConstraintGameObject = TryCreateConstraint( closestGeometryContact.points().at( 0 ).point.ToHandedVector3(),
                                                      body,
                                                      MouseButtonToDofTypes( m_mouseButtonState.ButtonDown ),
                                                      "PickHandlerConstraint" );

          if ( ConstraintGameObject != null ) {
            ConstraintGameObject.AddComponent<Rendering.PickHandlerRenderer>();
            Constraint.DrawGizmosEnable = false;
            m_distanceFromCamera = FindDistanceFromCamera( m_camera,
                                                           Constraint.AttachmentPair.ReferenceFrame.Position );
          }

          m_lineGeometry.setEnable( false );
        }
      }
    }

    private void OnPreStepForwardCallback()
    {
      // Trigger key + mouse button down and we enable the line geometry
      // here - similar to preCollide. In pre-step event if the line
      // geometry is enabled, collect geometry contacts with our line
      // and create constraint with the closest point.

      if ( m_camera == null )
        return;

      if ( ConstraintGameObject == null && Input.GetKey( TriggerKey ) && m_mouseButtonState.ButtonDown != MouseButton.None ) {
        var ray = m_camera.ScreenPointToRay( Input.mousePosition );
        m_lineShape.set( ray.origin.ToHandedVec3(), ray.GetPoint( 5000.0f ).ToHandedVec3() );
        m_lineGeometry.setEnable( true );

        m_mouseButtonState.Use( m_mouseButtonState.ButtonDown, buttonUp =>
        {
          if ( ConstraintGameObject != null ) {
            DestroyImmediate( ConstraintGameObject );
            ConstraintGameObject = null;
            m_distanceFromCamera = -1f;
          }
          m_lineGeometry.setEnable( false );
        } );
      }

      if ( ConstraintGameObject != null ) {
        Constraint.AttachmentPair.ConnectedFrame.Position = m_camera.ScreenToWorldPoint( new Vector3( Input.mousePosition.x,
                                                                                Input.mousePosition.y,
                                                                                m_distanceFromCamera ) );

        SetComplianceDamping( Constraint );

        ConstraintGameObject.GetComponent<Rendering.PickHandlerRenderer>().ThisMethodIsntAllowedToBeNamedUpdateByUnity( Constraint, m_camera );
      }
    }

    private MouseButton OnMouseButton( MouseButton oldValue, MouseButton newValue )
    {
      if ( oldValue == newValue )
        return newValue;

      if ( newValue == m_ballJointMouseButton )
        m_ballJointMouseButton = oldValue;
      else if ( newValue == m_lockJointMouseButton )
        m_lockJointMouseButton = oldValue;
      else if ( newValue == m_angularLockJointMouseButton )
        m_angularLockJointMouseButton = oldValue;

      return newValue;
    }

    private GameObject TryCreateConstraint( Vector3 worldPoint, RigidBody rb, DofTypes constrainedDofs, string gameObjectName )
    {
      if ( rb == null )
        return null;

      var constraintType = constrainedDofs == DofTypes.Translation ?
                             ConstraintType.BallJoint :
                           constrainedDofs == DofTypes.Rotation ?
                             ConstraintType.AngularLockJoint :
                           ( constrainedDofs & DofTypes.Translation ) != 0 && ( constrainedDofs & DofTypes.Rotation ) != 0 ?
                             ConstraintType.LockJoint :
                             ConstraintType.BallJoint;

      var constraintGameObject = Factory.Create( constraintType );
      constraintGameObject.name = gameObjectName;

      var constraint = constraintGameObject.GetComponent<Constraint>();
      constraint.ConnectedFrameNativeSyncEnabled = true;
      constraint.AttachmentPair.ReferenceObject = rb.gameObject;
      constraint.AttachmentPair.ReferenceFrame.Position = worldPoint;

      constraint.AttachmentPair.ConnectedObject = null;
      constraint.AttachmentPair.ConnectedFrame.Position = worldPoint;

      constraint.AttachmentPair.Synchronized = false;

      return constraintGameObject;
    }
  }
}


text:
<!doctype html>

    <title>Sorry, that link is not valid.</title>

Sorry, the link you have followed is invalid or has expired.

Please request a new one.


text:
'use strict';

// MODULES //

var CTORS = require( './ctors.js' );

// TYPE NAME //

/**
* FUNCTION: typeName( error )
*	Returns the error type.
*
* @param {Error|TypeError|SyntaxError|URIError|ReferenceError|RangeError|RangeError|EvalError} error - input error
* @returns {String} error type
*/
function typeName( error ) {
	var i;
	for ( i = 0; i < CTORS.length; i++ ) {
		if ( error instanceof CTORS[ i ][ 0 ] ) {
			return CTORS[ i ][ 1 ];
		}
	}
} // end FUNCTION typeName()

// EXPORTS //

module.exports = typeName;


text:
#ifndef GGADGET_WIN32_TESTS_MAIN_LOOP_TEST_UTILITY_H_
#define GGADGET_WIN32_TESTS_MAIN_LOOP_TEST_UTILITY_H_

#include <windows.h>

#if !defined(DEBUG)
enum {
  kWaitTimeout = 5000,
};
#else
enum {
  kWaitTimeout = INFINITE,
};
#endif  // DEBUG

static const wchar_t kTestWatchCalledEvent[] =
    L"ggadget_win32_MainLoopWatchCalledEvent";
static const wchar_t kTestWatchRemovedEvent[] =
    L"ggadget_win32_MainLoopWatchRemovedEvent";
static const wchar_t kTestProcessQuitEvent[] =
    L"ggadget_win32_MainLoopProcessQuitEvent";

#endif  // GGADGET_WIN32_TESTS_MAIN_LOOP_TEST_UTILITY_H_


text:
require 'test_helper'
require 'logback_helper'

class Loggr::SLF4J::LoggerTest < MiniTest::Unit::TestCase
  def setup
    setup_logback!
    if_jruby do
      require 'loggr/slf4j/logger'
      @logger = Loggr::SLF4J::Logger.new('test')
    end
  end

  def test_setting_logger_name
    skip_unless_jruby
    assert_equal 'test', @logger.java_logger.getName()
    assert_equal 'test', Loggr::SLF4J::Logger.new(:test).java_logger.getName()
    assert_equal 'test/fancy::Logger', Loggr::SLF4J::Logger.new(:'test/fancy::Logger').java_logger.getName()
    assert_equal 'test.Logger', Loggr::SLF4J::Logger.new('test.Logger').java_logger.getName()
    assert_equal 'Loggr::SLF4J', Loggr::SLF4J::Logger.new('Loggr::SLF4J').java_logger.getName()
    assert_equal 'Loggr::SLF4J/basic', Loggr::SLF4J::Logger.new('Loggr::SLF4J/basic').java_logger.getName()
    assert_equal 'loggr.slf4j.LoggerTest', Loggr::SLF4J::Logger.new(self).java_logger.getName()
    assert_equal 'loggr.slf4j.LoggerTest', Loggr::SLF4J::Logger.new(self.class).java_logger.getName()
    assert_equal 'loggr.SLF4J', Loggr::SLF4J::Logger.new(Loggr::SLF4J).java_logger.getName()
  end

  def test_behaves_like_stdlib_logger
    skip_unless_jruby
    %w{debug info warn error fatal}.each do |level|
      assert_respond_to @logger, level
      assert_respond_to @logger, "#{level}?"
    end
  end

  def test_should_respond_to_close_and_flush
    skip_unless_jruby
    assert_respond_to @logger, :close
    assert_respond_to @logger, :flush
  end

  def test_trace_message
    skip_unless_jruby
    @logger.trace "a trace message"
    assert_log_event 5000, "a trace message", @appender.last
  end

  def test_debug_message
    skip_unless_jruby
    @logger.debug "a debug message"
    assert_log_event 10000, "a debug message", @appender.last
  end

  def test_info_message
    skip_unless_jruby
    @logger.info "an info message"
    assert_log_event 20000, "an info message", @appender.last
  end

  def test_warn_message
    skip_unless_jruby
    @logger.warn "a warn message"
    assert_log_event 30000, "a warn message", @appender.last
  end

  def test_error_message
    skip_unless_jruby
    @logger.error "an error message"
    assert_log_event 40000, "an error message", @appender.last
  end

  def test_fatal_message
    skip_unless_jruby
    @logger.fatal "a fatal message"
    assert_log_event 40000, "a fatal message", @appender.last
  end

  def test_logging_message_using_block
    skip_unless_jruby
    @logger.info { "block info message" }
    assert_log_event 20000, "block info message", @appender.last
  end

  def test_default_logger_has_no_marker
    skip_unless_jruby
    @logger.info "no marker"
    assert_equal nil, @appender.last.getMarker()
  end

  def test_use_progname_as_marker
    skip_unless_jruby
    @logger.info "with marker", "MARK"
    assert_equal "MARK", @appender.last.getMarker().to_s

    @logger.debug "other marker", "KRAM"
    assert_equal "KRAM", @appender.last.getMarker().to_s
  end

  def test_ability_to_provide_default_marker
    skip_unless_jruby
    @other = Loggr::SLF4J::Logger.new('test.marker', :marker => "MARK")

    @other.info "no marker"
    assert_equal "MARK", @appender.last.getMarker().to_s

    @other.debug "other marker", "KRAM"
    assert_equal "KRAM", @appender.last.getMarker().to_s
  end

  def test_level_should_be_unknown
    skip_unless_jruby
    assert_equal Loggr::SLF4J::Logger::UNKNOWN, @logger.level
  end

  def test_support_for_nested_tagged_calls
    skip_unless_jruby
    assert_nil @logger.java_mdc[:tags]
    @logger.tagged("demo") do
      assert_equal "demo", @logger.java_mdc[:tags]
      @logger.tagged("action", "test") do
        assert_equal "demo, action, test", @logger.java_mdc[:tags]
      end
      assert_equal "demo", @logger.java_mdc[:tags]
    end
    assert_nil @logger.java_mdc[:tags]
  end

  def test_that_tagged_also_accepts_array
    skip_unless_jruby
    @logger.tagged(%w{a b c}) do
      assert_equal "a, b, c", @logger.java_mdc[:tags]
    end
  end

  def test_support_for_nested_mapped_calls
    skip_unless_jruby
    @logger.mapped(:user => "demo") do
      assert_equal({ "user" => "demo" }, @logger.java_mdc.to_hash)
      @logger.mapped(:request_id => "123456", :auth => "secure") do
        assert_equal({ "user" => "demo", "request_id" => "123456", "auth" => "secure" }, @logger.java_mdc.to_hash)
        @logger.mapped(:user => "system") do
          assert_equal({ "user" => "system", "request_id" => "123456", "auth" => "secure" }, @logger.java_mdc.to_hash)
        end
        assert_equal({ "user" => "demo", "request_id" => "123456", "auth" => "secure" }, @logger.java_mdc.to_hash)
      end
      assert_equal({ "user" => "demo" }, @logger.java_mdc.to_hash)
    end
    assert_equal Hash.new, @logger.java_mdc.to_hash
  end

  def test_strip_leading_newlines
    skip_unless_jruby
    assert_equal "   some\nnewline\nmessage", @logger.send(:build_message, "   some\nnewline\nmessage")
    assert_equal "Started GET \"/service/foobar\" for 127.0.0.1 at Wed Feb 15 22:28:02 +0100 2012", @logger.send(:build_message, "\n\nStarted GET \"/service/foobar\" for 127.0.0.1 at Wed Feb 15 22:28:02 +0100 2012")
    assert_equal "NoMethodError (missing foobar):\n   backtrace1\n   backtrace2\n\n", @logger.send(:build_message, "\n\nNoMethodError (missing foobar):\n   backtrace1\n   backtrace2\n\n")
  end

  def test_java_logger
    skip_unless_jruby
    refute_nil @logger.java_logger
    assert_kind_of Java::OrgSlf4j::Logger, @logger.java_logger
  end

  def test_java_marker
    skip_unless_jruby
    assert_nil @logger.java_marker

    @other = Loggr::SLF4J::Logger.new('test.marker', :marker => 'APP')
    refute_nil @other.java_marker
    assert_kind_of Java::OrgSlf4j::Marker, @other.java_marker
  end

  def test_internal_marker_factory
    skip_unless_jruby
    assert_nil Loggr::SLF4J::MarkerFactory[nil]
    assert_nil Loggr::SLF4J::MarkerFactory[' ']
    assert_nil Loggr::SLF4J::MarkerFactory[""]

    @marker = Loggr::SLF4J::MarkerFactory["MARK"]
    refute_nil @marker
    assert_kind_of Java::OrgSlf4j::Marker, @marker
    assert_same @marker, Loggr::SLF4J::MarkerFactory["MARK"]
  end
end