text:
from setuptools import setup

version = __import__('m2x').version

LONG_DESCRIPTION = """
AT&T's M2X is a cloud-based fully managed data storage service for network
connected machine-to-machine (M2M) devices. python-m2x is python client to M2X
API. API documentation at https://m2x.att.com/developer/documentation
"""

setup(
    name='m2x',
    version=version,
    author='Citrusbyte',
    author_email='matias.aguirre@citrusbyte.com',
    description='M2X Python API client',
    license='MIT',
    keywords='m2x, api',
    url='https://github.com/attm2x/m2x-python',
    packages=[
        'm2x',
        'm2x.v2',
        'm2x.tests',
        'm2x.tests.v2'
    ],
    long_description=LONG_DESCRIPTION,
    install_requires=[
        'requests>=2.0.1',
        'iso8601>=0.1.8',
    ],
    classifiers=[
        'Development Status :: 4 - Beta',
        'Topic :: Internet',
        'License :: OSI Approved :: MIT License',
        'Intended Audience :: Developers',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6'
    ],
    test_suite='m2x.tests',
    zip_safe=False
)


text:
Nesse vídeo mostro como carregar arquivos e arquivos grandes usando Node.js

Quando precisamos trabalhar com um arquivo de dados muito grande não é possível carregar todo o seu conteúdo na aplicação mas podemos ir lendo e processando partes do arquivo.

## Vídeo:

## Vamos ver 2 formas:

### 1 - usando o modulo readline do core do node.js

**Vantagem:** Não precisa instalar modulos da comunidade

Link: https://nodejs.org/api/readline.html#readline_example_read_file_stream_line_by_line

Exemplo, lendo o arquivo **country.txt**:

```js
const readline = require('readline');
const fs = require('fs');
// iniciamos com um stream de leitura no arquivo:
const rl = readline.createInterface({
  input: fs.createReadStream('country.txt')
});
// função que é executada a cada linha:
rl.on('line', (line) => {
  console.log('Line from file:', line);
});
// evento executado após ler todas as linhas do arquivo:
rl.on('close', () => {
  console.log('acabou!');
});

```

### 2 - Usando o modulo linebyline do NPM

**Vantagens:** é mais simples de usar pois já usa resolve coisas como o número da linha atual
**Desvantagens:** Precisa instalar o modulo `linebyline`

Instale o module com `npm install --save linebyline`

Modulo: https://www.npmjs.com/package/linebyline

```js
const linebyline = require('linebyline');
let rl = linebyline('./country.txt');

rl.on('line', (line, lineCount, byteCount) => {
  // faça algo com a linha
  console.log(`Estou na linha: ${lineCount} com o valor ${line}`)
});

.on('error', (e) => {
  console.error(e)
  // deu erro!
});
```

redpajama_set_name: RedPajamaGithub


text:
package android.net.sip;

public class SipAudioCall
{
  // Classes

  public static class Listener
  {
    // Constructors

    public Listener(){
    }
    // Methods

    @com.francetelecom.rd.stubs.annotation.CallBack("callListener")
    public void onError(SipAudioCall arg1, int arg2, java.lang.String arg3){
    }
    @com.francetelecom.rd.stubs.annotation.CallBack("callListener")
    public void onCallEnded(SipAudioCall arg1){
    }
    @com.francetelecom.rd.stubs.annotation.CallBack("callListener")
    public void onCallEstablished(SipAudioCall arg1){
    }
    @com.francetelecom.rd.stubs.annotation.CallBack("callListener")
    public void onCallBusy(SipAudioCall arg1){
    }
    @com.francetelecom.rd.stubs.annotation.CallBack("callListener")
    public void onCalling(SipAudioCall arg1){
    }
    @com.francetelecom.rd.stubs.annotation.CallBack("callListener")
    public void onRinging(SipAudioCall arg1, SipProfile arg2){
    }
    @com.francetelecom.rd.stubs.annotation.CallBack("callListener")
    public void onRingingBack(SipAudioCall arg1){
    }
    @com.francetelecom.rd.stubs.annotation.CallBack("callListener")
    public void onChanged(SipAudioCall arg1){
    }
    @com.francetelecom.rd.stubs.annotation.CallBack("callListener")
    public void onCallHeld(SipAudioCall arg1){
    }
    @com.francetelecom.rd.stubs.annotation.CallBack("callListener")
    public void onReadyToCall(SipAudioCall arg1){
    }
  }
  // Constructors

  public SipAudioCall(android.content.Context arg1, SipProfile arg2){
  }
  // Methods

  public int getState(){
    return 0;
  }
  public void close(){
  }
  public boolean isMuted(){
    return false;
  }
  public void sendDtmf(int arg1){
  }
  public void sendDtmf(int arg1, android.os.Message arg2){
  }
  public void endCall() throws SipException{
  }
  public void setListener(@com.francetelecom.rd.stubs.annotation.CallBackRegister("callListener") SipAudioCall.Listener arg1){
  }
  public void setListener(@com.francetelecom.rd.stubs.annotation.CallBackRegister("callListener") SipAudioCall.Listener arg1, boolean arg2){
  }
  public boolean isInCall(){
    return false;
  }
  public SipProfile getPeerProfile(){
    return (SipProfile) null;
  }
  public SipProfile getLocalProfile(){
    return (SipProfile) null;
  }
  public void answerCall(int arg1) throws SipException{
  }
  public void makeCall(SipProfile arg1, SipSession arg2, int arg3) throws SipException{
  }
  public void startAudio(){
  }
  public boolean isOnHold(){
    return false;
  }
  public void attachCall(SipSession arg1, java.lang.String arg2) throws SipException{
  }
  public android.net.rtp.AudioGroup getAudioGroup(){
    return (android.net.rtp.AudioGroup) null;
  }
  public void holdCall(int arg1) throws SipException{
  }
  public void setAudioGroup(android.net.rtp.AudioGroup arg1){
  }
  public void continueCall(int arg1) throws SipException{
  }
  public void toggleMute(){
  }
  public SipSession getSipSession(){
    return (SipSession) null;
  }
  public void setSpeakerMode(boolean arg1){
  }
  public android.net.rtp.AudioStream getAudioStream(){
    return (android.net.rtp.AudioStream) null;
  }
}


text:
日历

点击日期查看当日记录


text:
module Dsc
  # Handle cleanup and removing old builds
  class TypeCleaner
    attr_accessor :target_module_path
    attr_accessor :puppet_type_subpath
    attr_accessor :puppet_type_spec_subpath
    attr_accessor :module_path

    def initialize(target_module_path, puppet_type_subpath, puppet_type_spec_subpath)
      @target_module_path       = target_module_path
      @puppet_type_subpath      = puppet_type_subpath
      @puppet_type_spec_subpath = puppet_type_spec_subpath
    end

    def clean_dsc_types
      puppet_type_path = "#{@target_module_path}/#{@puppet_type_subpath}"
      clean_folder(["#{puppet_type_path}/dsc_*.rb"])
    end

    def clean_dsc_type_specs
      puppet_type_spec_path = "#{@target_module_path}/#{@puppet_type_spec_subpath}"
      clean_folder(["#{puppet_type_spec_path}/dsc_*_spec.rb"])
    end

    def clean_folder(folders)
      type_pathes = []
      folders.each do |folder|
        Dir.glob(folder.to_s).each do |filepath|
          pn = Pathname.new(filepath).expand_path.relative_path_from(@target_module_path)
          type_pathes << "Remove - #{pn}"
          FileUtils.rm_rf filepath
        end
      end
      type_pathes
    end
  end
end


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
 PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.skysport.core.mapper.DictionaryMapper">
	<sql id="searchDicSql">
			id AS id,
			type AS type,
			key_name  AS keyName,
			value_name   AS valueName
	</sql>

	<select id="searchDictionary" resultType="Dictionary">
		SELECT
			<include refid="searchDicSql"/>
		FROM t_sys_dictionary
	</select>

</mapper>


text:
// Qt includes
#include <QCoreApplication>
#include <QFileInfo>

// ctkDICOMCore includes
#include "ctkDICOMTester.h"

// STD includes
#include <iostream>
#include <cstdlib>

void printUsage()
{
  std::cout << " ctkDICOMTesterTest1 [<dcmqrscp>] [<configfile>]" << std::endl;
}

int ctkDICOMTesterTest1(int argc, char * argv [])
{
  QCoreApplication app(argc, argv);

  ctkDICOMTester tester;

  if (argc > 1)
    {
    tester.setDCMQRSCPExecutable(argv[1]);
    if (tester.dcmqrscpExecutable() != argv[1])
      {
       std::cerr << __LINE__
                 << ": Failed to set dcmqrscp: " << argv[1]
                 << " value:" << qPrintable(tester.dcmqrscpExecutable())
                 << std::endl;
       return EXIT_FAILURE;
      }
    }
  if (argc > 2)
    {
    tester.setDCMQRSCPConfigFile(argv[2]);
    if (tester.dcmqrscpConfigFile() != argv[2])
      {
       std::cerr << __LINE__
                 << ": Failed to set dcmqrscp config file: " << argv[2]
                 << " value:" << qPrintable(tester.dcmqrscpConfigFile())
                 << std::endl;
       return EXIT_FAILURE;
      }
    }

  QString dcmqrscp(tester.dcmqrscpExecutable());
  QString dcmqrscpConf(tester.dcmqrscpConfigFile());

  if (!QFileInfo(dcmqrscp).exists() ||
      !QFileInfo(dcmqrscp).isExecutable())
    {
    std::cerr << __LINE__
              << ": Wrong dcmqrscp executable: " << qPrintable(dcmqrscp)
              << std::endl;
    }

  if (!QFileInfo(dcmqrscpConf).exists() ||
      !QFileInfo(dcmqrscpConf).isReadable())
    {
    std::cerr << __LINE__
              << ": Wrong dcmqrscp executable: " << qPrintable(dcmqrscp)
              << std::endl;
    }

  QProcess* process = tester.startDCMQRSCP();
  if (!process)
    {
    std::cerr << __LINE__
              << ": Failed to start dcmqrscp: " << qPrintable(dcmqrscp)
              << " with config file:" << qPrintable(dcmqrscpConf) << std::endl;
    return EXIT_FAILURE;
    }
  bool res = tester.stopDCMQRSCP();
  if (!res)
    {
    std::cerr << __LINE__
              << ": Failed to stop dcmqrscp: " << qPrintable(dcmqrscp)
              << " with config file:" << qPrintable(dcmqrscpConf) << std::endl;
    return EXIT_FAILURE;
    }

  process = tester.startDCMQRSCP();
  if (!process)
    {
    std::cerr << __LINE__
              << ": Failed to start dcmqrscp: " << qPrintable(dcmqrscp)
              << " with config file:" << qPrintable(dcmqrscpConf)
              << std::endl;
    return EXIT_FAILURE;
    }
  process = tester.startDCMQRSCP();
  if (process)
    {
    std::cerr << __LINE__
              << ": Failed to start dcmqrscp: " << qPrintable(dcmqrscp)
              << " with config file:"<< qPrintable(dcmqrscpConf) << std::endl;
    return EXIT_FAILURE;
    }
  res = tester.stopDCMQRSCP();
  if (!res)
    {
    std::cerr << __LINE__
              << ": Failed to stop dcmqrscp: " << qPrintable(dcmqrscp)
              << " with config file:" << qPrintable(dcmqrscpConf) << std::endl;
    return EXIT_FAILURE;
    }
  // there should be no process to stop
  res = tester.stopDCMQRSCP();
  if (res)
    {
    std::cerr << __LINE__
              << ": Failed to stop dcmqrscp: " << qPrintable(dcmqrscp)
              << " with config file:" << qPrintable(dcmqrscpConf) << std::endl;
    return EXIT_FAILURE;
    }
  return EXIT_SUCCESS;
}


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

    /**
     * @ngdoc function
     * @name ngBoilerplateApp.main.controller:MainController
     * @description
     * # MainController
     * Controller of the ngBoilerplateApp
     */
    angular
        .module('ngBoilerplateApp.main')
        .controller('MainController', MainController);

    MainController.$inject = [];

    function MainController () {
        var vm = this;
    }
})();


