text:
BSLS_IDENT("$Id: $")

//@PURPOSE: Provide a value-semantic type encoding a message in an MD5 digest.
//
//@CLASSES:
//  bdlde::Md5: value-semantic type representing an MD5 digest
//
//@SEE_ALSO:
//
//@DESCRIPTION: This component implements a mechanism for computing, updating,
// and streaming an MD5 digest (a cryptographic hash comprised of 128 bits).
// This digest is a strong technique for determining whether or not a message
// was received without errors.  This implementation is based on the RFC 1321
// specification which can be found at:
//..
//  http://www.ietf.org/rfc/rfc1321.txt
//..
// Note that an MD5 digest does not aid in error correction.
//
///Performance
///-----------
// The performance of this component is slightly slower than the native
// 'openssl' implementation of MD5.  It is typically within 7% of the speed of
// the native 'openssl' implementation with an error margin of +/-2%, depending
// on machine load.  A million iterations of the 'update' method will typically
// take between 0.84s to 0.90s on Sun and 0.68s to 0.69s on IBM.  A million
// iterations of the equivalent function in 'openssl', 'MD5_Update', will
// typically take between 0.80s to 0.85s on Sun and 0.65s to 0.67s on IBM.
//
///Usage
///-----
// The following snippets of code illustrate a typical use of the 'bdlde::Md5'
// class.  Each function would typically execute in separate processes or
// potentially on separate machines.  The 'senderExample' function below
// demonstrates how a message sender can write a message and its MD5 digest
// to a 'bdex' output stream.  Note that 'Out' may be a 'typedef' of any class
// that implements the 'bslx::OutStream' protocol:
//..
//  void senderExample(Out& output)
//      // Write a message and its MD5 digest to the specified 'output'
//      // stream.
//  {
//      // Prepare a message.
//      bsl::string message = "This is a test message.";
//
//      // Generate a digest for 'message'.
//      bdlde::Md5 digest(message.data(), message.length());
//
//      // Write the message to 'output'.
//      output << message;
//
//      // Write the digest to 'output'.
//      const int VERSION = 1;
//      digest.bdexStreamOut(output, VERSION);
//  }
//..
// The 'receiverExample' function below illustrates how a message receiver can
// read a message and its MD5 digest from a 'bdex' input stream, then perform a
// local MD5 computation to verify that the message was received intact.  Note
// that 'In' may be a 'typedef' of any class that implements the
// 'bslx::InStream' protocol:
//..
//  void receiverExample(In& input)
//      // Read a message and its MD5 digest from the specified 'input' stream,
//      // and verify the integrity of the message.
//  {
//      // Read the message from 'input'.
//      bsl::string message;
//      input >> message;
//
//      // Read the digest from 'input'.
//      bdlde::Md5 digest;
//      const int VERSION = 1;
//      digest.bdexStreamIn(input, VERSION);
//
//      // Locally compute the digest of the received 'message'.
//      bdlde::Md5 digestLocal;
//      digestLocal.update(message.data(), message.length());
//
//      // Verify that the received and locally-computed digests match.
//      assert(digestLocal == digest);
//  }
//..
//
///Additional Copyright Notice
///---------------------------
// The implementation of this component is *substantially* derived from the RSA
// Data Security, Inc. MD5 Message-Digest Algorithm that was published in the
// aforementioned RFC 1321.

#ifndef INCLUDED_BDLSCM_VERSION
#include <bdlscm_version.h>
#endif

#ifndef INCLUDED_BSLS_ALIGNEDBUFFER
#include <bsls_alignedbuffer.h>
#endif

#ifndef INCLUDED_BSLS_TYPES
#include <bsls_types.h>
#endif

#ifndef INCLUDED_BSL_CSTRING
#include <bsl_cstring.h>
#endif

#ifndef INCLUDED_BSL_IOSFWD
#include <bsl_iosfwd.h>
#endif

namespace BloombergLP {
namespace bdlde {

                                 // =========
                                 // class Md5
                                 // =========

class Md5 {
    // This 'class' represents an MD5 digest that can be updated as additional
    // data is provided.
    //
    // More generally, this class supports a complete set of *value*
    // *semantic* operations, including copy construction, assignment,
    // equality comparison, 'ostream' printing, and 'bdex' serialization.
    // (A precise operational definition of when two instances have the same
    // value can be found in the description of 'operator==' for the class.)
    // This container is *exception* *neutral* with no guarantee of rollback:
    // if an exception is thrown during the invocation of a method on a
    // pre-existing instance, the class is left in a valid state, but its
    // value is undefined.  In no event is memory leaked.  Finally, *aliasing*
    // (e.g., using all or part of an object as both source and destination)
    // is supported in all cases.

    // DATA
    unsigned int       d_state[4];    // state array storing the digest

    bsls::Types::Int64 d_length;      // length of the message

    unsigned char      d_buffer[64];  // buffer for storing remaining part of
                                      // message that is not yet incorporated
                                      // into 'd_state'

    // FRIENDS
    friend bool operator==(const Md5&, const Md5&);

  public:
    // TYPES
    typedef bsls::AlignedBuffer<16> Md5Digest;
        // A maximally-aligned, 16-byte object type used to represent an MD5
        // digest.

    // CLASS METHODS
    static int maxSupportedBdexVersion(int);
        // Return the maximum valid BDEX format version, as indicated by the
        // specified 'versionSelector', to be passed to the 'bdexStreamOut'
        // method.  Note that the 'versionSelector' is expected to be formatted
        // as 'yyyymmdd', a date representation.  See the 'bslx' package-level
        // documentation for more information on BDEX streaming of
        // value-semantic types and containers.

    // CREATORS
    Md5();
        // Construct an MD5 digest having the value corresponding to no data
        // having been provided.

    Md5(const void *data, int length);
        // Construct an MD5 digest corresponding to the specified 'data' having
        // the specified 'length' (in bytes).  The behavior is undefined unless
        // '0 <= length'.  Note that if 'data' is 0, then 'length' also must
        // be 0.

    Md5(const Md5& original);
        // Construct an MD5 digest having the value of the specified 'original'
        // digest.

    ~Md5();
        // Destroy this MD5 digest.

    // MANIPULATORS
    // !Md5& operator=(const Md5& rhs);
        // Assign to this MD5 digest the value of the specified 'rhs' MD5
        // digest and return a reference to this modifiable MD5 digest.  Note
        // that this method's definition is compiler generated.

    template <class STREAM>
    STREAM& bdexStreamIn(STREAM& stream, int version);
        // Assign to this object the value read from the specified input
        // 'stream' using the specified 'version' format and return a reference
        // to the modifiable 'stream'.  If 'stream' is initially invalid, this
        // operation has no effect.  If 'stream' becomes invalid during this
        // operation, this object is valid, but its value is undefined.  If the
        // specified 'version' is not supported, 'stream' is marked invalid,
        // but this object is unaltered.  Note that no version is read from
        // 'stream'.  (See the package-group-level documentation for more
        // information on 'bdex' streaming of container types.)

    void reset();
        // Reset the value of this MD5 digest to the value provided by the
        // default constructor.

    void update(const void *data, int length);
        // Update the value of this MD5 digest to incorporate the specified
        // 'data' having the specified 'length' in bytes.  If the current state
        // is the default state, the resultant value of this MD5 digest is the
        // application of the MD5 algorithm upon the currently given 'data' of
        // the given 'length'.  If this digest has been previously provided
        // data and has not been subsequently reset, the current state is not
        // the default state and the resultant value is equivalent to applying
        // the MD5 algorithm upon the concatenation of all the provided data.
        // The behavior is undefined unless '0 <= length'.  Note that if 'data'
        // is 0, then 'length' also must be 0.

    void loadDigestAndReset(Md5Digest *result);
        // Load the current value of this MD5 digest into the specified
        // 'result' and set the value of this MD5 digest to the value provided
        // by the default constructor.

    // ACCESSORS
    template <class STREAM>
    STREAM& bdexStreamOut(STREAM& stream, int version) const;
        // Write this value to the specified output 'stream' and return a
        // reference to the modifiable 'stream'.  Optionally specify an
        // explicit 'version' format; by default, the maximum supported version
        // is written to 'stream' and used as the format.  If 'version' is
        // specified, that format is used, but *not* written to 'stream'.  If
        // 'version' is not supported, 'stream' is left unmodified.  (See the
        // package-group-level documentation for more information on 'bdex'
        // streaming of container types).

    bsl::ostream& print(bsl::ostream& stream) const;
        // Format the current value of this MD5 digest to the specified output
        // 'stream' and return a reference to the modifiable 'stream'.

    void loadDigest(Md5Digest *result) const;
        // Load the current value of this MD5 digest into the specified
        // 'result'.

#ifndef BDE_OMIT_DEPRECATED
    // CLASS METHODS
    static int maxSupportedBdexVersion();
        // Return the most current 'bdex' streaming version number supported by
        // this class.  (See the package-group-level documentation for more
        // information on 'bdex' streaming of container types.)
#endif
};

// FREE OPERATORS
bool operator==(const Md5& lhs, const Md5& rhs);
    // Return 'true' if the specified 'lhs' and 'rhs' MD5 digests have the same
    // value, and 'false' otherwise.  Two digests have the same value if the
    // values obtained from their respective 'loadDigest' methods are
    // identical.

inline
bool operator!=(const Md5& lhs, const Md5& rhs);
    // Return 'true' if the specified 'lhs' and 'rhs' MD5 digests do not have
    // the same value, and 'false' otherwise.  Two digests do not have the same
    // value if the values obtained from their respective 'loadDigest' methods
    // differ.

inline
bsl::ostream& operator<<(bsl::ostream& stream, const Md5& digest);
    // Write to the specified output 'stream' the specified MD5 'digest' and
    // return a reference to the modifiable 'stream'.

// ============================================================================
//                        INLINE FUNCTION DEFINITIONS
// ============================================================================

                                 // ---------
                                 // class Md5
                                 // ---------

// CLASS METHODS
inline
int Md5::maxSupportedBdexVersion(int)
{
    return 1;
}

// MANIPULATORS
template <class STREAM>
STREAM& Md5::bdexStreamIn(STREAM& stream, int version)
{
    switch (version) {
      case 1: {
        unsigned int       state[4];
        unsigned char      buf[64];
        bsls::Types::Int64 length;

        // first the state

        for (int i = 0; i < 4; i++) {
            stream.getUint32(state[i]);
        }

        // then the length

        stream.getInt64(length);

        // finally the buffer

        for (int i = 0; i < 64; i++) {
            stream.getUint8(buf[i]);
        }

        if (!stream) {
            return stream;                                            // RETURN
        }

        d_length = length;
        bsl::memcpy(d_state, state, sizeof state);
        bsl::memcpy(d_buffer, buf, sizeof buf);

      } break;
      default: {
        stream.invalidate();
      } break;
    }
    return stream;
}

// ACCESSORS
template <class STREAM>
STREAM& Md5::bdexStreamOut(STREAM& stream, int version) const
{
    if (stream) {
        switch (version) {
          case 1: {
            // first the state

            for (int i = 0; i < 4; ++i) {
                stream.putUint32(d_state[i]);
            }

            // then the length

            stream.putInt64(d_length);

            // finally the buffer

            for (int i = 0; i < 64; ++i) {
                stream.putUint8(d_buffer[i]);
            }

          } break;
          default: {
            stream.invalidate();
          } break;
        }
    }
    return stream;
}

// FREE OPERATORS
inline
bool operator!=(const Md5& lhs, const Md5& rhs)
{
    return !(lhs == rhs);
}

inline
bsl::ostream& operator<<(bsl::ostream& stream, const Md5& digest)
{
    return digest.print(stream);
}

#ifndef BDE_OMIT_DEPRECATED

// ACCESSORS
inline
int Md5::maxSupportedBdexVersion()
{
    return maxSupportedBdexVersion(0);
}

#endif

}  // close package namespace
}  // close enterprise namespace

#endif

// ----------------------------------------------------------------------------
// Copyright 2015 Bloomberg Finance L.P.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------- END-OF-FILE ----------------------------------


text:
<ion-content>
    <ion-refresher [enabled]="loaded" (ionRefresh)="refreshData($event)">
        <ion-refresher-content pullingText="{{ 'core.pulltorefresh' | translate }}"></ion-refresher-content>
    </ion-refresher>

    <core-search-box (onSubmit)="search($event)" (onClear)="clearSearch($event)" [placeholder]=" 'addon.messages.contactname' | translate" autocorrect="off" spellcheck="false" lengthCheck="2" [disabled]="!loaded"></core-search-box>

    <core-loading [hideUntil]="loaded" [message]="loadingMessage">
        <core-empty-box *ngIf="!hasContacts && searchString == ''" icon="person" [message]="'addon.messages.contactlistempty' | translate"></core-empty-box>

        <core-empty-box *ngIf="!hasContacts && searchString != ''" icon="person" [message]="'addon.messages.nousersfound' | translate"></core-empty-box>

        <ion-list *ngFor="let contactType of contactTypes" no-margin>
            <ng-container *ngIf="contacts[contactType] && (contacts[contactType].length > 0 || contactType === searchType)">
                <ion-item-divider color="light">

{{ 'addon.messages.type_' + contactType | translate }}

                    <ion-note item-end>{{ contacts[contactType].length }}</ion-note>
                </ion-item-divider>
                <ng-container *ngFor="let contact of contacts[contactType]">

                        <ion-avatar item-start>

                        </ion-avatar>

<core-format-text [text]="contact.fullname"></core-format-text>

                </ng-container>
            </ng-container>
        </ion-list>
    </core-loading>
</ion-content>

redpajama_set_name: RedPajamaGithub


text:
#import "APCCustomBackButton.h"

static  const  CGFloat  kButtonWidth     = 30.0;
static  const  CGFloat  kButtonHeight    = 44.0;
static  const  CGFloat  kLayerWidth      = 30.0;
static  const  CGFloat  kLayerHeight     = 44.0;

static  const  CGFloat  kArrowLineWeight =  2.0;

@interface APCCustomBackButton ()
@property (nonatomic, weak) UIViewController* owner;
@end

@implementation APCCustomBackButton

+ (APCCustomBackButton *)customBackButtonWithTarget:(id)aTarget action:(SEL)anAction tintColor:(UIColor *)aTintColor
{
    APCCustomBackButton  *button = [APCCustomBackButton buttonWithType:UIButtonTypeCustom];
    CGRect  frame = CGRectMake(0.0, 0.0, kButtonWidth, kButtonHeight);
    button.frame = frame;

    if (aTarget != nil)
    {
        [button addTarget:aTarget action:anAction forControlEvents:UIControlEventTouchUpInside];
    }
    else{
        [button addTarget:button action:@selector(defaultBack) forControlEvents:UIControlEventTouchUpInside];
    }

    CGMutablePathRef  path = CGPathCreateMutable();

    CGPoint  p0 = CGPointMake(13.0, 12.0);
    CGPathMoveToPoint(path, NULL, p0.x, p0.y);

    CGPoint  p1 = CGPointMake(2.0, 22.0);
    CGPathAddLineToPoint(path, NULL, p1.x, p1.y);

    CGPoint  p2 = CGPointMake(13.0, 32.0);
    CGPathAddLineToPoint(path, NULL, p2.x, p2.y);

    CALayer  *layer = button.layer;
    CAShapeLayer  *shaper = [[CAShapeLayer alloc] init];
    shaper.frame = CGRectMake(0.0, 0.0, kLayerWidth, kLayerHeight);
    shaper.bounds = CGRectMake(0.0, 0.0, kLayerWidth, kLayerHeight);
    shaper.path = path;
    shaper.lineWidth = kArrowLineWeight;
    shaper.fillColor = [[UIColor clearColor] CGColor];
    shaper.contentsScale = [[UIScreen mainScreen] scale];
    shaper.strokeColor = aTintColor.CGColor;
    [layer addSublayer:shaper];

    CGPathRelease(path);

    return  button;
}

- (void)defaultBack
{
    [self.owner.navigationController popViewControllerAnimated:YES];
}

+ (UIBarButtonItem *)customBackBarButtonItemWithTarget:(id)aTarget action:(SEL)anAction tintColor:(UIColor *)aTintColor
{
    APCCustomBackButton  *button = [self customBackButtonWithTarget:aTarget action:anAction tintColor:aTintColor];
    UIBarButtonItem  *barButton = [[UIBarButtonItem alloc] initWithCustomView:button];
    return  barButton;
}

+ (UIBarButtonItem *)customBackBarButtonItemWithVc:(__weak UIViewController*)vc
                                         tintColor:(UIColor *)aTintColor
{
    APCCustomBackButton *button = [self customBackButtonWithTarget:nil action:nil tintColor:aTintColor];
    button.owner = vc;
    UIBarButtonItem  *barButton = [[UIBarButtonItem alloc] initWithCustomView:button];
    return  barButton;
}

@end


text:
CHANGELOG
#########

0.2.0
=====

- Now used Gulp (minified CSS and JS).
- Now used Bower (assets libs directory).
- Comments table in administration with labels.
- Filters in admin.
- Actions in admin.
- Now Akismet reports false negatives.
- Simplified comment moderation: buttons 'spam', 'hidden' and 'publish'. Soft delete button.
- Change display comments.
- Comment viewing changed (removed comment, edited comment...).


text:
package cache // import "bosun.org/cmd/bosun/cache"

import (
	"sync"

	"bosun.org/_third_party/github.com/golang/groupcache/lru"
	"bosun.org/_third_party/github.com/golang/groupcache/singleflight"
)

type Cache struct {
	g singleflight.Group

	sync.Mutex
	lru *lru.Cache
}

func New(MaxEntries int) *Cache {
	return &Cache{
		lru: lru.New(MaxEntries),
	}
}

func (c *Cache) Get(key string, getFn func() (interface{}, error)) (interface{}, error) {
	if c == nil {
		return getFn()
	}
	c.Lock()
	result, ok := c.lru.Get(key)
	c.Unlock()
	if ok {
		return result, nil
	}
	// our lock only serves to protect the lru.
	// we can (and should!) do singleflight requests concurently
	return c.g.Do(key, func() (interface{}, error) {
		v, err := getFn()
		if err == nil {
			c.Lock()
			c.lru.Add(key, v)
			c.Unlock()
		}
		return v, err
	})
}


text:
/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  *
© Copyright (c) 2019 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 ---------------------------------------------------------*/
SD_HandleTypeDef hsd;

TIM_HandleTypeDef htim3;

UART_HandleTypeDef huart1;

SRAM_HandleTypeDef hsram1;

/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_USART1_UART_Init(void);
static void MX_FSMC_Init(void);
static void MX_TIM3_Init(void);
static void MX_SDIO_SD_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_USART1_UART_Init();
  MX_FSMC_Init();
  MX_TIM3_Init();
  MX_SDIO_SD_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_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9;
  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 SDIO Initialization Function
  * @param None
  * @retval None
  */