text:
<?php

namespace AmqpWorkers\Tests\Worker;

use AmqpWorkers\Worker\AbstractWorker;
use AmqpWorkers\Worker\ClosureWorker;

class AbstractWorkerTest extends \PHPUnit_Framework_TestCase
{
    public function testFromClosure()
    {
        $closure = function($value) { return $value; };
        $actual = AbstractWorker::fromClosure($closure);

        $this->assertInstanceOf(ClosureWorker::class, $actual);
    }
}


text:
theModule.controller('mainCtrl', ['$scope', '$timeout'
  , ($scope, $timeout) => {

  function updateUI(){
    var phase = $scope.$root.$$phase;
    if(phase !== '$apply' && phase !== '$digest') {
        $scope.$apply();
    }
  }

}]);


text:
package com.wso2telco.redis;

import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.Protocol;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * This class is used to connect to the Redis database and return a Jedis connection pool
 */
public class RedisConnection {

    private static final String REDIS_PROPERTIES_FILE = "repository/conf/redis-config.properties";

    private static JedisPool jedisPool;
    private static Properties prop;

    /**
     * Returns a pool of Jedis connections.
     * Create Create a new pool of Jedis connections if jedisPool is null.
     *
     * @return JedisPool
     */
    protected static JedisPool getJedisPool() {

        if (null == jedisPool) {
            createJedisPool();

        }
        return jedisPool;

    }

    /**
     * Create a new pool of Jedis connections.
     */
    private static void createJedisPool() {

        loadRedisProperties();

        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        String host = prop.getProperty("host");
        int port = Integer.parseInt(prop.getProperty("port"));
        int timeout = Protocol.DEFAULT_TIMEOUT;
        String password;
        if (prop.getProperty("password").equals("")) {
            password = null;
        } else {
            password = prop.getProperty("password");
        }

        jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout, password);

    }

    /**
     * Reads redis-config property file
     */
    private static void loadRedisProperties() {

        if (null == prop) {
            try (InputStream input = new FileInputStream(REDIS_PROPERTIES_FILE)) {
                prop = new Properties();
                prop.load(input);

            } catch (IOException e) {

            }

        }

    }

}


text:
package com.spatial4j.core.exception;

/**
 * A shape was constructed but failed because, based on the given parts, it's invalid. For example
 * a rectangle's minimum Y was specified as greater than the maximum Y. This class is not used for
 * parsing exceptions; that's usually {@link java.text.ParseException}.
 */
public class InvalidShapeException extends RuntimeException {

  public InvalidShapeException(String reason, Throwable cause) {
    super(reason, cause);
  }

  public InvalidShapeException(String reason) {
    super(reason);
  }
}


text:
<<<<<<< HEAD

package g4p_controls;

import java.awt.Color;
import java.awt.FlowLayout;

import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.colorchooser.ColorSelectionModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

/**
 * The preview panel class for the color selector.
 *
 * @author Peter Lager
 *
 */
@SuppressWarnings("serial")
class ColorPreviewPanel extends JPanel implements ChangeListener {
	JLabel lblPrev, lblCurr;
	JLabel lblPrevColor, lblCurrColor;

	public ColorPreviewPanel(Color c){
		setLayout(new FlowLayout());
		lblPrev = new JLabel("Initial Color");
		lblCurr = new JLabel("Current Color");
		lblPrevColor = new JLabel("                   ");
		lblPrevColor.setOpaque(true);
		lblPrevColor.setBackground(c);
		lblCurrColor = new JLabel("                   ");
		lblCurrColor.setOpaque(true);
		lblCurrColor.setBackground(c);
		add(lblCurr);
		add(lblCurrColor);
		add(lblPrevColor);
		add(lblPrev);
	}

	public void stateChanged(ChangeEvent e) {
		ColorSelectionModel csm = (ColorSelectionModel)e.getSource();
		lblCurrColor.setBackground(csm.getSelectedColor());
	}

	public void setPrevColor(Color pcol){
		lblPrevColor.setBackground(pcol);
	}
}
=======
/*
  Part of the G4P library for Processing
  	http://www.lagers.org.uk/g4p/index.html
	http://sourceforge.net/projects/g4p/files/?source=navbar

  Copyright (c) 2013 Peter Lager

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Lesser General Public
  License as published by the Free Software Foundation; either
  version 2.1 of the License, or (at your option) any later version.

  This library is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  Lesser General Public License for more details.

  You should have received a copy of the GNU Lesser General
  Public License along with this library; if not, write to the
  Free Software Foundation, Inc., 59 Temple Place, Suite 330,
  Boston, MA  02111-1307  USA
 */

package g4p_controls;

import java.awt.Color;
import java.awt.FlowLayout;

import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.colorchooser.ColorSelectionModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

/**
 * The preview panel class for the color selector.
 *
 * @author Peter Lager
 *
 */
@SuppressWarnings("serial")
class ColorPreviewPanel extends JPanel implements ChangeListener {
	JLabel lblPrev, lblCurr;
	JLabel lblPrevColor, lblCurrColor;

	public ColorPreviewPanel(Color c){
		setLayout(new FlowLayout());
		lblPrev = new JLabel("Initial Color");
		lblCurr = new JLabel("Current Color");
		lblPrevColor = new JLabel("                   ");
		lblPrevColor.setOpaque(true);
		lblPrevColor.setBackground(c);
		lblCurrColor = new JLabel("                   ");
		lblCurrColor.setOpaque(true);
		lblCurrColor.setBackground(c);
		add(lblCurr);
		add(lblCurrColor);
		add(lblPrevColor);
		add(lblPrev);
	}

	public void stateChanged(ChangeEvent e) {
		ColorSelectionModel csm = (ColorSelectionModel)e.getSource();
		lblCurrColor.setBackground(csm.getSelectedColor());
	}

	public void setPrevColor(Color pcol){
		lblPrevColor.setBackground(pcol);
	}
}
>>>>>>> origin/master


text:
package com.noelcurtis.greencard.bullitenscraper

object BulletinManagerTestApp extends App {
  new BulletinManagerApp().handler("", null)
}


text:
function Directive(){
    "ngInject";

    function link(scope, element, attr, ngModel){

        ngModel.$validators.compareTo = function(newPassword) {
          return newPassword == scope.confirmationPassword;
        };

        scope.$watch("confirmationPassword", function() {
          ngModel.$validate();
        });

    };

    var directive = {
        require : 'ngModel',
        link: link,
        scope : {
            confirmationPassword : "=compareTo"
        }
    }

    return directive;
}

module.exports =  Directive;


text:
package org.bouncycastle.cms.jcajce;

import java.io.IOException;

import org.bouncycastle.asn1.ASN1Encoding;
import org.bouncycastle.asn1.cms.ecc.ECCCMSSharedInfo;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.util.Pack;

class RFC5753KeyMaterialGenerator
    implements KeyMaterialGenerator
{
    public byte[] generateKDFMaterial(AlgorithmIdentifier keyAlgorithm, int keySize, byte[] userKeyMaterialParameters)
    {
        ECCCMSSharedInfo eccInfo = new ECCCMSSharedInfo(keyAlgorithm, userKeyMaterialParameters, Pack.intToBigEndian(keySize));

        try
        {
            return eccInfo.getEncoded(ASN1Encoding.DER);
        }
        catch (IOException e)
        {
            throw new IllegalStateException("Unable to create KDF material: " + e);
        }
    }
}


text:
ExternalProject_Add(Eigen
   PREFIX Eigen
   HG_REPOSITORY "https://bitbucket.org/eigen/eigen/"
   HG_TAG 3.3.3
   BUILD_COMMAND ""
   CONFIGURE_COMMAND ""
   INSTALL_COMMAND
       ${CMAKE_COMMAND} -E copy_directory
       ${CMAKE_BINARY_DIR}/Eigen/src/Eigen/Eigen
       ${DEP_INSTALL_DIR}/include/eigen3/Eigen &&
       ${CMAKE_COMMAND} -E copy_directory
       ${CMAKE_BINARY_DIR}/Eigen/src/Eigen/unsupported
       ${DEP_INSTALL_DIR}/include/eigen3/unsupported
   DOWNLOAD_DIR ${DEP_DOWNLOAD_DIR}/<PROJECT_NAME>
)


text:
from flask.ext.wtf import Form
from wtforms import StringField, SubmitField
from wtforms.validators import Required

class NameForm(Form):
    name = StringField('What is your name?', validators=[Required()])
    submit = SubmitField('Submit')

class CommentForm(Form):
    body = StringField('Enter your comment', validators=[Required()])
    submit = SubmitField('Submit')


text:
/*
 * $Log: HTMLClip.java,v $
 * Revision 1.2  2011/01/13 17:44:26  vizigoth
 * Major refactor of the industrial area and improved front-end documentation.
 *
 * Revision 1.1  2011/01/04 10:39:03  vizigoth
 * Refactor all package names to simpler forms more consistent with typical Java usage.
 *
 * Revision 1.4  2009/05/14 16:15:13  vizigoth
 * Major refactor to remove dependency on JPA and introduce better interface and implementation separation. Removed all setPropertiesFromInterface and castFromInterface methods.
 *
 * Revision 1.3  2009/03/30 09:04:50  vizigoth
 * Refactor to use SMPTE harmonized names and add early KLV file support.
 *
 * Revision 1.2  2008/01/27 11:07:36  vizigoth
 * Edited comments to a release standard.
 *
 * Revision 1.1  2007/11/13 22:08:45  vizigoth
 * Public release of MAJ API.
 */

package tv.amwa.maj.model;

// Documentation in AAFSpecDR4.pdf 1.0 so I'm guessing this is old and dusty.

import tv.amwa.maj.exception.PropertyNotPresentException;

/**
 *
 *
Specifies a reference to HTML text essence.

 *
 *
Typically, an HTML clip is in a {@linkplain StaticTrack static track} and defines a section of
 * HTML text that is associated with the essence data in a parallel {@linkplain TimelineTrack timeline
 * track}. The length of the HTML clip defines the extent of the association with the parallel track in
 * the same {@linkplain Package package}.

 *
 *
The {@linkplain #getBeginAnchor() begin anchor} and {@linkplain #getEndAnchor() end anchor} properties
 * specify the HTML tags that delineate the start and end of
 * the referenced text. The begin anchor tag shall precede the end anchor tag. If the begin anchor and end
 * anchor properties are omitted, the HTML clip references all the HTML text in the essence data object.

 *
 *
 *
 * @see HTMLDescriptor
 */