static void MX_SDIO_SD_Init(void)
{

  /* USER CODE BEGIN SDIO_Init 0 */

  /* USER CODE END SDIO_Init 0 */

  /* USER CODE BEGIN SDIO_Init 1 */

  /* USER CODE END SDIO_Init 1 */
  hsd.Instance = SDIO;
  hsd.Init.ClockEdge = SDIO_CLOCK_EDGE_RISING;
  hsd.Init.ClockBypass = SDIO_CLOCK_BYPASS_DISABLE;
  hsd.Init.ClockPowerSave = SDIO_CLOCK_POWER_SAVE_DISABLE;
  hsd.Init.BusWide = SDIO_BUS_WIDE_1B;
  hsd.Init.HardwareFlowControl = SDIO_HARDWARE_FLOW_CONTROL_DISABLE;
  hsd.Init.ClockDiv = 0;
  if (HAL_SD_Init(&hsd) != HAL_OK)
  {
    Error_Handler();
  }
  if (HAL_SD_ConfigWideBusOperation(&hsd, SDIO_BUS_WIDE_4B) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN SDIO_Init 2 */

  /* USER CODE END SDIO_Init 2 */

}

/**
  * @brief TIM3 Initialization Function
  * @param None
  * @retval None
  */
static void MX_TIM3_Init(void)
{

  /* USER CODE BEGIN TIM3_Init 0 */

  /* USER CODE END TIM3_Init 0 */

  TIM_Encoder_InitTypeDef sConfig = {0};
  TIM_MasterConfigTypeDef sMasterConfig = {0};

  /* USER CODE BEGIN TIM3_Init 1 */

  /* USER CODE END TIM3_Init 1 */
  htim3.Instance = TIM3;
  htim3.Init.Prescaler = 0;
  htim3.Init.CounterMode = TIM_COUNTERMODE_UP;
  htim3.Init.Period = 0;
  htim3.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
  htim3.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
  sConfig.EncoderMode = TIM_ENCODERMODE_TI1;
  sConfig.IC1Polarity = TIM_ICPOLARITY_RISING;
  sConfig.IC1Selection = TIM_ICSELECTION_DIRECTTI;
  sConfig.IC1Prescaler = TIM_ICPSC_DIV1;
  sConfig.IC1Filter = 0;
  sConfig.IC2Polarity = TIM_ICPOLARITY_RISING;
  sConfig.IC2Selection = TIM_ICSELECTION_DIRECTTI;
  sConfig.IC2Prescaler = TIM_ICPSC_DIV1;
  sConfig.IC2Filter = 0;
  if (HAL_TIM_Encoder_Init(&htim3, &sConfig) != HAL_OK)
  {
    Error_Handler();
  }
  sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
  sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
  if (HAL_TIMEx_MasterConfigSynchronization(&htim3, &sMasterConfig) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN TIM3_Init 2 */

  /* USER CODE END TIM3_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 GPIO Initialization Function
  * @param None
  * @retval None
  */
static void MX_GPIO_Init(void)
{

  /* GPIO Ports Clock Enable */
  __HAL_RCC_GPIOC_CLK_ENABLE();
  __HAL_RCC_GPIOF_CLK_ENABLE();
  __HAL_RCC_GPIOG_CLK_ENABLE();
  __HAL_RCC_GPIOE_CLK_ENABLE();
  __HAL_RCC_GPIOD_CLK_ENABLE();
  __HAL_RCC_GPIOA_CLK_ENABLE();

}

/* FSMC initialization function */
static void MX_FSMC_Init(void)
{

  /* USER CODE BEGIN FSMC_Init 0 */

  /* USER CODE END FSMC_Init 0 */

  FSMC_NORSRAM_TimingTypeDef Timing = {0};

  /* USER CODE BEGIN FSMC_Init 1 */

  /* USER CODE END FSMC_Init 1 */

  /** Perform the SRAM1 memory initialization sequence
  */
  hsram1.Instance = FSMC_NORSRAM_DEVICE;
  hsram1.Extended = FSMC_NORSRAM_EXTENDED_DEVICE;
  /* hsram1.Init */
  hsram1.Init.NSBank = FSMC_NORSRAM_BANK3;
  hsram1.Init.DataAddressMux = FSMC_DATA_ADDRESS_MUX_DISABLE;
  hsram1.Init.MemoryType = FSMC_MEMORY_TYPE_SRAM;
  hsram1.Init.MemoryDataWidth = FSMC_NORSRAM_MEM_BUS_WIDTH_16;
  hsram1.Init.BurstAccessMode = FSMC_BURST_ACCESS_MODE_DISABLE;
  hsram1.Init.WaitSignalPolarity = FSMC_WAIT_SIGNAL_POLARITY_LOW;
  hsram1.Init.WrapMode = FSMC_WRAP_MODE_DISABLE;
  hsram1.Init.WaitSignalActive = FSMC_WAIT_TIMING_BEFORE_WS;
  hsram1.Init.WriteOperation = FSMC_WRITE_OPERATION_ENABLE;
  hsram1.Init.WaitSignal = FSMC_WAIT_SIGNAL_DISABLE;
  hsram1.Init.ExtendedMode = FSMC_EXTENDED_MODE_DISABLE;
  hsram1.Init.AsynchronousWait = FSMC_ASYNCHRONOUS_WAIT_DISABLE;
  hsram1.Init.WriteBurst = FSMC_WRITE_BURST_DISABLE;
  /* Timing */
  Timing.AddressSetupTime = 0;
  Timing.AddressHoldTime = 15;
  Timing.DataSetupTime = 3;
  Timing.BusTurnAroundDuration = 0;
  Timing.CLKDivision = 16;
  Timing.DataLatency = 17;
  Timing.AccessMode = FSMC_ACCESS_MODE_A;
  /* ExtTiming */

  if (HAL_SRAM_Init(&hsram1, &Timing, NULL) != HAL_OK)
  {
    Error_Handler( );
  }

  /** Disconnect NADV
  */

  __HAL_AFIO_FSMCNADV_DISCONNECTED();

  /* USER CODE BEGIN FSMC_Init 2 */

  /* USER CODE END FSMC_Init 2 */
}

/* 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****/


text:
package com.yuanyu.lightmessage;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import com.yuanyu.lightmessage.utils.AsciiBinaryTurn;
import com.yuanyu.lightmessage.utils.StrBinaryTurn;

import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;

public class ReceiveActivity extends Activity implements SensorEventListener {

	private static final int WHITE = 0;
	private static final int BLACK = 1;
	private static final int GRAY = 2;

	private SensorManager sensorManager;
	private Sensor lightSensor;

	private RelativeLayout background;
	private ProgressBar progress;

	private Map<Long, Float> valueList;
	private boolean isStart = false;
	private long startPosition = 0;
	private long endPosition = 0;

	private long lastValueTime = 0;
	private long currentValueTime = 0;

	private Map<Long, Float> testValues;
	private int startSymbol = 0; // 0 means not start, 1 means start to receive test message, 2 means start

	private float mMax = Float.MIN_VALUE;
	private float mMin = Float.MAX_VALUE;

	private Handler mHandler;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// No title and full screen
		getWindow().requestFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		setContentView(R.layout.activity_receive);

		background = (RelativeLayout)findViewById(R.id.receive_activity_background);
		background.setBackgroundColor(Color.BLACK);
		progress = (ProgressBar)findViewById(R.id.receive_activity_progress);

		valueList = new TreeMap<Long, Float>();
		testValues = new TreeMap<Long, Float>();

		sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
		lightSensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
		if(lightSensor == null || lightSensor.getMinDelay() > Constant.RECEIVE_FREQUENCY) {
			showNotCompatibleDialog();
		}

		mHandler = new Handler();
		mHandler.postDelayed(new Runnable(){
			@Override
			public void run() {
				if(startSymbol != 2) {
					showReceiveFailedDialog();
					progress.setVisibility(View.INVISIBLE);
					sensorManager.unregisterListener(ReceiveActivity.this);
				}
			}
		}, Constant.TEST_TIMEOUT);
	}

	@Override
	protected void onResume() {
		super.onResume();
		sensorManager.registerListener(this, lightSensor, Constant.RECEIVE_FREQUENCY);
	}

	@Override
	protected void onPause() {
		sensorManager.unregisterListener(this);
		mHandler.removeCallbacksAndMessages(null);
		super.onPause();
	}

	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {

	}

	@Override
	public void onSensorChanged(SensorEvent event) {
		float lux = event.values[0];
		Log.d("YY", "Light value " + lux);
		if(startSymbol == 2 && recognize(lux) == GRAY ) {
			return;
		}

		lastValueTime = currentValueTime;
		currentValueTime = event.timestamp / 1000000;

		long interval = currentValueTime - lastValueTime;
		if(interval > Constant.RECEIVE_FLAG_THRESHOLD && lastValueTime != 0) {
			startSymbol++;
			Log.d("YY", "start symbol " + startSymbol);
		}

		if(startSymbol < 2) { // Receive value as test messages
			testValues.put(currentValueTime, lux);
			if(lux > mMax) {
				mMax = lux;
			}
			if(lux < mMin) {
				mMin = lux;
			}
			return;
		}

		if(!isEnded(lux)){

			valueList.put(currentValueTime, lux);
			if(!isStart && startSymbol == 2) {
				isStart = true;
				analyseTestMessage();
				startPosition = currentValueTime;
			}
		}
		else {
			sensorManager.unregisterListener(this);
			Log.d("End", "Receive ended");
			analyze();
		}
	}

	private void analyseTestMessage() {
		int maxNumber = 0, minNumber = 0;
		for(Map.Entry<Long, Float> entry : testValues.entrySet()) {
			if(entry.getValue() == mMax) {
				maxNumber++;
			}
			if(entry.getValue() == mMin) {
				minNumber++;
			}
		}
		if(maxNumber != 4 || minNumber != 4) {
			showReceiveFailedDialog();
			progress.setVisibility(View.INVISIBLE);
			sensorManager.unregisterListener(this);
			mHandler.removeCallbacksAndMessages(null);
		}
	}

	private int recognize(float value) {
		if(value == mMin) {
			Log.d("Message", "black");
			return BLACK;
		}
		if(value == mMax) {
			Log.d("Message", "white");
			return WHITE;
		}
		Log.d("Message", "gray");
		return GRAY;
	}

	private boolean isEnded(float value) {
		if(!isStart){
			return false;
		}

		if(currentValueTime - lastValueTime > Constant.RECEIVE_FLAG_THRESHOLD) {
			endPosition = lastValueTime;
			return true;
		}

		return false;
	}

	private long hasValueBeforeStart(Map<Long, Integer> map) { // return 0 is not, else return the first found key
		for(Map.Entry<Long, Integer> entry : map.entrySet()) {
			if(entry.getKey() < startPosition) {
				return entry.getKey();
			}
		}
		return 0;
	}

	private long hasValueAfterEnd(Map<Long, Integer> map) { // return 0 is not, else return the first found key
		for(Map.Entry<Long, Integer> entry : map.entrySet()) {
			if(entry.getKey() > endPosition) {
				return entry.getKey();
			}
		}
		return 0;
	}

	private void removeRedundant(Map<Long, Integer> map) {
		// Delete values before start
		long toRemove = hasValueBeforeStart(map);
		while(toRemove != 0) {
			map.remove(toRemove);
			toRemove = hasValueBeforeStart(map);
		}

		// Remove end flag value
		toRemove = hasValueAfterEnd(map);
		while(toRemove != 0) {
			map.remove(toRemove);
			toRemove = hasValueAfterEnd(map);
		}
	}

	private boolean decodeTimeDifference(long first, long second) {
		int difference = (int) (second - first);

		/*int min = Constant.INTERVAL_SHORT - Constant.DEVIATION;
		if(min < 0) {
			min = 0;
		}
		int max = Constant.INTERVAL_SHORT + Constant.DEVIATION;
		if(difference >= min && difference <= max) {
			return false;
		}*/

		// Maybe use this to make it more precise
		/*min = Constant.INTERVAL_LONG - Constant.DEVIATION;
		max = Constant.INTERVAL_LONG + Constant.DEVIATION;
		if(difference >= min && difference <= max) {
			return false;
		}*/

		int middleValue = (Constant.INTERVAL_LONG + Constant.INTERVAL_SHORT) / 2;
		if(difference < middleValue) {
			return false;
		}

		return true;
	}

	private void analyze() {

		Map<Long, Integer> map = new TreeMap<Long, Integer>(); // TODO, use just a sorted list
		// Recognize all data
		for(Map.Entry<Long, Float> entry : valueList.entrySet()) {
			map.put(entry.getKey(), recognize(entry.getValue()));
		}

		removeRedundant(map);

		// Decoding
		List<Boolean> list = new ArrayList<Boolean>();
		long lastKey = 0;
		for(Map.Entry<Long, Integer> entry : map.entrySet()) {
			if(lastKey == 0) {
				lastKey = entry.getKey();
				continue;
			}
			list.add(decodeTimeDifference(lastKey, entry.getKey()));
			lastKey = entry.getKey();
		}

		boolean[] array = new boolean[list.size()];
		for(int i = 0; i < list.size(); i++) {
			array[i] = list.get(i);
		}

		if(array.length == 0) {
			showReceiveFailedDialog();
			return;
		}

		boolean isUnicode = array[0];
		boolean[] newArray = new boolean[array.length - 1];
		for(int i = 0; i < array.length - 1; i++) {
			newArray[i] = array[i + 1];
		}

		if(array.length == 0) {
			this.setResult(MainActivity.RESULT_EMPTY_RESULT);
			finish();
		}

		String result = "";
		if(isUnicode) { // Unicode
			StrBinaryTurn turn = new StrBinaryTurn();
			result = turn.BoolToStr(newArray);
		}
		else { // Ascii
			AsciiBinaryTurn turn = new AsciiBinaryTurn();
			result = turn.boolToAscii(newArray);
		}

		Intent intent = new Intent();
		intent.putExtra("message", result);
		this.setResult(Activity.RESULT_OK, intent);
		finish();
	}

	private void showNotCompatibleDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(R.string.not_compatible_title)
			.setMessage(R.string.not_compatible_content)
			.setIcon(android.R.drawable.ic_dialog_alert)
			.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					finish();
				}
			})
			.show();
	}

	private void showReceiveFailedDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(R.string.receive_fail_title)
			.setMessage(R.string.receive_fail_content)
			.setIcon(android.R.drawable.ic_dialog_alert)
			.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					finish();
				}
			})
			.show();
	}
}


text:
'use strict';

var os        = require('os');
var fs        = require('fs');
var path      = require('path');
var async     = require('async');
var needle    = require('needle');
var unzip     = require('unzipper');
var mkdirp    = require('mkdirp');
var grunt     = require('grunt');
var normalize = require('normalize-path');

/* Fontello API parameters */
var getOptions = {
  follow: 10
};

/* Verify or build paths */
var processPath = function(options, dir, callback){

  fs.exists(dir, function(exists){

    if(!exists) {
      if(!options.force) {
        callback(dir + ' missing! use `force:true` to create');
      }
      else {
        // Force create path
        mkdirp(dir, function(err){
          if (err) {
            callback(err);
          }
          else {
            callback(null, dir + ' created!');
          }
        });
      }
    }
    else {
      callback(null, dir + ' verified!');
    }

  });

};

/* Get session */
var getSession = function(){

  var src = path.resolve(os.tmpdir(), 'grunt-fontello-session');

  // Make sure the session file exists, return `null` otherwise.
  if(!fs.existsSync(src))
    return null;

  // Read session from the session file.
  return fs.readFileSync(src, { encoding: 'utf-8' });

}

/* Set session */
var setSession = function(session){

  var dest = path.resolve(os.tmpdir(), 'grunt-fontello-session');

  // Write session to the session file since the Fontello
  // api dislikes custom members.
  fs.writeFileSync(dest, session);

}

/* Set relative font path */
var setFontPath = function(options, callback){

  var css2FontPath = options.cssFontPath || normalize(path.relative(options.styles, options.fonts));
  grunt.log.write('Processing font path...');

  try {
    fs.readdir(options.styles, function(err, files){

      for(var i in files) {
        if(!files.hasOwnProperty(i))
          continue;

        var filePath = path.join(options.styles, files[i]);

        if(fs.statSync(filePath).isDirectory())
          continue;

        var content = fs.readFileSync(filePath);
        fs.writeFileSync(filePath, content.toString().replace(/\.\.\/font/g, css2FontPath));
      }

    });

    grunt.log.debug('Font path is ' + css2FontPath);
    grunt.log.ok();
    callback(null, 'extract complete');
  } catch(err) {
    grunt.log.error(err);
    grunt.log.fail();
    callback(err);
  }

}

/*
* Display Deprecated Message(s)
* @callback: options
* */
var deprecated = function(options, callback){
  if(options.scss)
    grunt.log.warn('You\'re using the deprecated option "scss", please switch to "preprocessor" as soon as possible');

  callback(null, options);
};

/*
* Initial Checks
* @callback: options
* */
var init = function(options, callback){

  grunt.log.write('Verify paths...');
  var tests = [
    processPath.bind(null, options, options.fonts),
    processPath.bind(null, options, options.styles)
  ];

  async.parallel(options.styles ? tests : [tests[0]], function(err, results){

    if(err) {
      grunt.log.error(err);
      callback(err);
    }
    else {
      grunt.log.ok();
      results.forEach(function(result){
        grunt.log.debug(result);
      });
      callback(null, options);
    }

  });

};

/*
* Check Session
* URL: http://fontello.com
* GET: http://fontello.com/SESSIONID/get
* @callback: bool representing expiration of session
* */
var checkSession = function(options, callback){

  var expired = false;
  var session = getSession();

  grunt.log.write('Checking session...');
  if(session !== null) {
    needle.get(options.host + '/' + session + '/get', getOptions, function(err, response, body){

      if(response.statusCode === 500)
        expired = true;

      grunt.log.ok();
      callback(null, options, expired);

    });
  }
  else {
    callback(null, options, true);
  }

};

/*
* Create Session
* URL: http://fontello.com
* POST: config.json
* @callback: session id
* */
var createSession = function(options, expired, callback){

  var data = {
    config: {
      file: options.config,
      content_type: 'application/json'
    }
  };

  var session = getSession();

  if (session !== null && !expired) {
    callback(null, options, session);
  }
  else {
    grunt.log.write('Creating session...');
    needle.post( options.host, data, { multipart: true }, function(err, response, body){

       if (err) {
         grunt.log.error();
         callback(err);
       }
       else {
         grunt.log.ok();
         grunt.log.debug('sid: ' + body);

         // Store the new sid and continue
         setSession(body);
         callback(null, options, body);
       }

     });
  }

};

/*
* Download Archive
* URL: http://fontello.com
* GET: http://fontello.com/SESSIONID/get
* callback: fetch/download result
* */
var fetchStream = function(options, session, callback){

  // The Fontello api outputs an error message instead of a session id if the
  // config file contains unexpected data. Pass that error on.
  if(/Invalid/.test(session))
    throw new Error(session);

  var tempConfig = path.resolve(os.tmpdir(), 'config-tmp.json');
  var tempZip = path.resolve(os.tmpdir(), 'fontello-tmp.zip');

  grunt.log.write('Fetching archive...');
  needle.get(options.host + '/' + session + '/get', getOptions, function(err, response, body){

    if(err)
      throw err;

    if(response.statusCode == 404) {
      setSession(options, '');
      createSession(options, fetchStream);
    } else {
      fs.writeFileSync(tempZip, body);
      var readStream = fs.createReadStream(tempZip);

      /* Extract Files */
      if(options.fonts || options.styles) {
        return readStream.pipe(unzip.Parse())
          // TODO: fix inconsistent return point
          .on('entry', function(entry){
            var ext = path.extname(entry.path);
            var name = path.basename(entry.path);

            if(entry.type === 'File') {
              for(var rule of options.exclude) {
                if(rule === name || name.match(rule)) {
                  grunt.verbose.writeln('Ignored ', entry.path);
                  entry.autodrain();
                  return;
                }
              }

              switch(ext) {
                // Extract Fonts
                case '.woff':case '.svg': case '.ttf': case '.eot': case '.woff2':
                  var fontPath = path.join(options.fonts, path.basename(entry.path));
                  return entry.pipe(fs.createWriteStream(fontPath));
                // Extract CSS
                case '.css':
                  if (options.styles) {
                    var basename = path.basename(entry.path).replace('fontello', options.prefix);
                    var cssPath;
                    switch(options.preprocessor.toLowerCase()) {
                      case 'none':
                        if(options.scss === true) {
                          cssPath = path.join(options.styles, '_' + basename.replace(ext, '.scss'));
                        } else {
                          cssPath = path.join(options.styles, basename);
                        }
                        break;
                      case 'less':
                        cssPath = path.join(options.styles, basename.replace(ext, '.less'));
                        break;
                      case 'scss':
                        cssPath = path.join(options.styles, '_' + basename.replace(ext, '.scss'));
                        break;
                      default:
                        grunt.fail.warn('Unknown preprocessor "' + options.output + '"');
                        return;
                    }

                    return entry.pipe(fs.createWriteStream(cssPath));
                  }
                // Drain everything else
                default:
                  grunt.verbose.writeln('Ignored ', entry.path);
                  entry.autodrain();
              }
            }
          })
          .on('close', function(){
             fs.unlinkSync(tempZip);
             grunt.log.ok();
             callback(null, options);
          });
      }

      /* Extract full archive */
      return readStream.pipe(unzip.Extract({ path: options.zip }))
        .on('close', function(){
          grunt.log.ok();
          fs.unlinkSync(tempZip);
          callback(null, options);
      });
    }

  });

};

module.exports = {
  deprecated : deprecated,
  init       : init,
  check      : checkSession,
  post       : createSession,
  fetch      : fetchStream,
  fontPath   : setFontPath
};


text:
package org.cubeengine.i18n.plural.parser;

public class UnaryOperatorExpr extends Expr {
    private final UnaryOperator op;
    private final Expr value;

    public UnaryOperatorExpr(UnaryOperator op, Expr value) {
        this.op = op;
        this.value = value;
    }

    @Override
    public int eval(int n) {
        return op.apply(value.eval(n));
    }

    @Override
    public String toString() {
        return "(" + String.format(op.toString(), value) + ")";
    }
}


text:
package codingbat.string1;

//Given a string and an int n, return a string made of the first and last n chars from the string. The string length will be at least n.
//
//nTwice("Hello", 2) = "Helo"
//nTwice("Chocolate", 3) = "Choate"
//nTwice("Chocolate", 1) = "Ce"

public class NTwiceTest {

  public static void main(String[] args) {

    NTwiceTest test = new NTwiceTest();

    System.out.println(">" + test.nTwice("Hello", 2) + "<");
    System.out.println(">" + test.nTwice("Chocolate", 3) + "<");
    System.out.println(">" + test.nTwice("Chocolate", 1) + "<");
  }

  public String nTwice(String str, int n) {
    return str.substring(0, n) + str.substring(str.length() - n, str.length());
  }

}