public interface HTMLClip
	extends TextClip {

	/**
	 *
Sets the begin anchor property of this HTML clip, which delineates the anchor that is the start of
	 * the reference's text. Set this optional property to null to omit it.

	 *
	 * @param beginAnchor Begin anchor property of this HTML clip.
	 */
	public void setBeginAnchor(
			String beginAnchor);

	/**
	 *
Returns the begin anchor property of this HTML clip, which delineates the anchor that is the start
	 * of the reference's text. This is an optional property.

	 *
	 * @return Begin anchor property of this HTML clip.
	 *
	 * @throws PropertyNotPresentException The optional begin anchor property is not
	 * present in this HTML clip.
	 */
	public String getBeginAnchor()
		throws PropertyNotPresentException;

	/**
	 *
Sets the end anchor property of this HTML clip, which delineates the anchor that is the end of the
	 * reference's text. Set this optional property to null to omit it.

	 *
	 * @param endAnchor End anchor property of this HTML clip.
	 */
	public void setEndAnchor(
			String endAnchor);

	/**
	 *
Returns the end anchor property of this HTML clip, which delineates the anchor that is the end of the
	 * reference's text. This is an optional property.

	 *
	 * @return End anchor property of this HTML clip.
	 *
	 * @throws PropertyNotPresentException The optional end anchor property is not
	 * present in this HTML clip.
	 */
	public String getEndAnchor()
		throws PropertyNotPresentException;

	/**
	 *
Create a cloned copy of this HTML clip.

	 *
	 * @return Cloned copy of this HTML clip.
	 */
	public HTMLClip clone();
}


text:
class Region < ActiveRecord::Base
  include Ublisherp::PublishableWithInstanceShortcuts
end


text:
#import "IDEFileReference.h"

#import "IDEInspectorMatching-Protocol.h"

@class NSString;

@interface IDEFileReference (IDEKitFileReferenceSourceControlPropertyAdditions) <IDEInspectorMatching>
+ (id)keyPathsForValuesAffectingNavigableItem_sourceControlCurrentRevision;
+ (id)keyPathsForValuesAffectingNavigableItem_sourceControlLocalStatus;
+ (id)keyPathsForValuesAffectingNavigableItem_sourceControlLocalStatusFlag;
+ (id)keyPathsForValuesAffectingNavigableItem_sourceControlLocalStatusString;
+ (id)keyPathsForValuesAffectingNavigableItem_sourceControlServerStatus;
+ (id)keyPathsForValuesAffectingNavigableItem_sourceControlServerStatusFlag;
+ (id)keyPathsForValuesAffectingNavigableItem_versionAndServerStatus;
- (id)applicableInspectorsForCategory:(id)arg1 suggestion:(id)arg2;
@property(readonly) unsigned long long navigableItem_conflictStateForUpdateOrMerge;
@property(readonly) NSString *navigableItem_sourceControlCurrentRevision;
@property(readonly) NSString *navigableItem_sourceControlLocalStatus;
- (int)navigableItem_sourceControlLocalStatusFlag;
@property(readonly) NSString *navigableItem_sourceControlLocalStatusString;
@property(readonly) NSString *navigableItem_sourceControlServerStatus;
- (int)navigableItem_sourceControlServerStatusFlag;
@property(readonly) NSString *navigableItem_versionAndServerStatus;
- (id)sourceControlInspectorRepositoryURLString;
@end


text:
import React from 'react';

const NavbarContext = React.createContext();

NavbarContext.displayName = 'NavbarContext';

export default NavbarContext;


text:
"""
Brocade NOS Driver Test
"""
import sys

from quantum.plugins.brocade.nos import nosdriver as nos

def nostest(host, username, password):
    # Driver
    driver = nos.NOSdriver()

    # Quantum operations
    vlan = 1001
    mac = '0050.56bf.0001'
    driver.create_network(host, username, password, vlan)
    driver.associate_mac_to_network(host, username, password, vlan, mac)
    driver.dissociate_mac_from_network(host, username, password, vlan, mac)
    driver.delete_network(host, username, password, vlan)

    # AMPP enumeration
    with driver.connect(host, username, password) as mgr:
        print driver.get_port_profiles(mgr)
        print driver.get_port_profile(mgr, 'default')

if __name__ == '__main__':
    nostest(sys.argv[1], sys.argv[2], sys.argv[3])


text:
class WordFilter
  def initialize(base = 16, lower_bound = 0, upper_case_filter = false)
    @base              = base - 10 + 97
    @lower_bound       = lower_bound
    @upper_case_filter = upper_case_filter
  end

  def pick(word)
    if word.length <= @lower_bound
      return false
    end
    if @upper_case_filter
      if word.upcase! == nil
        return false
      end
    end
    word.downcase.each_byte do |c|
      if c >= @base
        return false
      end
    end
    true
  end

end


text:
"""
taken from

http://www.djangosnippets.org/snippets/377/

and adapted to LDObject
"""

import json
from django.db import models

from . import LDObject

class LDObjectField(models.TextField):
    """
    LDObject is a generic textfield that neatly serializes/unserializes
    JSON objects seamlessly.

    deserialization_params added on 2011-01-09 to provide additional hints at deserialization time
    """

    def __init__(self, type_hint=None, **kwargs):
        self.type_hint = type_hint
        super(LDObjectField, self).__init__(**kwargs)

    def to_python(self, value):
        """Convert our string value to LDObject after we load it from the DB"""

        # did we already convert this?
        if not isinstance(value, basestring):
            return value

        return self.from_db_value(value)

    # noinspection PyUnusedLocal
    def from_db_value(self, value, *args, **kwargs):
        if value is None:
            return None

        # in some cases, we're loading an existing array or dict,
        # we skip this part but instantiate the LD object
        if isinstance(value, basestring):
            try:
                parsed_value = json.loads(value)
            except:
                raise Exception("value is not JSON parseable, that's bad news")
        else:
            parsed_value = value

        if parsed_value is not None:
            # we give the wrapped object back because we're not dealing with serialization types
            return_val = LDObject.fromDict(parsed_value, type_hint=self.type_hint).wrapped_obj
            return return_val
        else:
            return None

    def get_prep_value(self, value):
        """Convert our JSON object to a string before we save"""
        if isinstance(value, basestring):
            return value

        if value is None:
            return None

        # instantiate the proper LDObject to dump it appropriately
        ld_object = LDObject.instantiate(value, datatype=self.type_hint)
        return ld_object.serialize()

    def value_to_string(self, obj):
        value = self._get_val_from_obj(obj)
        return self.get_db_prep_value(value, None)


text:
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.idea.maven.navigator.actions;

import com.intellij.execution.RunManager;
import com.intellij.execution.RunnerAndConfigurationSettings;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.idea.maven.project.MavenProjectBundle;
import org.jetbrains.idea.maven.utils.MavenDataKeys;

/**
 * @author Sergey Evdokimov
 */
public class RemoveMavenRunConfigurationAction extends AnAction {
  @Override
  public void actionPerformed(@NotNull AnActionEvent e) {
    Project project = e.getProject();
    RunnerAndConfigurationSettings settings = e.getData(MavenDataKeys.RUN_CONFIGURATION);

    assert settings != null && project != null;

    int res = Messages
      .showYesNoDialog(project, MavenProjectBundle.message("maven.run.configuration.remove.confirm", settings.getName()), "",
                       Messages.getQuestionIcon());
    if (res == Messages.YES) {
      RunManager.getInstance(project).removeConfiguration(settings);
    }
  }

  @Override
  public void update(@NotNull AnActionEvent e) {
    Project project = e.getProject();
    RunnerAndConfigurationSettings settings = e.getData(MavenDataKeys.RUN_CONFIGURATION);

    boolean enabled = settings != null && project != null;
    e.getPresentation().setEnabledAndVisible(enabled);
  }
}


text:
Java API Dekstop Example
=========

Sample application utilizing the Pyramid Java API for Pyramid bill validators. With this API
you can quickly configure your application to operate with a bill validator. This application shows RS-232 state transition and reports the denomination of accepted notes.

This is provided as both a Netbeans and Intellij project.