text:
package cn.fireworkstudio.java.tool.mail.bean;

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

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.activation.URLDataSource;
import javax.mail.BodyPart;
import javax.mail.MessagingException;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class HtmlEmail extends MultiPartEmail {

    public static final int CID_LENGTH = 10;
    private static final String HTML_MESSAGE_START = "
";
    private static final String HTML_MESSAGE_END = "
";
    protected String text;
    protected String html;
    /**
     * @deprecated
     */
    protected List inlineImages;
    protected Map inlineEmbeds;

    public HtmlEmail() {
        this.inlineEmbeds = new HashMap();
    }

    public HtmlEmail setTextMsg(String aText)
            throws EmailException {
        if (EmailUtils.isEmpty(aText)) {
            throw new EmailException("Invalid message supplied");
        }
        this.text = aText;
        return this;
    }

    public HtmlEmail setHtmlMsg(String aHtml)
            throws EmailException {
        if (EmailUtils.isEmpty(aHtml)) {
            throw new EmailException("Invalid message supplied");
        }
        this.html = aHtml;
        return this;
    }

    public Email setMsg(String msg)
            throws EmailException {
        if (EmailUtils.isEmpty(msg)) {
            throw new EmailException("Invalid message supplied");
        }
        setTextMsg(msg);

        StringBuffer htmlMsgBuf = new StringBuffer(msg.length() + "
".length() + "
".length());

        htmlMsgBuf.append("
").append(msg).append("
");

        setHtmlMsg(htmlMsgBuf.toString());

        return this;
    }

    public String embed(String urlString, String name)
            throws EmailException {
        try {
            return embed(new URL(urlString), name);
        } catch (MalformedURLException e) {
            throw new EmailException("Invalid URL", e);
        }
    }

    public String embed(URL url, String name)
            throws EmailException {
        if (EmailUtils.isEmpty(name)) {
            throw new EmailException("name cannot be null or empty");
        }
        if (this.inlineEmbeds.containsKey(name)) {
            InlineImage ii = (InlineImage) this.inlineEmbeds.get(name);
            URLDataSource urlDataSource = (URLDataSource) ii.getDataSource();
            if (url.equals(urlDataSource.getURL())) {
                return ii.getCid();
            }
            throw new EmailException("embedded name '" + name + "' is already bound to URL " + urlDataSource.getURL() + "; existing names cannot be rebound");
        }
        InputStream is = null;
        try {
            is = url.openStream();

            return embed(new URLDataSource(url), name);
        } catch (IOException e) {
            throw new EmailException("Invalid URL", e);
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException localIOException2) {
            }
        }
    }

    public String embed(File file)
            throws EmailException {
        String cid = EmailUtils.randomAlphabetic(10).toLowerCase();
        return embed(file, cid);
    }

    public String embed(File file, String cid)
            throws EmailException {
        if (EmailUtils.isEmpty(file.getName())) {
            throw new EmailException("file name cannot be null or empty");
        }
        String filePath = null;
        try {
            filePath = file.getCanonicalPath();
        } catch (IOException ioe) {
            throw new EmailException("couldn't get canonical path for " + file.getName(), ioe);
        }
        if (this.inlineEmbeds.containsKey(file.getName())) {
            InlineImage ii = (InlineImage) this.inlineEmbeds.get(file.getName());
            FileDataSource fileDataSource = (FileDataSource) ii.getDataSource();

            String existingFilePath = null;
            try {
                existingFilePath = fileDataSource.getFile().getCanonicalPath();
            } catch (IOException ioe) {
                throw new EmailException("couldn't get canonical path for file " + fileDataSource.getFile().getName() + "which has already been embedded", ioe);
            }
            if (filePath.equals(existingFilePath)) {
                return ii.getCid();
            }
            throw new EmailException("embedded name '" + file.getName() + "' is already bound to file " + existingFilePath + "; existing names cannot be rebound");
        }
        if (!file.exists()) {
            throw new EmailException("file " + filePath + " doesn't exist");
        }
        if (!file.isFile()) {
            throw new EmailException("file " + filePath + " isn't a normal file");
        }
        if (!file.canRead()) {
            throw new EmailException("file " + filePath + " isn't readable");
        }
        return embed(new FileDataSource(file), file.getName());
    }

    public String embed(DataSource dataSource, String name)
            throws EmailException {
        if (this.inlineEmbeds.containsKey(name)) {
            InlineImage ii = (InlineImage) this.inlineEmbeds.get(name);
            if (dataSource.equals(ii.getDataSource())) {
                return ii.getCid();
            }
            throw new EmailException("embedded DataSource '" + name + "' is already bound to name " + ii.getDataSource().toString() + "; existing names cannot be rebound");
        }
        String cid = EmailUtils.randomAlphabetic(10).toLowerCase();
        return embed(dataSource, name, cid);
    }

    public String embed(DataSource dataSource, String name, String cid)
            throws EmailException {
        if (EmailUtils.isEmpty(name)) {
            throw new EmailException("name cannot be null or empty");
        }
        MimeBodyPart mbp = new MimeBodyPart();
        try {
            mbp.setDataHandler(new DataHandler(dataSource));
            mbp.setFileName(name);
            mbp.setDisposition("inline");
            mbp.setContentID("<" + cid + ">");

            InlineImage ii = new InlineImage(cid, dataSource, mbp);
            this.inlineEmbeds.put(name, ii);

            return cid;
        } catch (MessagingException me) {
            throw new EmailException(me);
        }
    }

    public void buildMimeMessage()
            throws EmailException {
        try {
            build();
        } catch (MessagingException me) {
            throw new EmailException(me);
        }
        super.buildMimeMessage();
    }

    private static final Logger logger = LogManager.getLogger(HtmlEmail.class);

    private void build()
            throws MessagingException, EmailException {
        MimeMultipart container = getContainer();
        MimeMultipart subContainer = null;
        BodyPart msgHtml = null;
        BodyPart msgText = null;

        container.setSubType("related");
        subContainer = new MimeMultipart("alternative");
        if (EmailUtils.isNotEmpty(this.text)) {
            msgText = new MimeBodyPart();
            if (this.inlineEmbeds.size() > 0) {
                subContainer.addBodyPart(msgText);
            } else {
                container.addBodyPart(msgText);
            }
            if (EmailUtils.isNotEmpty(this.charset)) {
                msgText.setContent(this.text, "text/plain; charset=" + this.charset);
            } else {
                msgText.setContent(this.text, "text/plain");
            }
        }
        if (EmailUtils.isNotEmpty(this.html)) {
            msgHtml = new MimeBodyPart();
            if (this.inlineEmbeds.size() > 0) {
                subContainer.addBodyPart(msgHtml);
            } else {
                container.addBodyPart(msgHtml);
            }
            if (EmailUtils.isNotEmpty(this.charset)) {
                msgHtml.setContent(this.html, "text/html; charset=" + this.charset);
                logger.info("this.html---text/html; charset=" + this.charset);
            } else {
                msgHtml.setContent(this.html, "text/html");
                logger.info("this.html---text/html");
            }
            Iterator iter = this.inlineEmbeds.values().iterator();
            while (iter.hasNext()) {
                InlineImage ii = (InlineImage) iter.next();
                container.addBodyPart(ii.getMbp());
            }
        }
        if (this.inlineEmbeds.size() > 0) {
            addPart(subContainer, 0);
        }
    }

    private static class InlineImage {
        private String cid;
        private DataSource dataSource;
        private MimeBodyPart mbp;

        public InlineImage(String cid, DataSource dataSource, MimeBodyPart mbp) {
            this.cid = cid;
            this.dataSource = dataSource;
            this.mbp = mbp;
        }

        public String getCid() {
            return this.cid;
        }

        public DataSource getDataSource() {
            return this.dataSource;
        }

        public MimeBodyPart getMbp() {
            return this.mbp;
        }

        public boolean equals(Object obj) {
            if (this == obj) {
                return true;
            }
            if (!(obj instanceof InlineImage)) {
                return false;
            }
            InlineImage that = (InlineImage) obj;

            return this.cid.equals(that.cid);
        }

        public int hashCode() {
            return this.cid.hashCode();
        }
    }
}


text:
'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
        Team = mongoose.model('Team'),
        _ = require('lodash');

/**
 * Find team by id
 */
exports.team = function (req, res, next, id) {
    Team.load(id, function (err, team) {
        if (err)
            return next(err);
        if (!team)
            return next(new Error('Failed to load team ' + id));
        req.team = team;
        next();
    });
};

/**
 * Create a team
 */
exports.create = function (req, res) {
    var team = new Team(req.body);
    team.creator = req.user;

    team.save(function (err) {
        if (err) {
            return res.status(500).json({
                error: 'Cannot save the team'
            });
        }
        res.json(team);
    });
};

/**
 * Delete a team
 */
exports.destroy = function (req, res) {
    var team = req.team;

    team.remove(function (err) {
        if (err) {
            return res.status(500).json({
                error: 'Cannot delete the team'
            });
        }
        res.json(team);
    });
};

/**
 * Update a team
 */
exports.update = function (req, res) {
    var team = req.team;
    req.body.settings = (typeof req.body.settings === 'object' ? req.body.settings._id : req.body.settings);
    team = _.extend(team, req.body);

    team.save(function (err) {
        if (err) {
            return res.status(500).json({
                error: 'Cannot update the team'
            });
        }
        res.json(team);
    });
};

/**
 * Show a team
 */
exports.show = function (req, res) {
    res.json(req.team);
};

/**
 * List of Teams
 */
exports.get = function (req, res) {
    Team.find().sort('-created').exec(function (err, teams) {
        if (err) {
            return res.status(500).json({
                error: 'Cannot list the teams'
            });
        }
        res.json(teams);
    });
};


text:
using System;
using System.ComponentModel;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft.Win32;

namespace CanopyInterpreter {
    internal static class NativeMethods {
        [DllImport("kernel32", EntryPoint = "GetBinaryTypeW", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Winapi)]
        private static extern bool _GetBinaryType(string lpApplicationName, out GetBinaryTypeResult lpBinaryType);

        private enum GetBinaryTypeResult : uint {
            SCS_32BIT_BINARY = 0,
            SCS_DOS_BINARY = 1,
            SCS_WOW_BINARY = 2,
            SCS_PIF_BINARY = 3,
            SCS_POSIX_BINARY = 4,
            SCS_OS216_BINARY = 5,
            SCS_64BIT_BINARY = 6
        }

        public static ProcessorArchitecture GetBinaryType(string path) {
            GetBinaryTypeResult result;

            if (_GetBinaryType(path, out result)) {
                switch (result) {
                    case GetBinaryTypeResult.SCS_32BIT_BINARY:
                        return ProcessorArchitecture.X86;
                    case GetBinaryTypeResult.SCS_64BIT_BINARY:
                        return ProcessorArchitecture.Amd64;
                    case GetBinaryTypeResult.SCS_DOS_BINARY:
                    case GetBinaryTypeResult.SCS_WOW_BINARY:
                    case GetBinaryTypeResult.SCS_PIF_BINARY:
                    case GetBinaryTypeResult.SCS_POSIX_BINARY:
                    case GetBinaryTypeResult.SCS_OS216_BINARY:
                    default:
                        break;
                }
            }

            return ProcessorArchitecture.None;
        }

        public const int MAXIMUM_WAIT_OBJECTS = 64;

        [DllImport("advapi32", EntryPoint = "RegNotifyChangeKeyValue", CallingConvention = CallingConvention.Winapi)]
        private static extern int _RegNotifyChangeKeyValue(
            SafeHandle hKey,
            bool bWatchSubtree,
            RegNotifyChange dwNotifyFilter,
            SafeHandle hEvent,
            bool fAsynchronous
        );

        [Flags]
        public enum RegNotifyChange : uint {
            Name = 1,                   // REG_NOTIFY_CHANGE_NAME
            Attributes = 2,             // REG_NOTIFY_CHANGE_ATTRIBUTES
            Value = 4,                  // REG_NOTIFY_CHANGE_LAST_SET
            Security = 8,               // REG_NOTIFY_CHANGE_SECURITY
            ThreadAgnostic = 0x10000000 // REG_NOTIFY_THREAD_AGNOSTIC (Windows 8 only)
        }

        public static void RegNotifyChangeKeyValue(
            RegistryKey key,
            WaitHandle notifyEvent,
            bool recursive = false,
            RegNotifyChange filter = RegNotifyChange.Value
        ) {
            int error = _RegNotifyChangeKeyValue(
                key.Handle,
                recursive,
                filter,
                notifyEvent.SafeWaitHandle,
                true);

            if (error != 0) {
                throw new Win32Exception(error);
            }
        }
    }
}


text:
/** Automatically generated file. DO NOT MODIFY */
package com.coffeebaka.omoidasu.app;

public final class BuildConfig {
    public final static boolean DEBUG = true;
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<metadata>
  <groupId>com.github.haifengl</groupId>
  <artifactId>smile</artifactId>
  <versioning>
    <release>1.3.1</release>
    <versions>
      <version>1.3.1</version>
    </versions>
    <lastUpdated>20180726204639</lastUpdated>
  </versioning>
</metadata>


text:
This is an experimental script to support the use of pyradiomics with DICOM data.

The script will accept as input a directory with a single DICOM image study for the input image,
and the file name pointing to a DICOM Segmentation Image (DICOM SEG) object.

The script will transparently convert the DICOM image into a representation suitable by pyradiomics
using either plastimatch or dcm2niix.

# Why?

* medical image data usually comes in DICOM, and pyradiomics users often ask for help working with DICOM data
* there are public collections of data on TCIA where segmentations are stored as DICOM SEG
* the use of DICOM representation for radiomics features
 * introduces standardized formalism for the attributes that should be stored to accompany the features
 * allows to link results of calculations with the various ontologies describing the anatomy of the regions
  analyzed, and the features itself (e.g., the SR document produced by the script will utilize IBSI nomenclature
  to describe those features implemented in pyradiomics that have correspondence in IBSI)
 * allows to reference (by unique identifiers) the DICOM image series and DICOM segmentation used for feature
  calculation
 * enables harmonized representation of data for images, segmentations and features (i.e., same data management
  system can be used for all data types)
 * does not prevent the use of the results in software tools that are not DICOM-aware - dcmqi can be used to
  convert DICOM segmentations and DICOM SR with the measurements into non-DICOM representation (ITK-readable
  image formats for segmentations, and JSON for measurements); a separate tool is available to generate
  tab-delimited representation for DICOM attributes and measurements stored in those SRs: https://github.com/QIICR/dcm2tables

# Prerequisites

* [plastimatch](http://plastimatch.org/plastimatch.html) or [dcm2niix](https://github.com/rordenlab/dcm2niix) for image volume reconstruction
* dcmqi (build from https://github.com/QIICR/dcmqi/commit/3638930723bf1a239515409c1f9ec886a9fedb41 or later) for reading DICOM SEG and converting to a representation suitable by pyradiomics, and for storing the resulting features as a DICOM Structured Report, instantiating SR TID 1500
* prior to using this script, you might want to sort your DICOM data such that individual series
are stored in separate directories. You might find this tool useful for this purpose: https://github.com/pieper/dicomsort
* if you segmentations are not stored as DICOM SEG, you can use dcmqi for generating standard representation
of those segmentations: https://github.com/QIICR/dcmqi

# Usage

```bash
$ python pyradiomics-dcm.py -h                                                                              2.3.6
usage: pyradiomics-dcm.py --input-image <dir> --input-seg <name> --output-sr <name>

Warning: This is a "pyradiomics labs" script, which means it is an experimental feature in development!
The intent of this helper script is to enable pyradiomics feature extraction directly from/to DICOM data.
The segmentation defining the region of interest must be defined as a DICOM Segmentation image.
Support for DICOM Radiotherapy Structure Sets for defining region of interest may be added in the future.

optional arguments:
  -h, --help            show this help message and exit
  --input-image-dir <folder>
                        Path to the directory with the input DICOM series. It is expected that a single
                        series is corresponding to a single scalar volume.
  --input-seg-file <file>
                        Path to the input segmentation defined as a DICOM Segmentation object.
  --output-dir <folder>
                        Path to the directory for saving the resulting DICOM file.
  --parameters <parameters>
                        Pyradiomics feature extractor positional arguments
  --temp-dir <folder>   Path to the directory to store intermediate results
  --features-dict <file>
                        Path to the dictionary mapping pyradiomics feature names to the IBSI defined
                        features.
  --volume-reconstructor <plastimatch or dcm2niix>
                        Choose the tool to be used for reconstructing image volume from the DICOM image
                        series. Allowed options are plastimatch or dcm2niix (should be installed on the
                        system). plastimatch will be used by default.
  --geometry-tolerance <number>
                        Decimal number setting geometry tolerance for the extractor. Defaults to 1e-6.
  --correct-mask        Boolean flag argument. If present, PyRadiomics will attempt to resample the mask
                        to the image geometry if the mask check fails.
```

# Sample invocation

```bash
$ python pyradiomics-dcm.py --input-image-dir CT --input-seg SEG/1.dcm \
   --output-dir OutputSR --temp-dir TempDir --parameters Pyradiomics_Params.yaml
dcmqi repository URL: https://github.com/QIICR/dcmqi.git revision: 3638930 tag: latest-4-g3638930
Row direction: 1 0 0
Col direction: 0 1 0
Z direction: 0 0 1
Total frames: 177
Total frames with unique IPP: 177
Total overlapping frames: 0
Origin: [-227.475, -194.775, -1223]
dcmqi repository URL: https://github.com/QIICR/dcmqi.git revision: 3638930 tag: latest-4-g3638930
Total measurement groups: 1
Adding to compositeContext: 1.dcm
Composite Context initialized
SR saved!

$ dsrdump OutputSR/1.2.276.0.7230010.3.1.4.0.60427.1539113881.935517.dcm
Enhanced SR Document

Patient             : interobs05 (#interobs05)
ENH: include pyradiomics identification and version
Study               : interobs05_20170910_CT
Series              : GTV segmentation - Reader AB - pyradiomics features (#1)
Manufacturer        : QIICR (https://github.com/QIICR/dcmqi.git, #0)
Completion Flag     : PARTIAL
Verification Flag   : UNVERIFIED
Content Date/Time   : 2018-10-09 15:38:01

<CONTAINER:(,,"Imaging Measurement Report")=SEPARATE>
  <has concept mod CODE:(,,"Language of Content Item and Descendants")=(eng,RFC5646,"English")>
  <has obs context CODE:(,,"Observer Type")=(121007,DCM,"Device")>
  <has obs context UIDREF:(,,"Device Observer UID")="1.3.6.1.4.1.43046.3.1.4.0.60427.1539113880.935515">
  <has obs context TEXT:(,,"Device Observer Name")="pyradiomics">
  <has obs context TEXT:(,,"Device Observer Model Name")="2.1.0.post10.dev0+g51bc87f">
  <has concept mod CODE:(,,"Procedure reported")=(P0-0099A,SRT,"Imaging procedure")>
  <contains CONTAINER:(,,"Image Library")=SEPARATE>
    <contains CONTAINER:(,,"Image Library Group")=SEPARATE>
      <has acq context CODE:(,,"Modality")=(CT,DCM,"Computed Tomography")>
      <has acq context DATE:(,,"Study Date")="20170910">
      <has acq context UIDREF:(,,"Frame of Reference UID")="1.3.6.1.4.1.40744.29.28518703451127075549995420991770873582">

...

  <contains CONTAINER:(,,"Imaging Measurements")=SEPARATE>
    <contains CONTAINER:(,,"Measurement Group")=SEPARATE>
      <has obs context TEXT:(,,"Tracking Identifier")="Gross Target Volume">
      <has obs context UIDREF:(,,"Tracking Unique Identifier")="1.3.6.1.4.1.43046.3.1.4.0.60427.1539113881.935516"
>
      <contains CODE:(,,"Finding")=(C112913,NCIt,"Gross Target Volume")>
      <contains IMAGE:(,,"Referenced Segment")=(SG image,,1)>
      <contains UIDREF:(,,"Source series for segmentation")="1.3.6.1.4.1.40744.29.18397950185694012790332812250603
612437">
      <has concept mod CODE:(,,"Finding Site")=(T-28000,SRT,"Lung")>
      <contains NUM:(,,"shape_MeshVolume")="7.255467E+04" (1,UCUM,"no units")>
      <contains NUM:(,,"Maximum 3D diameter")="7.491328E+01" (1,UCUM,"no units")>
      <contains NUM:(,,"shape_Maximum2DDiameterSlice")="6.767570E+01" (1,UCUM,"no units")>
      <contains NUM:(,,"Elongation")="7.993260E-01" (1,UCUM,"no units")>
      <contains NUM:(,,"shape_MinorAxisLength")="4.699969E+01" (1,UCUM,"no units")>
      <contains NUM:(,,"Flatness")="6.517569E-01" (1,UCUM,"no units")>
      <contains NUM:(,,"shape_Maximum2DDiameterColumn")="6.746851E+01" (1,UCUM,"no units")>
      <contains NUM:(,,"Surface to volume ratio")="1.572168E-01" (1,UCUM,"no units")>
      <contains NUM:(,,"shape_Maximum2DDiameterRow")="6.072891E+01" (1,UCUM,"no units")>
      <contains NUM:(,,"shape_VoxelVolume")="7.285600E+04" (1,UCUM,"no units")>
      <contains NUM:(,,"Sphericity")="7.375024E-01" (1,UCUM,"no units")>
      <contains NUM:(,,"Surface area")="1.140681E+04" (1,UCUM,"no units")>
      <contains NUM:(,,"shape_MajorAxisLength")="5.879915E+01" (1,UCUM,"no units")>
      <contains NUM:(,,"shape_LeastAxisLength")="3.832275E+01" (1,UCUM,"no units")>
      <contains NUM:(,,"Small zone emphasis")="7.384502E-01" (1,UCUM,"no units")>
      <contains NUM:(,,"glszm_SmallAreaLowGrayLevelEmphasis")="3.381883E-03" (1,UCUM,"no units")>
      <contains NUM:(,,"Normalised grey level non-uniformity")="3.136554E-02" (1,UCUM,"no units")>
      <contains NUM:(,,"glszm_SmallAreaHighGrayLevelEmphasis")="5.478214E+02" (1,UCUM,"no units")>
      <contains NUM:(,,"Large zone emphasis")="3.873234E+03" (1,UCUM,"no units")>

...
```

# Questions?

* Andrey Fedorov andrey.fedorov@gmail.com

# References

* Herz C, Fillion-Robin J-C, Onken M, Riesmeier J, Lasso A, Pinter C, Fichtinger G, Pieper S, Clunie D, Kikinis R, Fedorov A. dcmqi: An Open Source Library for Standardized Communication of Quantitative Image Analysis Results Using DICOM. Cancer Research. 2017;77(21):e87–e90 http://cancerres.aacrjournals.org/content/77/21/e87
* Fedorov A, Clunie D, Ulrich E, Bauer C, Wahle A, Brown B, Onken M, Riesmeier J, Pieper S, Kikinis R, Buatti J, Beichel RR. (2016) DICOM for quantitative imaging biomarker development: a standards based approach to sharing clinical data and structured PET/CT analysis results in head and neck cancer research. PeerJ 4:e2057 https://doi.org/10.7717/peerj.2057


text:
package org.broadinstitute.dsde.firecloud.fixture

import org.broadinstitute.dsde.workbench.auth.AuthToken
import org.broadinstitute.dsde.workbench.config.{Credentials, UserPool}
import org.broadinstitute.dsde.workbench.fixture._
import org.broadinstitute.dsde.workbench.service.test.{RandomUtil, WebBrowserSpec}
import org.scalatest.{Matchers, Outcome, fixture}

import scala.util.Try

abstract class BillingFixtureSpec extends fixture.FreeSpec with BillingFixtures with Matchers
  with WebBrowserSpec with UserFixtures with WorkspaceFixtures with GroupFixtures with RandomUtil {

  val owner: Credentials = UserPool.chooseProjectOwner
  implicit val ownerAuthToken: AuthToken = owner.makeAuthToken()
  var claimedBillingProject: ClaimedProject = _

  /**
    * See
    *  https://www.artima.com/docs-scalatest-2.0.M5/org/scalatest/FreeSpec.html
    *   Section: "Overriding withFixture(OneArgTest)"
    *
    * Claim a billing project for project owner
    * @param billingProject
    */
  case class OwnerBillingProjectFixture(billingProject: String)

  type FixtureParam = OwnerBillingProjectFixture

  override def withFixture(test: OneArgTest): Outcome = {
    withFixture(test.toNoArgTest(OwnerBillingProjectFixture(claimedBillingProject.projectName)))
  }

  def claimBillingProject(): Unit = {
    Try {
      claimedBillingProject = claimGPAllocProject(owner)
      logger.info(s"Billing project claimed: ${claimedBillingProject.projectName}")
    }.recover {
      case ex: Exception =>
        logger.error(s"Error occurred in billing project claim as owner $owner", ex)
        throw ex
    }
  }

  def unclaimBillingProject(): Unit = {
    val projectName = claimedBillingProject.projectName
    Try {
      claimedBillingProject.cleanup(owner)
      logger.info(s"Billing project unclaimed: $projectName")
    }.recover{
      case ex: Exception =>
        logger.error(s"Error occurred in billing project clean $projectName as owner $owner", ex)
        throw ex
    }
  }

}


text:
<?php

namespace Chamilo\Core\Repository\ContentObject\ExternalTool\Display\Component;

use Chamilo\Core\Repository\ContentObject\ExternalTool\Display\Manager;
use Chamilo\Core\Repository\ContentObject\ExternalTool\Display\Service\LaunchGenerator;

/**
 * @package Chamilo\Core\Repository\ContentObject\ExternalTool\Display\Component
 * @author Sven Vanpoucke - Hogeschool Gent
 */
class ViewerComponent extends Manager
{

    /**
     * @return string
     *
     * @throws \Twig_Error_Loader
     * @throws \Twig_Error_Runtime
     * @throws \Twig_Error_Syntax
     */
    function run()
    {
        $html = array();
        $html[] = $this->render_header();

        $html[] = $this->getLaunchGenerator()->generateLaunchHtml(
            $this->getExternalToolServiceBridge()->getExternalTool(), $this->getUser(),
            $this->getExternalToolServiceBridge()
        );

        $html[] = $this->render_footer();

        return implode(PHP_EOL, $html);
    }

    /**
     * @return \Chamilo\Core\Repository\ContentObject\ExternalTool\Display\Service\LaunchGenerator
     */
    protected function getLaunchGenerator()
    {
        return $this->getService(LaunchGenerator::class);
    }
}


text:
$(document).ready(function(){
    //底边栏
    var footer = $("

").attr("id","footer");
    var footlinks = $("

").attr("class","foot-links clearfix");
    var linksselectbox =  $("

").attr("class","links-select-box");
    linksselectbox.append($('
友情链接
'));
    var optionbox = $("

").attr("class","option-box");
    linksselectbox.append(optionbox);
    var icons = $("

").addClass("icons");
//    icons.append($(''));
    footlinks.append(icons);
    var aidlinks = $("

").addClass("aid-links");
    aidlinks.append('友情链接');
    aidlinks.append('|');
    aidlinks.append('联系我们');
    aidlinks.append('|');
    aidlinks.append('网站地图');
    aidlinks.append('|');
    aidlinks.append('网络调查');
    aidlinks.append('|');
    aidlinks.append('观众留言');

    footlinks.append(aidlinks);
    footlinks.append(linksselectbox);
    var footinfo = $("

").attr("class","foot-info");
    footinfo.append('QQ人工客服时间: 9:00 - 16:30 (其他时间请留言)');
    footinfo.append($('
'));
    footinfo.append('24小时客服邮箱: service@moyuan798.com   客服QQ: 2043019077');
    footinfo.append($('
'));
    footinfo.append('墨缘798 版权所有 隐私保护');
    footinfo.append($('
'));
    footinfo.append('鲁ICP备13030697号     ');
    footinfo.append($('
'));
    footinfo.append($('设计: 博锐科技  技术支持:潍坊博锐科技有限公司'));
    footinfo.append($('
'));
    var footadorn = $('

');
    footer.append(footlinks);
    footer.append(footinfo);
    footer.append(footadorn);
    $('#container').append(footer);
    //工具栏
//    var toolbtns = $("

").addClass('tool-btns');
//    var ullist = $("

");
//    ullist.append($('

'));
//    ullist.append($('

'));
//    ullist.append($('

'));
//    ullist.append($('

'));
//    ullist.append($('

'));
//    ullist.append($('

'));
//    toolbtns.append(ullist);
//    var gsw = $("

").addClass('g-s-w');
//    var inner = $("

").addClass('inner');
//    var searchall = $('<form id="search_all" method="post"></form>');
//    searchall.append($('<input type="hidden" name="searchword" value="" />'));
//    searchall.append($('<input type="hidden" name="channelid" id="overall_channelid" value="200116" />'));
//    searchall.append($(''));
//    var fieldset = $('<fieldset></fieldset>');
//    fieldset.append($('<legend>全站检索</legend>'));
//    var box = $('

').addClass('box');
//    var boxinner = $('

').addClass('box-inner');
//    boxinner.append($('<input class="input-text searchcolumn" type="text" id="overall_searchword" formtype="inputtext" datatype="fulltext" />'));
//    boxinner.append($('全站检索'));
//    box.append(boxinner);
//    var box2 = $('

').addClass('box');
//    var boxinner2 = $('

').addClass('box-inner');
//    boxinner2.append($('
全部
'));
//    var optionbox = $('

').addClass('option-box');
//    var list = $('

');
//    list.append($('
全部
'));
//    list.append($('
新闻
'));
//    list.append($('
展览
'));
//    list.append($('
藏品
'));
//    list.append($('
教育活动
'));
//    list.append($('
美术百科
'));
//    optionbox.append(list);
//    boxinner2.append($('optionbox'));
//    box2.append(boxinner2);
//    var box3 = $('

').addClass('box');
//    box3.append($('
<input type="submit" class="submit-btn" value="检 索" />
').addClass('box-inner'));
//    fieldset.append(box);
//    fieldset.append(box2);
//    fieldset.append(box3);
//    searchall.append(fieldset);
//    inner.append(searchall);
//    gsw.append(inner);
//    toolbtns.append(gsw);
//    var datepop = $('

');
//    toolbtns.append(datepop);
//    $('#container').append(toolbtns);
});

document.write('
');
document.write('
');
document.write('

');
document.write('

');
document.write('

');
document.write('

');
document.write('

');

document.write('

');
document.write('
');
document.write('
');
document.write('
');
document.write('    <form action="/was5/web/search" method="post" onsubmit="return post(\'search_all\')" id="search_all">');
document.write('    <input type="hidden" name="searchword" value="" />');
document.write('    <input type="hidden" name="channelid" id="overall_channelid" value="200116" />');
document.write('      ');
document.write('      <fieldset>');
document.write('        <legend>全站检索</legend>');
document.write('
');
document.write('
');
document.write('            <input class="input-text searchcolumn" type="text" id="overall_searchword" formtype="inputtext" datatype="fulltext" />');
document.write('            全站检索');
document.write('
');
document.write('
');
document.write('
');
document.write('
');
document.write('
');
document.write('              全部');
document.write('              ');
document.write('
');
document.write('
');
document.write('
');
document.write('
全部
');
document.write('
新闻
');
document.write('
展览
');
document.write('
藏品
');
document.write('
教育活动
');
document.write('
美术百科
');
document.write('
');
document.write('
');
document.write('
');
document.write('
');
document.write('
');
document.write('
');
document.write('             <input type="submit" class="submit-btn" value="检 索" />');
document.write('
');
document.write('
');
document.write('      </fieldset>');
document.write('    </form>');
document.write('
');
document.write('
');
document.write('

');
document.write('
');

document.write('');
document.write('');
document.write('');
var _bdhmProtocol = (("https:" == document.location.protocol) ? " https://" : " http://");
document.write(unescape("%3Cscript src='" + _bdhmProtocol + "hm.baidu.com/h.js%3F32806cb69e00ddaaf3847937c32700c8' type='text/javascript'%3E%3C/script%3E"));


text:
CURRENT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "${CURRENT_DIR}/../integration_test_setup.sh" \
  || { echo "integration_test_setup.sh not found!" >&2; exit 1; }

#### SETUP #############################################################

set -e

function set_up() {
  mkdir -p testing || fail "Couldn't create directory"
  echo "cc_test(name='mytest', srcs=['mytest.cc'], malloc=':system_malloc')" > testing/BUILD || fail
  echo "cc_library(name='system_malloc', srcs=[])"                           >> testing/BUILD || fail
  echo "int main() {return 0;}"         > testing/mytest.cc || fail
}

STARTUP_FLAGS="--batch"
BUILD_FLAGS="--keep_going --discard_analysis_cache"

#### TESTS #############################################################

function test_build() {
  bazel $STARTUP_FLAGS build $BUILD_FLAGS //testing:mytest >& $TEST_log \
    || fail "Expected success"
}

function test_test() {
  bazel $STARTUP_FLAGS test $BUILD_FLAGS //testing:mytest >& $TEST_log \
    || fail "Expected success"
}

# bazel info inherits from bazel build, but it doesn't have much in common with it.
function test_info() {
  bazel $STARTUP_FLAGS info $BUILD_FLAGS >& $TEST_log || fail "Expected success"
}

function test_empty_build() {
  bazel $STARTUP_FLAGS build $BUILD_FLAGS >& $TEST_log || fail "Expected success"
}

function test_query() {
  bazel $STARTUP_FLAGS query 'somepath(//testing:mytest,//testing:system_malloc)' >& $TEST_log \
    || fail "Expected success"
  expect_log "//testing:mytest"
  expect_log "//testing:system_malloc"
}

# Action conflicts can cause deletion of nodes, and deletion is tricky with no edges.
function test_action_conflict() {
  mkdir -p conflict || fail "Couldn't create directory"
  cat > conflict/BUILD <<EOF || fail "Couldn't create BUILD file"
cc_library(name='x', srcs=['foo.cc'])
cc_binary(name='_objs/x/conflict/foo.pic.o', srcs=['bar.cc'])
cc_binary(name='foo', deps=['x'], data=['_objs/x/conflict/foo.pic.o'])
EOF
  touch conflict/foo.cc || fail
  touch conflict/bar.cc || fail

  # --nocache_test_results to make log-grepping easier.
  bazel $STARTUP_FLAGS test $BUILD_FLAGS --nocache_test_results //conflict:foo //testing:mytest >& $TEST_log \
    && fail "Expected failure"
  exit_code=$?
  [ $exit_code -eq 1 ] || fail "Wrong exit code: $exit_code"
  expect_log "is generated by these conflicting actions"
  expect_not_log "Graph edges not stored"
  expect_log "mytest *PASSED"
}

# The following tests are not expected to exercise codepath -- make sure nothing bad happens.

function test_no_batch() {
  bazel $STARTUP_FLAGS --nobatch test $BUILD_FLAGS //testing:mytest >& $TEST_log \
    || fail "Expected success"
}

function test_no_keep_going() {
  bazel $STARTUP_FLAGS test $BUILD_FLAGS --nokeep_going //testing:mytest >& $TEST_log \
    || fail "Expected success"
}

function test_no_discard_analysis_cache() {
  bazel $STARTUP_FLAGS test $BUILD_FLAGS --nodiscard_analysis_cache //testing:mytest >& $TEST_log \
    || fail "Expected success"
}

run_suite "test for --discard_graph_edges"


text:
package org.clinical3po.conceptmatcher

import javax.annotation.Nonnull
import scala.annotation.implicitNotFound
import org.apache.lucene.document.Document
import scala.collection.JavaConverters._
import LuceneFieldHelpers._
import scala.language.reflectiveCalls

object LuceneDocumentAdder {

  /**
   * A type class that provides logic to convert an object f
   * type T to a collection of Lucene Document objects
   */
  @implicitNotFound("No member of type class LuceneDocumentLike in scope for ${T}")
  trait LuceneDocumentLike[T] {

    /**
     * Convert object of type T to a Lucene document
     */
    def toDocuments(v: T): Iterable[Document]

  }

  /**
   * Implementation of LuceneDocumentLike for collection of Lucene Documents
   */
  implicit object TransparentLuceneDocumentLike extends LuceneDocumentLike[Document] {
    def toDocuments(v: Document) = Seq(v)
  }

  type StringStringMap = Map[String, Any]
  implicit object StringStringMapLuceneDocumentLike extends LuceneDocumentLike[StringStringMap] {
    def toDocuments(map: StringStringMap): Iterable[Document] = {
      val doc = new Document
      map.foreach { case (k, v) =>
        doc.addIndexedStoredField(k, v.toString)
      }
      Seq(doc)
    }
  }

}

trait LuceneDocumentAdder { self: LuceneIndexWriter =>
  import LuceneDocumentAdder.LuceneDocumentLike

  /**
   * Adds a collection of documents to the Index
   */
  def addDocuments[T: LuceneDocumentLike](@Nonnull docs: Iterable[T]): Unit =
    withIndexWriter { indexWriter =>
      val documents = docs.flatMap { doc => implicitly[LuceneDocumentLike[T]].toDocuments(doc) }
      indexWriter.addDocuments(documents.asJava)
    }

  /**
   * Adds a single document to the index
   */
  def addDocument[T: LuceneDocumentLike](@Nonnull doc: T): Unit =
    addDocuments[T](Seq(doc))

}


text:
package com.tigerhotel.backoffice.core.model;

public enum NotifyType {

		INFO("bs-callout-info"), WARNING("bs-callout-warning"), DANGER("bs-callout-danger");

		private String style;

		NotifyType(String NotifyStyle) {
			style = NotifyStyle;
		}

		public String getStyle() {
			return this.style;
		}
}


text:
var lorenzSystem;
var cam;
var cameraController;
var lsViewer;
var currentPoint;

var gui;
var systemParams = {
  rho: 28,
  sigma: 10,
  beta: 8/3.0
};

function setup(){
  createCanvas(windowWidth, windowHeight, WEBGL);

  gui = new dat.gui.GUI();
  gui.add(systemParams, "rho").min(1).max(50).step(0.1);
  gui.add(systemParams, "sigma").min(1).max(30).step(0.1);
  gui.add(systemParams, "beta").min(1).max(30).step(0.1);

  lorenzSystem = new LorenzSystem(systemParams);
  lsViewer = new LorenzSystemViewer();

  cam = createCamera();
  cameraController = new CameraController(cam);
  currentPoint = createVector(1, 1, 1);
}

function draw(){
  background(45);
  cameraController.tick();
  scale(6);
  currentPoint = lsViewer.computePoints(lorenzSystem, currentPoint, 1);
  lsViewer.render();
}

function keyTyped(){
  if (key === 'c'){
    lsViewer.clearPoints();
  }
}

class LorenzSystem {
  constructor(config){
    this.config = config;
  }

  dx_dt (loc){
    return this.config.sigma * (loc.y - loc.x);
  }

  dy_dt (loc){
    return loc.x * (this.config.rho - loc.z) - loc.y;
  }

  dz_dt (loc){
    return loc.x * loc.y - this.config.beta * loc.z;
  }

  nextLocation(loc, timeStep){
    let newPoint = loc.copy();
    newPoint.x += this.dx_dt(loc) * timeStep;
    newPoint.y += this.dy_dt(loc) * timeStep;
    newPoint.z += this.dz_dt(loc) * timeStep;
    return newPoint;
  }
}

class LorenzSystemViewer {
  constructor(){
    this.timeStep = 0.01;
    this.computedPoints = [];
  }

  computePoints(system, loc, numIterations){
    let nextPoint;
    for (var i = 0; i < numIterations; i++){
      nextPoint = system.nextLocation(loc, this.timeStep);
      this.computedPoints.push(nextPoint);

      // console.log(`x: ${loc.x}, y: ${loc.y}, z: ${loc.z}`)
      loc = nextPoint;
    }

    return loc;
  }

  clearPoints(){
    this.computedPoints = [];
  }

  render(){
    this.renderAsShape();
  }

  renderAsLines(){
    let loc = this.computedPoints[0];

    for (var i = 0; i < (this.computedPoints.length-1); i++){
      stroke(85+ i%255, 170+ i%255, 255 + i%255);
      let nextPoint = this.computedPoints[i+1];
      line(loc.x, loc.y, loc.z, nextPoint.x, nextPoint.y, nextPoint.z);
      loc = nextPoint;
    }
  }

  renderAsShape(){
    let loc;
    stroke(50, 200, 50);

    noFill();
    beginShape()
    for (var i = 0; i < this.computedPoints.length; i++){
      loc = this.computedPoints[i];

      if (i % 10 === 0){
        vertex(loc.x, loc.y, loc.z);
        endShape();
        stroke(150+ i%80, 100 +i%80, 50 + i%150);
        beginShape();
      }

      vertex(loc.x, loc.y, loc.z);
    }
    endShape();
  }
}


text:
import salt.modules.config as config
import salt.modules.zenoss as zenoss
from tests.support.mixins import LoaderModuleMockMixin
from tests.support.mock import MagicMock, call, patch
from tests.support.unit import TestCase

class ZenossTestCase(TestCase, LoaderModuleMockMixin):
    """
    Test cases for salt.modules.keystone
    """

    def setup_loader_modules(self):
        return {
            zenoss: {"__salt__": {"config.option": config.option}},
            config: {"__opts__": {}},
        }

    def test_zenoss_session(self):
        """
        test zenoss._session when using verify_ssl
        """
        zenoss_conf = {
            "zenoss": {
                "hostname": "https://test.zenoss.com",
                "username": "admin",
                "password": "test123",
            }
        }

        for verify in [True, False, None]:
            zenoss_conf["zenoss"]["verify_ssl"] = verify
            if verify is None:
                zenoss_conf["zenoss"].pop("verify_ssl")
                verify = True

            patch_opts = patch.dict(config.__opts__, zenoss_conf)
            mock_http = MagicMock(return_value=None)
            patch_http = patch("salt.utils.http.session", mock_http)

            with patch_http, patch_opts:
                zenoss._session()
                self.assertEqual(
                    mock_http.call_args_list,
                    [
                        call(
                            ca_bundle=None,
                            headers={"Content-type": "application/json; charset=utf-8"},
                            password="test123",
                            user="admin",
                            verify_ssl=verify,
                        )
                    ],
                )


text:
package com.neykov.appstud.util;

import android.app.Application;
import android.content.Context;
import android.support.annotation.NonNull;

import dagger.Module;
import dagger.Provides;

@Module
public class ApplicationModule {

    private final Application mApplication;

    public ApplicationModule(@NonNull Application application) {
        this.mApplication = application;
    }

    @Provides
    Application provideApplication(){
        return mApplication;
    }

    @Provides
    @Global
    Context provideApplicationContext(){
        return mApplication.getApplicationContext();
    }
}


text:
package com.rocketfuel.sdbc.h2

/**
 * Serialized tells the H2 client to send the parameter
 * as a serialized object instead of trying the other implicit conversions
 * to ParameterValue.
 */
@SerialVersionUID(-3881436119431769328L)
case class Serialized(
  value: AnyRef with java.io.Serializable
)


text:
package org.n52.iceland.lifecycle;

import javax.annotation.PreDestroy;

/**
 * @see PreDestroy
 * @since 1.0.0
 * @author Christian Autermann
 */
public interface Destroyable {
    /**
     * Destroys this object.
     */
    void destroy();
}


text:
<?php

namespace GotChosen\SiteBundle\Repository;

use Doctrine\ORM\EntityRepository;

/**
 * VideoStatusRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class VideoStatusRepository extends EntityRepository
{
}