## Important
If youa re using an Apex 7000 or Spectra, please make sure that all of your dip switches are in the off position. The unit msust be in RS-232 mode to use this library. For more information about configuration, please see our [faq](http://pyramidacceptors.com/support/faq/).

## Requirements
1. A supported bill validator
   - Spectra
   - Apex 7000
   - Apex 5000
   - Trilogy *requires RS-232 firmware*
   - Curve *require RS-232 firmware*
2. Communication Harness
   - [Recommended Harness](http://shop.pyramidacceptors.com/usb-rs-232-communication-cable-harness-for-apex-05aa0023/)
   - Or a DB9 RS-232 connection or USB UART cable of your choice
3. Your favorite Java editor (we use Netbeans because projects are easy to share)

## Setup
If you are using Netbeans, simply open the project and satisfy the PTalk.jar dependency. You will then be able to run and debug the application.

If you are using Intellij, the project should import and handle all of the depency stuff for you via gradle.
NOTE: When exporting the JAR, you must have the forms_rt.jar on your classpath!

## Notes for Linux users running Java 8
We have had mixed reports of this application not finding all available ports. The fix seems to be to run the app from terminal using the -jar switch

    java -jar your_app.jar

## Dependencies
If you prefer to handle your own dependencies, here is what you will need

 1. The ptalk.jar file from this project (which itself include its bundled dependencies)
 2. (log4j12-1.7.12)[http://mvnrepository.com/artifact/log4j/log4j/1.2.17]
 3. (Already in PTalk) jSSC latest

 __Please note that you may omit logging or swap out log4j for another framework.__

## Questions
Please [let us know](https://github.com/PyramidTechnologies/Java-API-desktop-sample/issues/new).

![](https://googledrive.com/host/0B79TkjL8Nm20QjU0UGhObnBTUE0/logo_2.jpg)


text:
namespace picasa {

namespace {

const int64 kPmpMaxFilesize = 50*1024*1024;  // Arbitrary maximum of 50 MB.

}  // namespace

PmpColumnReader::PmpColumnReader()
    : length_(0),
      field_type_(PMP_TYPE_INVALID),
      rows_(0) {}

PmpColumnReader::~PmpColumnReader() {}

bool PmpColumnReader::Init(const base::FilePath& filepath,
                           const PmpFieldType expected_type,
                           uint32* rows_read) {
  DCHECK(!data_.get());
  base::ThreadRestrictions::AssertIOAllowed();

  if (!file_util::GetFileSize(filepath, &length_))
    return false;

  if (length_ < kPmpHeaderSize || length_ > kPmpMaxFilesize)
    return false;

  data_.reset(new uint8[length_]);

  char* data_begin = reinterpret_cast<char*>(data_.get());

  DCHECK(length_ < kint32max);  // ReadFile expects an int.

  bool success = file_util::ReadFile(filepath, data_begin, length_) &&
                 ParseData(expected_type, rows_read);

  if (!success)
    rows_ = 0;  // If any of the reading or parsing fails, prevent Read* calls.

  return success;
}

bool PmpColumnReader::ReadString(const uint32 row, std::string* result) const {
  DCHECK(data_.get() != NULL);

  if (field_type_ != PMP_TYPE_STRING || row >= rows_)
    return false;

  DCHECK_LT(row, strings_.size());
  *result = strings_[row];
  return true;
}

bool PmpColumnReader::ReadUInt32(const uint32 row, uint32* result) const {
  DCHECK(data_.get() != NULL);

  if (field_type_ != PMP_TYPE_UINT32 || row >= rows_)
    return false;

  *result = reinterpret_cast<uint32*>(data_.get() + kPmpHeaderSize)[row];
  return true;
}

bool PmpColumnReader::ReadDouble64(const uint32 row, double* result) const {
  DCHECK(data_.get() != NULL);

  if (field_type_ != PMP_TYPE_DOUBLE64 || row >= rows_)
    return false;

  *result = reinterpret_cast<double*>(data_.get() + kPmpHeaderSize)[row];
  return true;
}

bool PmpColumnReader::ReadUInt8(const uint32 row, uint8* result) const {
  DCHECK(data_.get() != NULL);

  if (field_type_ != PMP_TYPE_UINT8 || row >= rows_)
    return false;

  *result = reinterpret_cast<uint8*>(data_.get() + kPmpHeaderSize)[row];
  return true;
}

bool PmpColumnReader::ReadUInt64(const uint32 row, uint64* result) const {
  DCHECK(data_.get() != NULL);

  if (field_type_ != PMP_TYPE_UINT64 || row >= rows_)
    return false;

  *result = reinterpret_cast<uint64*>(data_.get() + kPmpHeaderSize)[row];
  return true;
}

bool PmpColumnReader::ParseData(const PmpFieldType expected_type,
                                uint32* rows_read) {
  DCHECK(data_.get() != NULL);
  DCHECK_GE(length_, kPmpHeaderSize);

  // Check all magic bytes.
  if (memcmp(&kPmpMagic1, &data_[kPmpMagic1Offset], sizeof(kPmpMagic1)) != 0 ||
      memcmp(&kPmpMagic2, &data_[kPmpMagic2Offset], sizeof(kPmpMagic2)) != 0 ||
      memcmp(&kPmpMagic3, &data_[kPmpMagic3Offset], sizeof(kPmpMagic3)) != 0 ||
      memcmp(&kPmpMagic4, &data_[kPmpMagic4Offset], sizeof(kPmpMagic4)) != 0) {
    return false;
  }

  uint16 field_type_data =
      *(reinterpret_cast<uint16*>(&data_[kPmpFieldType1Offset]));

  // Verify if field type matches second declaration
  if (field_type_data !=
      *(reinterpret_cast<uint16*>(&data_[kPmpFieldType2Offset]))) {
    return false;
  }

  field_type_ = static_cast<PmpFieldType>(field_type_data);

  if (field_type_ != expected_type)
    return false;

  rows_ = *(reinterpret_cast<uint32*>(&data_[kPmpRowCountOffset]));

  // Sanity check against malicious row field.
  if (rows_ > (kPmpMaxFilesize - kPmpHeaderSize))
    return false;

  DCHECK_GE(length_, kPmpHeaderSize);
  int64 body_length = length_ - kPmpHeaderSize;
  int64 expected_body_length = 0;
  switch (field_type_) {
    case PMP_TYPE_STRING:
      expected_body_length = IndexStrings();
      break;
    case PMP_TYPE_UINT32:
      expected_body_length = static_cast<int64>(rows_) * sizeof(uint32);
      break;
    case PMP_TYPE_DOUBLE64:
      expected_body_length = static_cast<int64>(rows_) * sizeof(double);
      break;
    case PMP_TYPE_UINT8:
      expected_body_length = static_cast<int64>(rows_) * sizeof(uint8);
      break;
    case PMP_TYPE_UINT64:
      expected_body_length = static_cast<int64>(rows_) * sizeof(uint64);
      break;
    default:
      return false;
      break;
  }

  if (body_length == expected_body_length && rows_read)
    *rows_read = rows_;
  return body_length == expected_body_length;
}

int64 PmpColumnReader::IndexStrings() {
  DCHECK(data_.get() != NULL);
  DCHECK_GE(length_, kPmpHeaderSize);

  strings_.reserve(rows_);

  int64 bytes_parsed = kPmpHeaderSize;
  const uint8* data_cursor = data_.get() + kPmpHeaderSize;

  while (strings_.size() < rows_) {
    const uint8* string_end = static_cast<const uint8*>(
        memchr(data_cursor, '\0', length_ - bytes_parsed));

    // Fail if cannot find null termination. String runs on past file end.
    if (string_end == NULL)
      return -1;

    // Length of string. (+1 to include the termination character).
    ptrdiff_t length_in_bytes = string_end - data_cursor + 1;

    strings_.push_back(reinterpret_cast<const char*>(data_cursor));
    data_cursor += length_in_bytes;
    bytes_parsed += length_in_bytes;
  }

  return bytes_parsed - kPmpHeaderSize;
}

}  // namespace picasa


text:
package com.family.service.bean;

import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;

import com.family.db.domain.MoneyTransactionTypeDomain;
import com.family.enums.StandardMoneyTransactionEnum;

public class MoneyTransactionTypeBean {

	private long id;

	private String name;

	private String ioe;

	private Boolean active;

	private long familyId;

	public MoneyTransactionTypeBean() {}

	public MoneyTransactionTypeBean(StandardMoneyTransactionEnum smte) {
		this.id = smte.getId();
		this.name = smte.name();
		this.ioe = smte.getIoe().name();
		this.active = smte.isActive();
		this.familyId = smte.getFamilyId();
	}

	public MoneyTransactionTypeBean(MoneyTransactionTypeDomain domain) {
		this.setId(Long.parseLong(domain.getId()));
		this.setFamilyId(Long.parseLong(domain.getFamilyId()));
		this.setActive(Boolean.parseBoolean(domain.getActive()));
		this.setIoe(domain.getIoe());
		this.setName(domain.getName());
	}

	public String getName() {
		return name;
	}

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

	public long getId() {
		return id;
	}

	public void setId(long id) {
		this.id = id;
	}

	public String getIoe() {
		return ioe;
	}

	public void setIoe(String ioe) {
		this.ioe = ioe;
	}

	public Boolean getActive() {
		return active;
	}

	public void setActive(Boolean active) {
		this.active = active;
	}

	public long getFamilyId() {
		return familyId;
	}

	public void setFamilyId(long familyId) {
		this.familyId = familyId;
	}

	@Override
	public int hashCode() {
		return HashCodeBuilder.reflectionHashCode(this);
	}

	@Override
	public boolean equals(Object obj) {
		return EqualsBuilder.reflectionEquals(this, obj);
	}

	@Override
	public String toString() {
		return ToStringBuilder.reflectionToString(this);
	}

}


text:
package org.support.project.knowledge.logic.notification;

import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;

import org.support.project.common.log.Log;
import org.support.project.common.log.LogFactory;
import org.support.project.di.Container;
import org.support.project.di.DI;
import org.support.project.di.Instance;
import org.support.project.knowledge.entity.EventsEntity;
import org.support.project.knowledge.entity.KnowledgeItemValuesEntity;
import org.support.project.knowledge.entity.KnowledgesEntity;

@DI(instance = Instance.Singleton)
public class EventNotificationByWeek extends AbstractEventNotification {
    /** ログ */
    private static final Log LOG = LogFactory.getLog(EventNotificationByWeek.class);
    /** インスタンス取得 */
    public static EventNotificationByWeek get() {
        return Container.getComp(EventNotificationByWeek.class);
    }
    @Override
    public void notify(EventsEntity event, KnowledgesEntity knowledge, List<KnowledgeItemValuesEntity> values, Calendar now) {
        int timing = NOTIFY_STATUS_BEFORE_WEEK;
        if (event.getNotifyStatus() >= timing) {
            // 既に通知済
            return;
        }
        //日曜日?(イベントのタイムゾーンで)
        TimeZone timezone = TimeZone.getTimeZone(event.getTimeZone());
        Calendar today = Calendar.getInstance(timezone);
        today.setTimeInMillis(now.getTimeInMillis());
        if (today.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY) {
            // 日曜日でない場合は通知しない
            return;
        }
        LOG.info("イベントのメール通知 [ID] " + knowledge.getKnowledgeId() + " [Timing] 今週開催");
        sendNotify(event, knowledge, values, timing);
    }

}


text:
@implementation NotificationConst

NSString *const IS_EYE_PASSWORD_SHOW = @"IS_EYE_PASSWORD_SHOW";
NSString *const USER_TOKEN = @"USER_TOKEN";

@end


text:
require 'benchmark'
require 'zlib'
require 'active_support/core_ext/array/extract_options'
require 'active_support/core_ext/array/wrap'
require 'active_support/core_ext/benchmark'
require 'active_support/core_ext/exception'
require 'active_support/core_ext/class/attribute_accessors'
require 'active_support/core_ext/numeric/bytes'
require 'active_support/core_ext/numeric/time'
require 'active_support/core_ext/object/to_param'
require 'active_support/core_ext/string/inflections'

module ActiveSupport
  # See ActiveSupport::Cache::Store for documentation.
  module Cache
    autoload :FileStore, 'active_support/cache/file_store'
    autoload :MemoryStore, 'active_support/cache/memory_store'
    autoload :MemCacheStore, 'active_support/cache/mem_cache_store'
    autoload :SynchronizedMemoryStore, 'active_support/cache/synchronized_memory_store'
    autoload :CompressedMemCacheStore, 'active_support/cache/compressed_mem_cache_store'

    # These options mean something to all cache implementations. Individual cache
    # implementations may support additional options.
    UNIVERSAL_OPTIONS = [:namespace, :compress, :compress_threshold, :expires_in, :race_condition_ttl]

    module Strategy
      autoload :LocalCache, 'active_support/cache/strategy/local_cache'
    end

    # Creates a new CacheStore object according to the given options.
    #
    # If no arguments are passed to this method, then a new
    # ActiveSupport::Cache::MemoryStore object will be returned.
    #
    # If you pass a Symbol as the first argument, then a corresponding cache
    # store class under the ActiveSupport::Cache namespace will be created.
    # For example:
    #
    #   ActiveSupport::Cache.lookup_store(:memory_store)
    #   # => returns a new ActiveSupport::Cache::MemoryStore object
    #
    #   ActiveSupport::Cache.lookup_store(:mem_cache_store)
    #   # => returns a new ActiveSupport::Cache::MemCacheStore object
    #
    # Any additional arguments will be passed to the corresponding cache store
    # class's constructor:
    #
    #   ActiveSupport::Cache.lookup_store(:file_store, "/tmp/cache")
    #   # => same as: ActiveSupport::Cache::FileStore.new("/tmp/cache")
    #
    # If the first argument is not a Symbol, then it will simply be returned:
    #
    #   ActiveSupport::Cache.lookup_store(MyOwnCacheStore.new)
    #   # => returns MyOwnCacheStore.new
    def self.lookup_store(*store_option)
      store, *parameters = *Array.wrap(store_option).flatten

      case store
      when Symbol
        store_class_name = store.to_s.camelize
        store_class =
          begin
            require "active_support/cache/#{store}"
          rescue LoadError => e
            raise "Could not find cache store adapter for #{store} (#{e})"
          else
            ActiveSupport::Cache.const_get(store_class_name)
          end
        store_class.new(*parameters)
      when nil
        ActiveSupport::Cache::MemoryStore.new
      else
        store
      end
    end

    def self.expand_cache_key(key, namespace = nil)
      expanded_cache_key = namespace ? "#{namespace}/" : ""

      prefix = ENV["RAILS_CACHE_ID"] || ENV["RAILS_APP_VERSION"]
      if prefix
        expanded_cache_key << "#{prefix}/"
      end

      expanded_cache_key <<
        if key.respond_to?(:cache_key)
          key.cache_key
        elsif key.is_a?(Array)
          if key.size > 1
            key.collect { |element| expand_cache_key(element) }.to_param
          else
            key.first.to_param
          end
        elsif key
          key.to_param
        end.to_s

      expanded_cache_key
    end

    # An abstract cache store class. There are multiple cache store
    # implementations, each having its own additional features. See the classes
    # under the ActiveSupport::Cache module, e.g.
    # ActiveSupport::Cache::MemCacheStore. MemCacheStore is currently the most
    # popular cache store for large production websites.
    #
    # Some implementations may not support all methods beyond the basic cache
    # methods of +fetch+, +write+, +read+, +exist?+, and +delete+.
    #
    # ActiveSupport::Cache::Store can store any serializable Ruby object.
    #
    #   cache = ActiveSupport::Cache::MemoryStore.new
    #
    #   cache.read("city")   # => nil
    #   cache.write("city", "Duckburgh")
    #   cache.read("city")   # => "Duckburgh"
    #
    # Keys are always translated into Strings and are case sensitive. When an
    # object is specified as a key, its +cache_key+ method will be called if it
    # is defined. Otherwise, the +to_param+ method will be called. Hashes and
    # Arrays can be used as keys. The elements will be delimited by slashes
    # and Hashes elements will be sorted by key so they are consistent.
    #
    #   cache.read("city") == cache.read(:city)   # => true
    #
    # Nil values can be cached.
    #
    # If your cache is on a shared infrastructure, you can define a namespace for
    # your cache entries. If a namespace is defined, it will be prefixed on to every
    # key. The namespace can be either a static value or a Proc. If it is a Proc, it
    # will be invoked when each key is evaluated so that you can use application logic
    # to invalidate keys.
    #
    #   cache.namespace = lambda { @last_mod_time }  # Set the namespace to a variable
    #   @last_mod_time = Time.now  # Invalidate the entire cache by changing namespace
    #
    #
    # Caches can also store values in a compressed format to save space and reduce
    # time spent sending data. Since there is some overhead, values must be large
    # enough to warrant compression. To turn on compression either pass
    # <tt>:compress => true</tt> in the initializer or to +fetch+ or +write+.
    # To specify the threshold at which to compress values, set
    # <tt>:compress_threshold</tt>. The default threshold is 32K.
    class Store

      cattr_accessor :logger, :instance_writer => true

      attr_reader :silence, :options
      alias :silence? :silence

      # Create a new cache. The options will be passed to any write method calls except
      # for :namespace which can be used to set the global namespace for the cache.
      def initialize (options = nil)
        @options = options ? options.dup : {}
      end

      # Silence the logger.
      def silence!
        @silence = true
        self
      end

      # Silence the logger within a block.
      def mute
        previous_silence, @silence = defined?(@silence) && @silence, true
        yield
      ensure
        @silence = previous_silence
      end

      # Set to true if cache stores should be instrumented. Default is false.
      def self.instrument=(boolean)
        Thread.current[:instrument_cache_store] = boolean
      end

      def self.instrument
        Thread.current[:instrument_cache_store] || false
      end

      # Fetches data from the cache, using the given key. If there is data in
      # the cache with the given key, then that data is returned.
      #
      # If there is no such data in the cache (a cache miss occurred),
      # then nil will be returned. However, if a block has been passed, then
      # that block will be run in the event of a cache miss. The return value
      # of the block will be written to the cache under the given cache key,
      # and that return value will be returned.
      #
      #   cache.write("today", "Monday")
      #   cache.fetch("today")  # => "Monday"
      #
      #   cache.fetch("city")   # => nil
      #   cache.fetch("city") do
      #     "Duckburgh"
      #   end
      #   cache.fetch("city")   # => "Duckburgh"
      #
      # You may also specify additional options via the +options+ argument.
      # Setting <tt>:force => true</tt> will force a cache miss:
      #
      #   cache.write("today", "Monday")
      #   cache.fetch("today", :force => true)  # => nil
      #
      # Setting <tt>:compress</tt> will store a large cache entry set by the call
      # in a compressed format.
      #
      #
      # Setting <tt>:expires_in</tt> will set an expiration time on the cache. All caches
      # support auto expiring content after a specified number of seconds. This value can
      # be specified as an option to the construction in which call all entries will be
      # affected. Or it can be supplied to the +fetch+ or +write+ method for just one entry.
      #
      #   cache = ActiveSupport::Cache::MemoryStore.new(:expires_in => 5.minutes)
      #   cache.write(key, value, :expires_in => 1.minute)  # Set a lower value for one entry
      #
      # Setting <tt>:race_condition_ttl</tt> is very useful in situations where a cache entry
      # is used very frequently and is under heavy load. If a cache expires and due to heavy load
      # seven different processes will try to read data natively and then they all will try to
      # write to cache. To avoid that case the first process to find an expired cache entry will
      # bump the cache expiration time by the value set in <tt>:race_condition_ttl</tt>. Yes
      # this process is extending the time for a stale value by another few seconds. Because
      # of extended life of the previous cache, other processes will continue to use slightly
      # stale data for a just a big longer. In the meantime that first process will go ahead
      # and will write into cache the new value. After that all the processes will start
      # getting new value. The key is to keep <tt>:race_condition_ttl</tt> small.
      #
      # If the process regenerating the entry errors out, the entry will be regenerated
      # after the specified number of seconds. Also note that the life of stale cache is
      # extended only if it expired recently. Otherwise a new value is generated and
      # <tt>:race_condition_ttl</tt> does not play any role.
      #
      #   # Set all values to expire after one minute.
      #   cache = ActiveSupport::Cache::MemoryStore.new(:expires_in => 1.minute)
      #
      #   cache.write("foo", "original value")
      #   val_1 = nil
      #   val_2 = nil
      #   sleep 60
      #
      #   Thread.new do
      #     val_1 = cache.fetch("foo", :race_condition_ttl => 10) do
      #       sleep 1
      #       "new value 1"
      #     end
      #   end
      #
      #   Thread.new do
      #     val_2 = cache.fetch("foo", :race_condition_ttl => 10) do
      #       "new value 2"
      #     end
      #   end
      #
      #   # val_1 => "new value 1"
      #   # val_2 => "original value"
      #   # sleep 10 # First thread extend the life of cache by another 10 seconds
      #   # cache.fetch("foo") => "new value 1"
      #
      # Other options will be handled by the specific cache store implementation.
      # Internally, #fetch calls #read_entry, and calls #write_entry on a cache miss.
      # +options+ will be passed to the #read and #write calls.
      #
      # For example, MemCacheStore's #write method supports the +:raw+
      # option, which tells the memcached server to store all values as strings.
      # We can use this option with #fetch too:
      #
      #   cache = ActiveSupport::Cache::MemCacheStore.new
      #   cache.fetch("foo", :force => true, :raw => true) do
      #     :bar
      #   end
      #   cache.fetch("foo")  # => "bar"
      def fetch(name, options = nil)
        if block_given?
          options = merged_options(options)
          key = namespaced_key(name, options)
          unless options[:force]
            entry = instrument(:read, name, options) do |payload|
              payload[:super_operation] = :fetch if payload
              read_entry(key, options)
            end
          end
          if entry && entry.expired?
            race_ttl = options[:race_condition_ttl].to_f
            if race_ttl and Time.now.to_f - entry.expires_at <= race_ttl
              entry.expires_at = Time.now + race_ttl
              write_entry(key, entry, :expires_in => race_ttl * 2)
            else
              delete_entry(key, options)
            end
            entry = nil
          end

          if entry
            instrument(:fetch_hit, name, options) { |payload| }
            entry.value
          else
            result = instrument(:generate, name, options) do |payload|
              yield
            end
            write(name, result, options)
            result
          end
        else
          read(name, options)
        end
      end

      # Fetches data from the cache, using the given key. If there is data in
      # the cache with the given key, then that data is returned. Otherwise,
      # nil is returned.
      #
      # Options are passed to the underlying cache implementation.
      def read(name, options = nil)
        options = merged_options(options)
        key = namespaced_key(name, options)
        instrument(:read, name, options) do |payload|
          entry = read_entry(key, options)
          if entry
            if entry.expired?
              delete_entry(key, options)
              payload[:hit] = false if payload
              nil
            else
              payload[:hit] = true if payload
              entry.value
            end
          else
            payload[:hit] = false if payload
            nil
          end
        end
      end

      # Read multiple values at once from the cache. Options can be passed
      # in the last argument.
      #
      # Some cache implementation may optimize this method.
      #
      # Returns a hash mapping the names provided to the values found.
      def read_multi(*names)
        options = names.extract_options!
        options = merged_options(options)
        results = {}
        names.each do |name|
          key = namespaced_key(name, options)
          entry = read_entry(key, options)
          if entry
            if entry.expired?
              delete_entry(key, options)
            else
              results[name] = entry.value
            end
          end
        end
        results
      end

      # Writes the value to the cache, with the key.
      #
      # Options are passed to the underlying cache implementation.
      def write(name, value, options = nil)
        options = merged_options(options)
        instrument(:write, name, options) do |payload|
          entry = Entry.new(value, options)
          write_entry(namespaced_key(name, options), entry, options)
        end
      end

      # Deletes an entry in the cache. Returns +true+ if an entry is deleted.
      #
      # Options are passed to the underlying cache implementation.
      def delete(name, options = nil)
        options = merged_options(options)
        instrument(:delete, name) do |payload|
          delete_entry(namespaced_key(name, options), options)
        end
      end

      # Return true if the cache contains an entry for the given key.
      #
      # Options are passed to the underlying cache implementation.
      def exist?(name, options = nil)
        options = merged_options(options)
        instrument(:exist?, name) do |payload|
          entry = read_entry(namespaced_key(name, options), options)
          if entry && !entry.expired?
            true
          else
            false
          end
        end
      end

      # Delete all entries with keys matching the pattern.
      #
      # Options are passed to the underlying cache implementation.
      #
      # All implementations may not support this method.
      def delete_matched(matcher, options = nil)
        raise NotImplementedError.new("#{self.class.name} does not support delete_matched")
      end

      # Increment an integer value in the cache.
      #
      # Options are passed to the underlying cache implementation.
      #
      # All implementations may not support this method.
      def increment(name, amount = 1, options = nil)
        raise NotImplementedError.new("#{self.class.name} does not support increment")
      end

      # Increment an integer value in the cache.
      #
      # Options are passed to the underlying cache implementation.
      #
      # All implementations may not support this method.
      def decrement(name, amount = 1, options = nil)
        raise NotImplementedError.new("#{self.class.name} does not support decrement")
      end

      # Cleanup the cache by removing expired entries.
      #
      # Options are passed to the underlying cache implementation.
      #
      # All implementations may not support this method.
      def cleanup(options = nil)
        raise NotImplementedError.new("#{self.class.name} does not support cleanup")
      end

      # Clear the entire cache. Be careful with this method since it could
      # affect other processes if shared cache is being used.
      #
      # Options are passed to the underlying cache implementation.
      #
      # All implementations may not support this method.
      def clear(options = nil)
        raise NotImplementedError.new("#{self.class.name} does not support clear")
      end

      protected
        # Add the namespace defined in the options to a pattern designed to match keys.
        # Implementations that support delete_matched should call this method to translate
        # a pattern that matches names into one that matches namespaced keys.
        def key_matcher(pattern, options)
          prefix = options[:namespace].is_a?(Proc) ? options[:namespace].call : options[:namespace]
          if prefix
            source = pattern.source
            if source.start_with?('^')
              source = source[1, source.length]
            else
              source = ".*#{source[0, source.length]}"
            end
            Regexp.new("^#{Regexp.escape(prefix)}:#{source}", pattern.options)
          else
            pattern
          end
        end

        # Read an entry from the cache implementation. Subclasses must implement this method.
        def read_entry(key, options) # :nodoc:
          raise NotImplementedError.new
        end

        # Write an entry to the cache implementation. Subclasses must implement this method.
        def write_entry(key, entry, options) # :nodoc:
          raise NotImplementedError.new
        end

        # Delete an entry from the cache implementation. Subclasses must implement this method.
        def delete_entry(key, options) # :nodoc:
          raise NotImplementedError.new
        end

      private
        # Merge the default options with ones specific to a method call.
        def merged_options(call_options) # :nodoc:
          if call_options
            options.merge(call_options)
          else
            options.dup
          end
        end

        # Expand key to be a consistent string value. Invoke +cache_key+ if
        # object responds to +cache_key+. Otherwise, to_param method will be
        # called. If the key is a Hash, then keys will be sorted alphabetically.
        def expanded_key(key) # :nodoc:
          return key.cache_key.to_s if key.respond_to?(:cache_key)

          case key
          when Array
            if key.size > 1
              key = key.collect{|element| expanded_key(element)}
            else
              key = key.first
            end
          when Hash
            key = key.sort_by { |k,_| k.to_s }.collect{|k,v| "#{k}=#{v}"}
          end

          key.to_param
        end

        # Prefix a key with the namespace. Namespace and key will be delimited with a colon.
        def namespaced_key(key, options)
          key = expanded_key(key)
          namespace = options[:namespace] if options
          prefix = namespace.is_a?(Proc) ? namespace.call : namespace
          key = "#{prefix}:#{key}" if prefix
          key
        end

        def instrument(operation, key, options = nil)
          log(operation, key, options)

          if self.class.instrument
            payload = { :key => key }
            payload.merge!(options) if options.is_a?(Hash)
            ActiveSupport::Notifications.instrument("cache_#{operation}.active_support", payload){ yield(payload) }
          else
            yield(nil)
          end
        end

        def log(operation, key, options = nil)
          return unless logger && logger.debug? && !silence?
          logger.debug("Cache #{operation}: #{key}#{options.blank? ? "" : " (#{options.inspect})"}")
        end
    end

    # Entry that is put into caches. It supports expiration time on entries and can compress values
    # to save space in the cache.
    class Entry
      attr_reader :created_at, :expires_in

      DEFAULT_COMPRESS_LIMIT = 16.kilobytes

      class << self
        # Create an entry with internal attributes set. This method is intended to be
        # used by implementations that store cache entries in a native format instead
        # of as serialized Ruby objects.
        def create (raw_value, created_at, options = {})
          entry = new(nil)
          entry.instance_variable_set(:@value, raw_value)
          entry.instance_variable_set(:@created_at, created_at.to_f)
          entry.instance_variable_set(:@compressed, !!options[:compressed])
          entry.instance_variable_set(:@expires_in, options[:expires_in])
          entry
        end
      end

      # Create a new cache entry for the specified value. Options supported are
      # +:compress+, +:compress_threshold+, and +:expires_in+.
      def initialize(value, options = {})
        @compressed = false
        @expires_in = options[:expires_in]
        @expires_in = @expires_in.to_f if @expires_in
        @created_at = Time.now.to_f
        if value
          if should_compress?(value, options)
            @value = Zlib::Deflate.deflate(Marshal.dump(value))
            @compressed = true
          else
            @value = value
          end
        else
          @value = nil
        end
      end

      # Get the raw value. This value may be serialized and compressed.
      def raw_value
        @value
      end

      # Get the value stored in the cache.
      def value
        if @value
          val = compressed? ? Marshal.load(Zlib::Inflate.inflate(@value)) : @value
          unless val.frozen?
            val.freeze rescue nil
          end
          val
        end
      end

      def compressed?
        @compressed
      end

      # Check if the entry is expired. The +expires_in+ parameter can override the
      # value set when the entry was created.
      def expired?
        @expires_in && @created_at + @expires_in <= Time.now.to_f
      end

      # Set a new time when the entry will expire.
      def expires_at=(time)
        if time
          @expires_in = time.to_f - @created_at
        else
          @expires_in = nil
        end
      end

      # Seconds since the epoch when the entry will expire.
      def expires_at
        @expires_in ? @created_at + @expires_in : nil
      end

      # Returns the size of the cached value. This could be less than value.size
      # if the data is compressed.
      def size
        if @value.nil?
          0
        elsif @value.respond_to?(:bytesize)
          @value.bytesize
        else
          Marshal.dump(@value).bytesize
        end
      end

      private
        def should_compress?(value, options)
          if options[:compress] && value
            unless value.is_a?(Numeric)
              compress_threshold = options[:compress_threshold] || DEFAULT_COMPRESS_LIMIT
              serialized_value = value.is_a?(String) ? value : Marshal.dump(value)
              return true if serialized_value.size >= compress_threshold
            end
          end
          false
        end
    end
  end
end


text:
namespace CodedViews.Html.Constants
{
    /// <summary>
    /// Specifies the type of Button it refers to
    /// </summary>
    public sealed class FormButtonType : SimpleStringEnum
    {
        /// <summary>
        /// This is hidden for instantiation because this is predefined
        /// </summary>
        /// <param name="value"></param>
        internal FormButtonType(string value) : base(value)
        {
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.nps.micro"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="19" />
    <uses-feature android:name="android.hardware.usb.host" />
    <uses-permission android:name="android.permission.USB_PERMISSION" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <application
        android:largeHeap="true"
        android:allowBackup="true"
        android:debuggable="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">
        <activity
            android:launchMode="singleInstance"
            android:name="com.nps.micro.MainActivity"
            android:label="@string/app_name"
            android:configChanges="orientation|screenSize"
            android:windowSoftInputMode="stateHidden">
            <intent-filter>
                <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
<!-- Opens application if USB device was connected -->
<!--             <meta-data -->
<!--                 android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" -->
<!--                 android:resource="@xml/olimex_sam3s" /> -->
<!--             <meta-data -->
<!--                 android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" -->
<!--                 android:resource="@xml/olimex_sam7s" /> -->
        </activity>

        <activity android:name="com.nps.micro.UserPreferenceActivity"></activity>

        <service
            android:name="UsbService"
            android:icon="@drawable/ic_launcher"
            android:label="@string/service_name" />
    </application>

</manifest>


text:
package com.alibaba.otter.manager.web.home.module.screen.api;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang.StringUtils;

import com.alibaba.citrus.turbine.dataresolver.Param;
import com.alibaba.otter.manager.biz.config.channel.ChannelService;
import com.alibaba.otter.manager.biz.remote.NodeRemoteService;
import com.alibaba.otter.shared.arbitrate.ArbitrateManageService;
import com.alibaba.otter.shared.common.model.config.channel.Channel;
import com.alibaba.otter.shared.common.model.config.channel.ChannelStatus;

public class NodeOp extends AbstractJsonScreen<String> {

    private final static String    ONLINE  = "online";

    private final static String    OFFLINE = "offline";

    private final static String    THREAD  = "thread";
    private final static String    PROFILE = "profile";

    @Resource(name = "channelService")
    private ChannelService         channelService;

    @Resource(name = "arbitrateManageService")
    private ArbitrateManageService arbitrateManageService;

    @Resource(name = "nodeRemoteService")
    private NodeRemoteService      nodeRemoteService;

    public void execute(@Param("nid") Long nid, @Param("command") String command, @Param("value") String value) {
        try {
            if (StringUtils.equalsIgnoreCase(command, OFFLINE)) {
                List<Channel> channels = channelService.listByNodeId(nid, ChannelStatus.START);
                for (Channel channel : channels) {// 重启一下对应的channel
                    boolean result = arbitrateManageService.channelEvent().restart(channel.getId());
                    if (result) {
                        channelService.notifyChannel(channel.getId());// 推送一下配置
                    }
                }
            } else if (StringUtils.equalsIgnoreCase(command, ONLINE)) {
                // doNothing,自动会加入服务列表
            } else if (StringUtils.endsWithIgnoreCase(command, THREAD)) {
                nodeRemoteService.setThreadPoolSize(nid, Integer.valueOf(value));
            } else if (StringUtils.endsWithIgnoreCase(command, PROFILE)) {
                nodeRemoteService.setProfile(nid, BooleanUtils.toBoolean(value));
            } else {
                returnError("please add specfy the 'command' param.");
                return;
            }

            returnSuccess();
        } catch (Exception e) {
            String errorMsg = String.format("error happens while [%s] with node id [%d]", command, nid);
            log.error(errorMsg, e);
            returnError(errorMsg);
        }
    }
}


text:
This document outlines the process for bumping the major version of Chef Infra Client for the yearly release.

## Preparing Ohai

Chef consumes Ohai from GitHub as both a runtime dependency and a testing dependency for Test Kitchen validations in Buildkite. Ohai's version is tightly coupled to that of Chef Infra Client so the first step in bumping the major release in the chef/chef repo is to bump the major version of Ohai.

### Create a new stable branch of Ohai

On your local machine fork the current master branch to a new stable branch. For example: `git checkout -b 15-stable`. You'll then want to edit the Expeditor config.yml file to update the branch configs like this:

https://github.com/chef/ohai/commit/ad208165619425dd7886b2de3f168b49ded25146

With the expeditor config complete push the branch `git push --set-upstream origin 15-stable`

### Bump Ohai master to the new major version

Create a PR which:

- Edits the `VERSION` file in the root of the repository to the new major release
- Updates the `chef-config` dependency to allow for the new major release of Chef Infra in `ohai.gemspec`

## Fork Chef master to a stable branch

Before bumping the major version of Chef Infra we want to fork off the current master to a new stable branch, which will be used to build hotfix releases. We support the N-1 version of Chef Infra Client for a year after the release of a new major version. For example Chef Infra Client 16 was released in April 2020, at which point Chef Infra Client 15 became the N-1 release. Chef Infra Client 15 will then be maintained with critical bug and security fixes until April 2021.

On your local machine fork the current master branch to a new stable branch. For example: `git checkout -b chef-15` and `git push --set-upstream origin chef-15`, which can then be pushed up to GitHub.

### Create a branch to fixup your new stable branch for release

Once you've forked to a new stable branch such as `chef-15` you'll want to create a new branch so you can build a PR, which will get this branch ready for release:

- In ./expeditor/config.yml add the version_constraint for the new branch, update the version_constrant for master to match the new major version, and remove all the update_dep.sh subscriptions which don't work against stable branches.
- In readme.md update the buildkite badge to point to the new stable branch image and link instead of pointing to master.
- In kitchen-tests/Gemfile update the Ohai branch to point to the new Ohai stable
- In kitchen-tests/kitchen.yml update chef_version to be your new stable version and not current. Ex: 15
- In tasks/bin/run_external_test update the ohai branch to point to your new stable ohai branch
- In Gemfile set ohai to pull from the ohai stable branch
- Run `rake dependencies:update`

Example PR for Chef 15: https://github.com/chef/chef/pull/9236

## Bump master for the new major release

Create a PR that performs the following:

- Update the version in the VERSION file
- Update chef.gemspec to point to the new ohai major release
- Update .expeditor/config.yml to include the new version_constraints you setup on your stable branch and an updated project alias
- run `rake dependencies:update`


text:
<?php

namespace Donatorsky\StringBuilder\Tests;

use Donatorsky\StringBuilder\StringBuilder;
use PHPUnit\Framework\TestCase;

class StringBuilderSetLengthTest extends TestCase
{

    /**
     * @return array
     */
    public function shortenStringsProvider(): array
    {
        return [
            // ASCII
            [
                'Lorem ipsum dolor sit amet',
                17,
                'Lorem ipsum dolor',
            ],

            // Multi-byte
            [
                'Ведь это невозможно.',
                15,
                'Ведь это',
            ],
            [
                'Zażółć gęślą jaźń',
                19,
                'Zażółć gęślą',
            ],
        ];
    }

    /**
     * Test for setting string length shorter than original.
     *
     * @dataProvider shortenStringsProvider
     *
     * @covers       \Donatorsky\StringBuilder\AbstractStringBuilder::__toString()
     * @covers       \Donatorsky\StringBuilder\StringBuilder::setLength()
     * @covers       \Donatorsky\StringBuilder\StringBuilder::length()
     * @covers       \Donatorsky\StringBuilder\StringBuilder::capacity()
     *
     * @param string $string  The string
     * @param int    $length  Length of new string
     * @param string $shorten The shorten string
     */
    public function testSetLengthToShortenString(string $string, int $length, string $shorten)
    {
        $builder = new StringBuilder($string, 1024);

        $capacity = $builder->capacity();
        $again_builder = $builder->setLength($length);

        self::assertInstanceOf(StringBuilder::class, $again_builder);
        self::assertSame($builder, $again_builder);
        self::assertSame($shorten, $builder->__toString());
        self::assertEquals($length, $builder->length());
        self::assertEquals($capacity, $builder->capacity());
    }

    /**
     * Test for setting string length greater than original.
     *
     * @dataProvider shortenStringsProvider
     *
     * @covers       \Donatorsky\StringBuilder\AbstractStringBuilder::__toString()
     * @covers       \Donatorsky\StringBuilder\StringBuilder::setLength()
     * @covers       \Donatorsky\StringBuilder\StringBuilder::length()
     * @covers       \Donatorsky\StringBuilder\StringBuilder::capacity()
     *
     * @param string $string The string
     */
    public function testSetLengthToLengthenString(string $string)
    {
        $builder = new StringBuilder($string, 50, 32);

        $again_builder = $builder->setLength(100);
        $full = $string . str_repeat(StringBuilder::NULL_CHAR, 100 - strlen($string));

        self::assertInstanceOf(StringBuilder::class, $again_builder);
        self::assertSame($builder, $again_builder);
        self::assertSame($full, $builder->__toString());
        self::assertEquals(100, $builder->length());
        self::assertEquals(128, $builder->capacity());
    }

    /**
     * Test for setting string length negative.
     *
     * @dataProvider             shortenStringsProvider
     *
     * @covers                   \Donatorsky\StringBuilder\StringBuilder::setLength()
     * @expectedException        \OutOfBoundsException
     * @expectedExceptionMessage New string length cannot be negative
     *
     * @param string $string The string
     */
    public function testSetNegativeLength(string $string)
    {
        $builder = new StringBuilder($string, 50, 32);

        $builder->setLength(-3);
    }
}


text:
/* { dg-do compile } */
/* { dg-options "-O1 -fdump-tree-dom3" } */

extern void abort (void);

union tree_node;
typedef union tree_node *tree;
extern const char tree_code_type[];

union tree_node
{
  int code;
  long pointer_alias_set;
};

long
get_alias_set (t)
     tree t;
{
  if (tree_code_type[t->code])
    abort ();
  if (t->pointer_alias_set)
    {
      tree __t = t;
      if (tree_code_type[__t->code])
	abort ();
    }
}

/* There should be precisely one load of {t,__t}->code.  If there is
   more than one, then the dominator optimizations failed.  */
/* { dg-final { scan-tree-dump-times "->code" 1 "dom3"} } */

/* There should be precisely one load of tree_code_type.  If there is
   more than one, then the dominator optimizations failed.  */
/* { dg-final { scan-tree-dump-times "tree_code_type" 1 "dom3"} } */

/* There should be one IF conditional.  If 'tree_code_type[t->code]' is
   zero, then the third if() conditional is unnecessary.  That should cause
   the call to abort() to be removed, which in turn causes the whole second
   if() to disappear.  */
/* { dg-final { scan-tree-dump-times "if " 1 "dom3"} } */

/* { dg-final { cleanup-tree-dump "dom3" } } */


text:
using namespace boost::multiprecision;

#ifdef BOOST_MSVC
#pragma warning(disable : 4127)
#endif

template <class T>
T generate_random()
{
   typedef int                   e_type;
   static boost::random::mt19937 gen;
   T                             val      = gen();
   T                             prev_val = -1;
   while (val != prev_val)
   {
      val *= (gen.max)();
      prev_val = val;
      val += gen();
   }
   e_type e;
   val = frexp(val, &e);

   static boost::random::uniform_int_distribution<e_type> ui(-20, 20);
   return ldexp(val, ui(gen));
}

template <class From, class To>
void test_convert_neg_int(From from, const std::integral_constant<bool, true>&)
{
   from = -from;
   To t3(from);
   To t4 = from.template convert_to<To>();
   BOOST_CHECK_EQUAL(From(trunc(from)), From(t3));
   BOOST_CHECK_EQUAL(From(trunc(from)), From(t4));
}
template <class From, class To>
void test_convert_neg_int(From const&, const std::integral_constant<bool, false>&)
{
}

template <class From, class To>
void test_convert_imp(std::integral_constant<int, number_kind_floating_point> const&, std::integral_constant<int, number_kind_integer> const&)
{
   for (unsigned i = 0; i < 100; ++i)
   {
      From from = generate_random<From>();
      To   t1(from);
      To   t2 = from.template convert_to<To>();
      BOOST_CHECK_EQUAL(From(trunc(from)), From(t1));
      BOOST_CHECK_EQUAL(From(trunc(from)), From(t2));
      test_convert_neg_int<From, To>(from, std::integral_constant<bool, std::numeric_limits<From>::is_signed && std::numeric_limits<To>::is_signed > ());
   }
}

template <class From, class To>
void test_convert_neg_rat(From from, const std::integral_constant<bool, true>&)
{
   from = -from;
   To   t3(from);
   To   t4  = from.template convert_to<To>();
   From tol = std::numeric_limits<From>::epsilon();
   BOOST_CHECK_CLOSE_FRACTION(From(t3), from, tol);
   BOOST_CHECK_CLOSE_FRACTION(From(t4), from, tol);
}
template <class From, class To>
void test_convert_rat_int(From const&, const std::integral_constant<bool, false>&)
{
}

template <class From, class To>
void test_convert_imp(std::integral_constant<int, number_kind_floating_point> const&, std::integral_constant<int, number_kind_rational> const&)
{
   for (unsigned i = 0; i < 100; ++i)
   {
      From from = generate_random<From>();
      To   t1(from);
      To   t2  = from.template convert_to<To>();
      From tol = std::numeric_limits<From>::epsilon();
      BOOST_CHECK_CLOSE_FRACTION(From(t1), from, tol);
      BOOST_CHECK_CLOSE_FRACTION(From(t2), from, tol);
      test_convert_neg_rat<From, To>(from, std::integral_constant<bool, std::numeric_limits<From>::is_signed && std::numeric_limits<To>::is_signed > ());
   }
}

template <class From, class To>
void test_convert_neg_float(From from, const std::integral_constant<bool, true>&)
{
   from = -from;
   To t3(from);
   To t4 = from.template convert_to<To>();
   To answer(from.str());
   To tol = (std::max)(std::numeric_limits<To>::epsilon(), To(std::numeric_limits<From>::epsilon())) * 2;
   BOOST_CHECK_CLOSE_FRACTION(t3, answer, tol);
   BOOST_CHECK_CLOSE_FRACTION(t4, answer, tol);
}
template <class From, class To>
void test_convert_neg_float(From const&, const std::integral_constant<bool, false>&)
{
}

template <class From, class To>
void test_convert_imp(std::integral_constant<int, number_kind_floating_point> const&, std::integral_constant<int, number_kind_floating_point> const&)
{
   for (unsigned i = 0; i < 100; ++i)
   {
      From from = generate_random<From>();
      To   t1(from);
      To   t2 = from.template convert_to<To>();
      To   answer(from.str());
      To   tol = (std::max)(std::numeric_limits<To>::epsilon(), To(std::numeric_limits<From>::epsilon())) * 2;
      BOOST_CHECK_CLOSE_FRACTION(t1, answer, tol);
      BOOST_CHECK_CLOSE_FRACTION(t2, answer, tol);
      test_convert_neg_float<From, To>(from, std::integral_constant<bool, std::numeric_limits<From>::is_signed && std::numeric_limits<To>::is_signed > ());
   }
}

template <class From, class To>
void test_convert()
{
   test_convert_imp<From, To>(typename number_category<From>::type(), typename number_category<To>::type());
}

int main()
{
   test_convert<cpp_dec_float_50, cpp_int>();
   test_convert<cpp_dec_float_50, int128_t>();
   test_convert<cpp_dec_float_50, uint128_t>();

   test_convert<cpp_dec_float_50, cpp_rational>();

   test_convert<cpp_dec_float_50, cpp_bin_float_50>();

#if defined(HAS_GMP)
   test_convert<cpp_dec_float_50, mpz_int>();
   test_convert<cpp_dec_float_50, mpq_rational>();
   test_convert<cpp_dec_float_50, mpf_float_50>();
#endif
#if defined(HAS_MPFR)
   test_convert<cpp_dec_float_50, mpfr_float_50>();
#endif
#if defined(HAS_MPFI)
   test_convert<cpp_dec_float_50, mpfi_float_50>();
#endif
#ifdef HAS_TOMMATH
   test_convert<cpp_dec_float_50, tom_int>();
   test_convert<cpp_dec_float_50, tom_rational>();
#endif
#ifdef HAS_FLOAT128
   test_convert<cpp_dec_float_50, float128>();
#endif
   return boost::report_errors();
}


text:
<resources>
    <string name="app_name">JNI</string>
    <string name="action_settings">Settings</string>
  <string name="some_text_here">Some Text Here</string>
</resources>


text:
from __future__ import absolute_import

from datetime import datetime
from django.core.urlresolvers import reverse

from sentry.models import Release, ReleaseCommit, ReleaseProject
from sentry.testutils import APITestCase

class ProjectReleaseListTest(APITestCase):
    def test_simple(self):
        self.login_as(user=self.user)

        team = self.create_team()
        project1 = self.create_project(team=team, name='foo')
        project2 = self.create_project(team=team, name='bar')

        release1 = Release.objects.create(
            organization_id=project1.organization_id,
            version='1',
            date_added=datetime(2013, 8, 13, 3, 8, 24, 880386),
        )
        release1.add_project(project1)
        ReleaseProject.objects.filter(project=project1, release=release1).update(new_groups=5)

        release2 = Release.objects.create(
            organization_id=project1.organization_id,
            version='2',
            date_added=datetime(2013, 8, 14, 3, 8, 24, 880386),
        )
        release2.add_project(project1)

        release3 = Release.objects.create(
            organization_id=project1.organization_id,
            version='3',
            date_added=datetime(2013, 8, 12, 3, 8, 24, 880386),
            date_released=datetime(2013, 8, 15, 3, 8, 24, 880386),
        )
        release3.add_project(project1)

        release4 = Release.objects.create(
            organization_id=project2.organization_id,
            version='4',
        )
        release4.add_project(project2)

        url = reverse(
            'sentry-api-0-project-releases',
            kwargs={
                'organization_slug': project1.organization.slug,
                'project_slug': project1.slug,
            }
        )
        response = self.client.get(url, format='json')

        assert response.status_code == 200, response.content
        assert len(response.data) == 3
        assert response.data[0]['version'] == release3.version
        assert response.data[1]['version'] == release2.version
        assert response.data[2]['version'] == release1.version
        assert response.data[2]['newGroups'] == 5

    def test_query_filter(self):
        self.login_as(user=self.user)

        team = self.create_team()
        project = self.create_project(team=team, name='foo')

        release = Release.objects.create(
            organization_id=project.organization_id,
            version='foobar',
            date_added=datetime(2013, 8, 13, 3, 8, 24, 880386),
        )
        release.add_project(project)

        url = reverse(
            'sentry-api-0-project-releases',
            kwargs={
                'organization_slug': project.organization.slug,
                'project_slug': project.slug,
            }
        )
        response = self.client.get(url + '?query=foo', format='json')

        assert response.status_code == 200, response.content
        assert len(response.data) == 1
        assert response.data[0]['version'] == release.version

        response = self.client.get(url + '?query=bar', format='json')

        assert response.status_code == 200, response.content
        assert len(response.data) == 0

class ProjectReleaseCreateTest(APITestCase):
    def test_minimal(self):
        self.login_as(user=self.user)

        project = self.create_project(name='foo')

        url = reverse(
            'sentry-api-0-project-releases',
            kwargs={
                'organization_slug': project.organization.slug,
                'project_slug': project.slug,
            }
        )
        response = self.client.post(
            url, data={
                'version': '1.2.1',
            }
        )

        assert response.status_code == 201, response.content
        assert response.data['version']

        release = Release.objects.get(
            version=response.data['version'],
        )
        assert not release.owner
        assert release.organization == project.organization
        assert release.projects.first() == project

    def test_ios_release(self):
        self.login_as(user=self.user)

        project = self.create_project(name='foo')

        url = reverse(
            'sentry-api-0-project-releases',
            kwargs={
                'organization_slug': project.organization.slug,
                'project_slug': project.slug,
            }
        )
        response = self.client.post(
            url, data={
                'version': '1.2.1 (123)',
            }
        )

        assert response.status_code == 201, response.content
        assert response.data['version']

        release = Release.objects.get(
            version=response.data['version'],
        )
        assert not release.owner
        assert release.organization == project.organization
        assert release.projects.first() == project

    def test_duplicate(self):
        self.login_as(user=self.user)

        project = self.create_project(name='foo')

        release = Release.objects.create(version='1.2.1', organization_id=project.organization_id)
        release.add_project(project)

        url = reverse(
            'sentry-api-0-project-releases',
            kwargs={
                'organization_slug': project.organization.slug,
                'project_slug': project.slug,
            }
        )

        response = self.client.post(
            url, data={
                'version': '1.2.1',
            }
        )

        assert response.status_code == 208, response.content

    def test_duplicate_accross_org(self):
        self.login_as(user=self.user)

        project = self.create_project(name='foo')

        release = Release.objects.create(version='1.2.1', organization_id=project.organization_id)
        release.add_project(project)

        project2 = self.create_project(name='bar', organization=project.organization)

        url = reverse(
            'sentry-api-0-project-releases',
            kwargs={
                'organization_slug': project2.organization.slug,
                'project_slug': project2.slug,
            }
        )

        response = self.client.post(
            url, data={
                'version': '1.2.1',
            }
        )

        # since project2 was added, should be 201
        assert response.status_code == 201, response.content
        assert Release.objects.filter(
            version='1.2.1', organization_id=project.organization_id
        ).count() == 1
        assert ReleaseProject.objects.get(release=release, project=project)
        assert ReleaseProject.objects.get(release=release, project=project2)

    def test_version_whitespace(self):
        self.login_as(user=self.user)

        project = self.create_project(name='foo')

        url = reverse(
            'sentry-api-0-project-releases',
            kwargs={
                'organization_slug': project.organization.slug,
                'project_slug': project.slug,
            }
        )

        response = self.client.post(
            url, data={
                'version': '1.2.3\n',
            }
        )
        assert response.status_code == 400, response.content

        response = self.client.post(
            url, data={
                'version': '\n1.2.3',
            }
        )
        assert response.status_code == 400, response.content

        response = self.client.post(
            url, data={
                'version': '1.\n2.3',
            }
        )
        assert response.status_code == 400, response.content

        response = self.client.post(
            url, data={
                'version': '1.2.3\f',
            }
        )
        assert response.status_code == 400, response.content

        response = self.client.post(
            url, data={
                'version': '1.2.3\t',
            }
        )
        assert response.status_code == 400, response.content

        response = self.client.post(
            url, data={
                'version': '1.2.3',
            }
        )
        assert response.status_code == 201, response.content
        assert response.data['version'] == '1.2.3'

        release = Release.objects.get(
            organization_id=project.organization_id,
            version=response.data['version'],
        )
        assert not release.owner

    def test_features(self):
        self.login_as(user=self.user)

        project = self.create_project(name='foo')

        url = reverse(
            'sentry-api-0-project-releases',
            kwargs={
                'organization_slug': project.organization.slug,
                'project_slug': project.slug,
            }
        )
        response = self.client.post(
            url, data={
                'version': '1.2.1',
                'owner': self.user.email,
            }
        )

        assert response.status_code == 201, response.content
        assert response.data['version']

        release = Release.objects.get(
            organization_id=project.organization_id,
            version=response.data['version'],
        )
        assert release.owner == self.user

    def test_commits(self):
        self.login_as(user=self.user)

        project = self.create_project(name='foo')

        url = reverse(
            'sentry-api-0-project-releases',
            kwargs={
                'organization_slug': project.organization.slug,
                'project_slug': project.slug,
            }
        )
        response = self.client.post(
            url, data={'version': '1.2.1',
                       'commits': [
                           {
                               'id': 'a' * 40
                           },
                           {
                               'id': 'b' * 40
                           },
                       ]}
        )

        assert response.status_code == 201, (response.status_code, response.content)
        assert response.data['version']

        release = Release.objects.get(
            organization_id=project.organization_id,
            version=response.data['version'],
        )

        rc_list = list(
            ReleaseCommit.objects.filter(
                release=release,
            ).select_related('commit', 'commit__author').order_by('order')
        )
        assert len(rc_list) == 2
        for rc in rc_list:
            assert rc.organization_id

    def test_fails_with_refs(self):
        self.login_as(user=self.user)

        project = self.create_project(name='foo')

        url = reverse('sentry-api-0-project-releases', kwargs={
            'organization_slug': project.organization.slug,
            'project_slug': project.slug,
        })

        response = self.client.post(url, data={
            'version': '1.2.1',
            'refs': [{
                'repository': 'getsentry/sentry',
                'commit': 'a' * 40,
            }],
        })

        assert response.status_code == 400


text:
<?php
namespace Janus\Tests\ServiceRegistry\Service;

use Janus\ServiceRegistry\Connection\Metadata\MetadataDefinitionHelper;
use Janus\ServiceRegistry\Connection\Metadata\MetadataTreeFlattener;
use Janus\ServiceRegistry\Entity\Connection;
use Janus\ServiceRegistry\Entity\ConnectionRepository;
use PHPUnit_Framework_TestCase;
use Phake;

use Janus\ServiceRegistry\Bundle\CoreBundle\DependencyInjection\ConfigProxy;
use Janus\ServiceRegistry\Connection\ConnectionDto;
use Janus\ServiceRegistry\Service\ConnectionService;
use Janus\ServiceRegistry\Entity\Connection\Revision\Metadata;

class ConnectionServiceTest extends PHPUnit_Framework_TestCase
{
    public function testFlattensMetadataOnSave()
    {
        // Create Conection service
        $entityManagerMock = Phake::mock('Doctrine\ORM\EntityManager');
        $mockDbConnection = Phake::mock('Doctrine\DBAL\Connection');
        Phake::when($entityManagerMock)
            ->getConnection()
            ->thenReturn($mockDbConnection);
        $config = new ConfigProxy(array(
            "metadatafields" => array(
                'saml20_idp' => array(
                    'foo:bar:baz' => array(
                        'supported' => array(
                            1
                        )
                    )
                )
            )
        ));

        // Create metadata tree flattener
        $metadataDefinitionHelper = new MetadataDefinitionHelper($config);
        $metadataTreeFlattener = new MetadataTreeFlattener($metadataDefinitionHelper);

        $loggerMock = Phake::mock('Monolog\Logger');

        $connectionRepository = new ConnectionRepository($entityManagerMock, $loggerMock);

        $connectionService = new ConnectionService(
            $entityManagerMock,
            $config,
            $loggerMock,
            $metadataTreeFlattener,
            $metadataDefinitionHelper,
            $connectionRepository
        );

        // Mock existing connection
        $connectionRepositoryMock = Phake::mock('Janus\ServiceRegistry\Entity\ConnectionRepository');
        $connection = new Connection('fooConnection', 'saml20-idp', 'initial revision');
        Phake::when($connectionRepositoryMock)
            ->find(1)
            ->thenReturn($connection);
        Phake::when($entityManagerMock)
            ->getRepository('Janus\ServiceRegistry\Entity\Connection')
            ->thenReturn($connectionRepositoryMock);

        // Mock metadata dto
        $nestedMetadata = array(
            'foo' => array(
                'bar' => array(
                    'baz' => 1
                )
            )
        );

        // Save
        $connectionDto = new ConnectionDto();
        $connectionDto->id = 1;
        $connectionDto->name = 'fooConnection';
        $connectionDto->type = 'saml20-idp';
        $connectionDto->revisionNote = 'initial revision';
        $connectionDto->metadata = $nestedMetadata;
        $connectionService->save($connectionDto);

        // Verify flattened metadata is saved
        $metadataRecord = new Metadata(
            $connection->getLatestRevision(),
            'foo:bar:baz',
            1
        );
        Phake::verify($entityManagerMock)->persist($metadataRecord);
    }

    public function testReturnsConnectionEntity()
    {
        // Mock repository which returns connection
        $connectionRepositoryMock = Phake::mock('Janus\ServiceRegistry\Entity\ConnectionRepository');
        $connection = new Connection('test', 'saml20-idp');
        Phake::when($connectionRepositoryMock)
            ->find(1)
            ->thenReturn($connection);

        // Mock entity manager which returns repository
        $entityManagerMock = Phake::mock('Doctrine\ORM\EntityManager');
        Phake::when($entityManagerMock)
            ->getRepository('Janus\ServiceRegistry\Entity\Connection')
            ->thenReturn($connectionRepositoryMock);

        // Create service
        $config = new ConfigProxy(array());
        $metadataDefinitionHelper = new MetadataDefinitionHelper($config);
        $loggerMock = Phake::mock('Monolog\Logger');
        $connectionService = new ConnectionService(
            $entityManagerMock,
            $config,
            $loggerMock,
            new MetadataTreeFlattener($metadataDefinitionHelper),
            $metadataDefinitionHelper,
            $connectionRepositoryMock
        );

        $connection = $connectionService->findById(1);
        $this->assertInstanceOf('Janus\ServiceRegistry\Entity\Connection', $connection);
    }
}