text:
@class TQNumber;

extern NSString * const TQTypeObj;
extern NSString * const TQTypeClass;
extern NSString * const TQTypeSel;
extern NSString * const TQTypeChar;
extern NSString * const TQTypeUChar;
extern NSString * const TQTypeShort;
extern NSString * const TQTypeUShort;
extern NSString * const TQTypeInt;
extern NSString * const TQTypeUInt;
extern NSString * const TQTypeLong;
extern NSString * const TQTypeULong;
extern NSString * const TQTypeLongLong;
extern NSString * const TQTypeULongLong;
extern NSString * const TQTypeFloat;
extern NSString * const TQTypeDouble;
extern NSString * const TQTypeBool;
extern NSString * const TQTypeString;

// A class to enable use of (Obj-)C APIs that utilize pointers
@interface TQPointer : TQObject <NSCopying> {
    char *_itemType;
    NSUInteger _itemSize, _count;
    BOOL _freeOnDealloc;
    @public
    char *_addr; // Only ever meant to be accessed by TQBoxedObject
}
+ (TQPointer *)box:(void *)aPtr withType:(const char *)aType;
+ (TQPointer *)withObjects:(NSArray *)aObjs type:(NSString *)aType;
+ (TQPointer *)to:(id)aObj withType:(NSString *)aType;
+ (TQPointer *)withType:(NSString *)aType count:(NSNumber *)aCount;
+ (TQPointer *)withType:(NSString *)aType;

- (id)initWithType:(const char *)aType count:(NSUInteger)aCount;
- (id)initWithType:(const char *)aType address:(void *)aAddr count:(NSUInteger)aCount;

- (TQPointer *)castTo:(NSString *)type;
- (id)addressAsObject;

- (id)objectAtIndexedSubscript:(NSUInteger)aIdx;
- (void)setObject:(id)aObj atIndexedSubscript:(NSUInteger)aIdx;
- (id)at:(id)aIdx;
- (id)set:(id)aIdx to:(id)aVal;

- (TQNumber *)count;
- (id)value; // Returns the first item

- (const char *)UTF8String;

- (id)pointsToNULL;
@end

@interface TQPointer (ConvenienceConstructors)
+ (TQPointer *)toObject;
+ (TQPointer *)toChar;
+ (TQPointer *)toBOOL;
+ (TQPointer *)toShort;
+ (TQPointer *)toInt;
+ (TQPointer *)toLong;
+ (TQPointer *)toLongLong;
+ (TQPointer *)toFloat;
+ (TQPointer *)toDouble;
+ (TQPointer *)toNSPoint;
+ (TQPointer *)toNSSize;
+ (TQPointer *)toNSRect;
+ (TQPointer *)toObjects:(TQNumber *)aCount;
+ (TQPointer *)toChars:(TQNumber *)aCount;
+ (TQPointer *)toBOOLs:(TQNumber *)aCount;
+ (TQPointer *)toShorts:(TQNumber *)aCount;
+ (TQPointer *)toInts:(TQNumber *)aCount;
+ (TQPointer *)toLongs:(TQNumber *)aCount;
+ (TQPointer *)toLongLongs:(TQNumber *)aCount;
+ (TQPointer *)toFloats:(TQNumber *)aCount;
+ (TQPointer *)toDoubles:(TQNumber *)aCount;
+ (TQPointer *)toNSPoints:(TQNumber *)aCount;
+ (TQPointer *)toNSSizes:(TQNumber *)aCount;
+ (TQPointer *)toNSRects:(TQNumber *)aCount;
@end


text:
package org.springframework.boot.gradle.docs;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;

import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

import org.springframework.boot.gradle.junit.GradleMultiDslSuite;
import org.springframework.boot.gradle.testkit.GradleBuild;

import static org.assertj.core.api.Assertions.assertThat;

/**
 * Tests for the generating build info documentation.
 *
 * @author Andy Wilkinson
 * @author Jean-Baptiste Nizet
 */
@RunWith(GradleMultiDslSuite.class)
public class IntegratingWithActuatorDocumentationTests {

	@Rule
	public GradleBuild gradleBuild;

	@Test
	public void basicBuildInfo() throws IOException {
		this.gradleBuild
				.script("src/main/gradle/integrating-with-actuator/build-info-basic")
				.build("bootBuildInfo");
		assertThat(new File(this.gradleBuild.getProjectDir(),
				"build/resources/main/META-INF/build-info.properties")).isFile();
	}

	@Test
	public void buildInfoCustomValues() throws IOException {
		this.gradleBuild.script(
				"src/main/gradle/integrating-with-actuator/build-info-custom-values")
				.build("bootBuildInfo");
		File file = new File(this.gradleBuild.getProjectDir(),
				"build/resources/main/META-INF/build-info.properties");
		assertThat(file).isFile();
		Properties properties = buildInfoProperties(file);
		assertThat(properties).containsEntry("build.artifact", "example-app");
		assertThat(properties).containsEntry("build.version", "1.2.3");
		assertThat(properties).containsEntry("build.group", "com.example");
		assertThat(properties).containsEntry("build.name", "Example application");
	}

	@Test
	public void buildInfoAdditional() throws IOException {
		this.gradleBuild
				.script("src/main/gradle/integrating-with-actuator/build-info-additional")
				.build("bootBuildInfo");
		File file = new File(this.gradleBuild.getProjectDir(),
				"build/resources/main/META-INF/build-info.properties");
		assertThat(file).isFile();
		Properties properties = buildInfoProperties(file);
		assertThat(properties).containsEntry("build.a", "alpha");
		assertThat(properties).containsEntry("build.b", "bravo");
	}

	private Properties buildInfoProperties(File file) {
		assertThat(file).isFile();
		Properties properties = new Properties();
		try (FileReader reader = new FileReader(file)) {
			properties.load(reader);
			return properties;
		}
		catch (IOException ex) {
			throw new RuntimeException(ex);
		}
	}

}

redpajama_set_name: RedPajamaGithub


text:
"""
This package is based on the PhysicalQuantity package that is part of ScientificPython.
It performs unit conversions.
"""


text:
function noop() {}

var localStorage = {};
localStorage.setItem = noop;
localStorage.getItem = noop;
localStorage.clear = noop;
localStorage.removeItem = noop;

// Expose localStorage as a global object
global.localStorage = localStorage;


text:
package net.ljcomputing.sr.repository;

import net.ljcomputing.core.repository.BaseRepository;
import net.ljcomputing.sr.entity.ActivityEntity;
import net.ljcomputing.sr.entity.WbsEntity;

import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Activity entity repository.
 *
 * @author James G. Willmore
 *
 */
@Repository
public interface ActivityEntityRepository
    extends BaseRepository<ActivityEntity, String> {

  /**
   * Find by name.
   *
   * @param name the name
   * @return the activity entity
   */
  ActivityEntity findByName(String name);

  /**
   * Find by work breakdown structure.
   *
   * @param wbsEntity the wbs entity
   * @return the list
   */
  List<ActivityEntity> findByWbs(WbsEntity wbsEntity);
}


text:
SPEC_BEGIN(DesignerNewsURLSpec)

describe(@"DesignerNewsURL", ^{

    context(@"when login", ^{
        it(@"should return the login url string", ^{
            NSString *expect = [NSString stringWithFormat:@"%@/oauth/token", baseURL];
            [[[DesignerNewsURL loginURLString] should] equal:expect];
        });
    });

    context(@"when get stories", ^{
        it(@"should return the stories url string", ^{
            NSString *expect = [NSString stringWithFormat:@"%@/api/v1/stories", baseURL];
            [[[DesignerNewsURL stroiesURLString] should] equal:expect];
        });
    });

    context(@"when get storie by id", ^{
        it(@"should return story url string by id", ^{
            NSString *expect = [NSString stringWithFormat:@"%@/api/v1/stories/1", baseURL];
            [[[DesignerNewsURL storyIdURLStringWithId:1] should] equal:expect];
        });
    });

    context(@"when upvote story by id", ^{
        it(@"should return story upvote url string", ^{
            NSString *expect = [NSString stringWithFormat:@"%@/api/v1/stories/1/upvote", baseURL];
            [[[DesignerNewsURL storyUpvoteWithId:1] should] equal:expect];
        });
    });

    context(@"when reply story by id", ^{
        it(@"should return story reply url string", ^{
            NSString *expect = [NSString stringWithFormat:@"%@/api/v1/stories/1/reply", baseURL];
            [[[DesignerNewsURL storyReplyWithId:1] should] equal:expect];
        });
    });

    context(@"when upvote comment by id", ^{
        it(@"should return comment upvote url string", ^{
            NSString *expect = [NSString stringWithFormat:@"%@/api/v1/comments/1/upvote", baseURL];
            [[[DesignerNewsURL commentUpvoteWithId:1] should] equal:expect];
        });
    });

    context(@"when reply comment by id", ^{
        it(@"should return comment reply url string ", ^{
            NSString *expect = [NSString stringWithFormat:@"%@/api/v1/comments/1/reply", baseURL];
            [[[DesignerNewsURL commentReplyWithId:1] should] equal:expect];
        });
    });
});

SPEC_END


text:
#include "DDSEntityManager.h"

DDSEntityManager::DDSEntityManager()
{
  m_autodispose_unregistered_instances = false;
}

DDSEntityManager::DDSEntityManager(bool autodispose_unregistered_instances)
{
  m_autodispose_unregistered_instances = autodispose_unregistered_instances;
}

void DDSEntityManager::createParticipant(const char *partitiontName)
{
  domain = DOMAIN_ID_DEFAULT;
  dpf = DomainParticipantFactory::get_instance();
  checkHandle(dpf.in(), "DDS::DomainParticipantFactory::get_instance");
  participant = dpf->create_participant(domain, PARTICIPANT_QOS_DEFAULT, NULL,
    STATUS_MASK_NONE);
  checkHandle(participant.in(),
    "DDS::DomainParticipantFactory::create_participant");
  partition = partitiontName;
}

void DDSEntityManager::deleteParticipant()
{
  status = dpf->delete_participant(participant.in());
  checkStatus(status, "DDS::DomainParticipantFactory::delete_participant");
}

void DDSEntityManager::registerType(TypeSupport *ts)
{
  typeName = ts->get_type_name();
  status = ts->register_type(participant.in(), typeName);
  checkStatus(status, "register_type");
}

void DDSEntityManager::createTopic(char *topicName)
{
  status = participant->get_default_topic_qos(reliable_topic_qos);
  checkStatus(status, "DDS::DomainParticipant::get_default_topic_qos");
  reliable_topic_qos.reliability.kind = RELIABLE_RELIABILITY_QOS;
  reliable_topic_qos.durability.kind = TRANSIENT_DURABILITY_QOS;

  /* Set a the history Policy */
  //reliable_topic_qos.history.kind = KEEP_LAST_HISTORY_QOS;
  //reliable_topic_qos.history.depth = 1;

  /* Make the tailored QoS the new default. */
  status = participant->set_default_topic_qos(reliable_topic_qos);
  checkStatus(status, "DDS::DomainParticipant::set_default_topic_qos");

  /* Use the changed policy when defining the Lifecycle topic */
  topic = participant->create_topic(topicName, typeName, reliable_topic_qos,
    NULL, STATUS_MASK_NONE);
  checkHandle(topic.in(), "DDS::DomainParticipant::create_topic ()");
}

void DDSEntityManager::deleteTopic()
{
  status = participant->delete_topic(topic);
  checkStatus(status, "DDS.DomainParticipant.delete_topic");
}

void DDSEntityManager::createPublisher()
{
  status = participant->get_default_publisher_qos(pub_qos);
  checkStatus(status, "DDS::DomainParticipant::get_default_publisher_qos");
  pub_qos.partition.name.length(1);
  pub_qos.partition.name[0] = partition;

  publisher = participant->create_publisher(pub_qos, NULL, STATUS_MASK_NONE);
  checkHandle(publisher.in(), "DDS::DomainParticipant::create_publisher");
}

void DDSEntityManager::deletePublisher()
{
  status = participant->delete_publisher(publisher);
   // TODO : uncomment checkStatus(status, "DDS::DomainParticipant::delete_publisher");
}

void DDSEntityManager::createWriters()
{
  status = publisher->get_default_datawriter_qos(dw_qos);
  checkStatus(status, "DDS::DomainParticipant::get_default_publisher_qos");
  status = publisher->copy_from_topic_qos(dw_qos, reliable_topic_qos);
  checkStatus(status, "DDS::Publisher::copy_from_topic_qos");
  // Set autodispose to false otherwise the instances of the
  // topic will be suppressed from the persistence file when
  // the writer is stopped
  dw_qos.writer_data_lifecycle.autodispose_unregistered_instances =
    m_autodispose_unregistered_instances;
  writer = publisher->create_datawriter(topic.in(), dw_qos, NULL,
    STATUS_MASK_NONE);
  writer_stopper = publisher->create_datawriter(topic.in(), dw_qos, NULL,
    STATUS_MASK_NONE);
  checkHandle(writer, "DDS::Publisher::create_datawriter");
}

void DDSEntityManager::deleteWriter(DDS::DataWriter_ptr dataWriter)
{
   status = publisher->delete_datawriter(dataWriter);
   checkStatus(status, "DDS::Publisher::delete_datawriter ");
}

void DDSEntityManager::createSubscriber()
{
  status = participant->get_default_subscriber_qos(sub_qos);
  checkStatus(status, "DDS::DomainParticipant::get_default_subscriber_qos");
  sub_qos.partition.name.length(1);
  sub_qos.partition.name[0] = partition;
  subscriber = participant->create_subscriber(sub_qos, NULL, STATUS_MASK_NONE);
  checkHandle(subscriber.in(), "DDS::DomainParticipant::create_subscriber");
}

void DDSEntityManager::deleteSubscriber()
{
  status = participant->delete_subscriber(subscriber);
  checkStatus(status, "DDS::DomainParticipant::delete_subscriber");
}

void DDSEntityManager::createReader()
{
  status = subscriber->get_default_datareader_qos(dr_qos);
  checkStatus(status, "DDS::Subscriber::get_default_datareader_qos");
  status = subscriber->copy_from_topic_qos(dr_qos, reliable_topic_qos);
  checkStatus(status, "DDS::Subscriber::copy_from_topic_qos");
  reader = subscriber->create_datareader(topic.in(), dr_qos, NULL,
    STATUS_MASK_NONE);
  checkHandle(reader, "DDS::Subscriber::create_datareader ()");
}

void DDSEntityManager::deleteReader(DDS::DataReader_ptr dataReader)
{
   status = subscriber->delete_datareader(dataReader);
   checkStatus(status, "DDS::Subscriber::delete_datareader ");
}

DataReader_ptr DDSEntityManager::getReader()
{
  return DataReader::_duplicate(reader.in());
}

DataWriter_ptr DDSEntityManager::getWriter()
{
  return DataWriter::_duplicate(writer.in());
}

DataWriter_ptr DDSEntityManager::getWriter_stopper()
{
  return DataWriter::_duplicate(writer_stopper.in());
}

Publisher_ptr DDSEntityManager::getPublisher()
{
  return Publisher::_duplicate(publisher.in());
}

Subscriber_ptr DDSEntityManager::getSubscriber()
{
  return Subscriber::_duplicate(subscriber.in());
}

Topic_ptr DDSEntityManager::getTopic()
{
  return Topic::_duplicate(topic.in());
}

DomainParticipant_ptr DDSEntityManager::getParticipant()
{
  return DomainParticipant::_duplicate(participant.in());
}

DDSEntityManager::~DDSEntityManager(){

}


text:
// Copyright 2000-2020 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 com.intellij.ide.customize;

import com.intellij.openapi.extensions.PluginId;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;

public final class IdSet {

  private static final List<@NonNls String> STOP_LIST = List.of("Support", "support",
                                                                "Integration", "integration");

  private final @NotNull Set<PluginId> myPluginIds;
  private final @Nls @NotNull String myTitle;

  IdSet(@NotNull Set<PluginId> pluginIds,
        @Nls @NotNull String title) {
    assert !pluginIds.isEmpty();
    myPluginIds = pluginIds;
    myTitle = cleanTitle(title);
  }

  @Override
  public String toString() {
    return myTitle + ": " + myPluginIds.size();
  }

  public @NotNull Set<PluginId> getPluginIds() {
    return Collections.unmodifiableSet(myPluginIds);
  }

  public @Nls @NotNull String getTitle() {
    return myTitle;
  }

  /**
   * @deprecated Please use {@link #getPluginIds()}.
   */
  @Deprecated(forRemoval = true)
  public @NotNull List<PluginId> getIds() {
    return new ArrayList<>(myPluginIds);
  }

  private static @Nls @NotNull String cleanTitle(@Nls @NotNull String title) {
    for (String skipWord : STOP_LIST) {
      title = title.replaceAll(skipWord, ""); //NON-NLS
    }
    return title.replaceAll(" {2}", " ").trim();
  }
}


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _regenerator = require('babel-runtime/regenerator');

var _regenerator2 = _interopRequireDefault(_regenerator);

var _extends2 = require('babel-runtime/helpers/extends');

var _extends3 = _interopRequireDefault(_extends2);

var _asyncToGenerator2 = require('babel-runtime/helpers/asyncToGenerator');

var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);

var _toConsumableArray2 = require('babel-runtime/helpers/toConsumableArray');

var _toConsumableArray3 = _interopRequireDefault(_toConsumableArray2);

var _objectWithoutProperties2 = require('babel-runtime/helpers/objectWithoutProperties');

var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2);

var formatStdin = function () {
  var _ref2 = (0, _asyncToGenerator3.default)(_regenerator2.default.mark(function _callee(prettierESLintOptions) {
    var stdinValue, formatted;
    return _regenerator2.default.wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            _context.next = 2;
            return (0, _getStdin2.default)();

          case 2:
            stdinValue = _context.sent.trim();
            _context.prev = 3;
            formatted = (0, _prettierEslint2.default)((0, _extends3.default)({ text: stdinValue }, prettierESLintOptions));

            process.stdout.write(formatted);
            return _context.abrupt('return', Promise.resolve(formatted));

          case 9:
            _context.prev = 9;
            _context.t0 = _context['catch'](3);

            logger.error('There was a problem trying to format the stdin text', `\n${(0, _indentString2.default)(_context.t0.stack, 4)}`);
            process.exitCode = 1;
            return _context.abrupt('return', Promise.resolve(stdinValue));

          case 14:
          case 'end':
            return _context.stop();
        }
      }
    }, _callee, this, [[3, 9]]);
  }));

  return function formatStdin(_x) {
    return _ref2.apply(this, arguments);
  };
}();

var _path = require('path');

var _path2 = _interopRequireDefault(_path);

var _fs = require('fs');

var _fs2 = _interopRequireDefault(_fs);

var _glob = require('glob');

var _glob2 = _interopRequireDefault(_glob);

var _Rx = require('rxjs/Rx');

var _Rx2 = _interopRequireDefault(_Rx);

var _prettierEslint = require('prettier-eslint');

var _prettierEslint2 = _interopRequireDefault(_prettierEslint);

var _chalk = require('chalk');

var _chalk2 = _interopRequireDefault(_chalk);

var _getStdin = require('get-stdin');

var _getStdin2 = _interopRequireDefault(_getStdin);

var _ignore = require('ignore');

var _ignore2 = _interopRequireDefault(_ignore);

var _findUp = require('find-up');

var _findUp2 = _interopRequireDefault(_findUp);

var _lodash = require('lodash.memoize');

var _lodash2 = _interopRequireDefault(_lodash);

var _indentString = require('indent-string');

var _indentString2 = _interopRequireDefault(_indentString);

var _loglevelColoredLevelPrefix = require('loglevel-colored-level-prefix');

var _loglevelColoredLevelPrefix2 = _interopRequireDefault(_loglevelColoredLevelPrefix);

var _messages = require('./messages');

var messages = _interopRequireWildcard(_messages);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var LINE_SEPERATOR_REGEX = /(\r|\n|\r\n)/; /* eslint no-console:0 */

var rxGlob = _Rx2.default.Observable.bindNodeCallback(_glob2.default);
var rxReadFile = _Rx2.default.Observable.bindNodeCallback(_fs2.default.readFile);
var rxWriteFile = _Rx2.default.Observable.bindNodeCallback(_fs2.default.writeFile);
var findUpSyncMemoized = (0, _lodash2.default)(findUpSync, function resolver() {
  for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
    args[_key] = arguments[_key];
  }

  return args.join('::');
});
var getIsIgnoredMemoized = (0, _lodash2.default)(getIsIgnored);

var logger = (0, _loglevelColoredLevelPrefix2.default)({ prefix: 'prettier-eslint-cli' });

exports.default = formatFilesFromArgv;

function formatFilesFromArgv(_ref) {
  var fileGlobs = _ref._,
      _ref$logLevel = _ref.logLevel,
      logLevel = _ref$logLevel === undefined ? logger.getLevel() : _ref$logLevel,
      listDifferent = _ref.listDifferent,
      stdin = _ref.stdin,
      write = _ref.write,
      eslintPath = _ref.eslintPath,
      prettierPath = _ref.prettierPath,
      _ref$ignore = _ref.ignore,
      ignoreGlobs = _ref$ignore === undefined ? [] : _ref$ignore,
      _ref$eslintIgnore = _ref.eslintIgnore,
      applyEslintIgnore = _ref$eslintIgnore === undefined ? true : _ref$eslintIgnore,
      prettierLast = _ref.prettierLast,
      prettierOptions = (0, _objectWithoutProperties3.default)(_ref, ['_', 'logLevel', 'listDifferent', 'stdin', 'write', 'eslintPath', 'prettierPath', 'ignore', 'eslintIgnore', 'prettierLast']);

  logger.setLevel(logLevel);
  var prettierESLintOptions = {
    logLevel,
    eslintPath,
    prettierPath,
    prettierLast,
    prettierOptions
  };
  var cliOptions = { write, listDifferent };
  if (stdin) {
    return formatStdin(prettierESLintOptions);
  } else {
    return formatFilesFromGlobs(fileGlobs, [].concat((0, _toConsumableArray3.default)(ignoreGlobs)), // make a copy to avoid manipulation
    cliOptions, prettierESLintOptions, applyEslintIgnore);
  }
}

function formatFilesFromGlobs(fileGlobs, ignoreGlobs, cliOptions, prettierESLintOptions, applyEslintIgnore) {
  var concurrentGlobs = 3;
  var concurrentFormats = 10;
  return new Promise(function (resolve) {
    var successes = [];
    var failures = [];
    var unchanged = [];
    _Rx2.default.Observable.from(fileGlobs).mergeMap(getFilesFromGlob.bind(null, ignoreGlobs, applyEslintIgnore), null, concurrentGlobs).concatAll().distinct().mergeMap(filePathToFormatted, null, concurrentFormats).subscribe(onNext, onError, onComplete);

    function filePathToFormatted(filePath) {
      return formatFile(filePath, prettierESLintOptions, cliOptions);
    }

    function onNext(info) {
      if (info.error) {
        failures.push(info);
      } else if (info.unchanged) {
        unchanged.push(info);
      } else {
        successes.push(info);
      }
    }

    function onError(error) {
      logger.error('There was an unhandled error while formatting the files', `\n${(0, _indentString2.default)(error.stack, 4)}`);
      process.exitCode = 1;
      resolve({ error, successes, failures });
    }

    function onComplete() {
      var isNotSilent = logger.getLevel() !== logger.levels.SILENT;

      /* use console.error directly here because
       * - we don't want these messages prefixed
       * - we want them to go to stderr, not stdout
       */
      if (successes.length && isNotSilent) {
        console.error(messages.success({
          success: _chalk2.default.green('success'),
          count: successes.length,
          countString: _chalk2.default.bold(successes.length)
        }));
      }
      if (failures.length && isNotSilent) {
        process.exitCode = 1;
        console.error(messages.failure({
          failure: _chalk2.default.red('failure'),
          count: failures.length,
          countString: _chalk2.default.bold(failures.length)
        }));
      }
      if (unchanged.length && isNotSilent) {
        console.error(messages.unchanged({
          unchanged: _chalk2.default.gray('unchanged'),
          count: unchanged.length,
          countString: _chalk2.default.bold(unchanged.length)
        }));
      }
      resolve({ successes, failures });
    }
  });
}

function getFilesFromGlob(ignoreGlobs, applyEslintIgnore, fileGlob) {
  var globOptions = { ignore: ignoreGlobs };
  if (!fileGlob.includes('node_modules')) {
    // basically, we're going to protect you from doing something
    // not smart unless you explicitly include it in your glob
    globOptions.ignore.push('**/node_modules/**');
  }
  return rxGlob(fileGlob, globOptions).map(function (filePaths) {
    return filePaths.filter(function (filePath) {
      return applyEslintIgnore ? !isFilePathMatchedByEslintignore(filePath) : true;
    });
  });
}

function formatFile(filePath, prettierESLintOptions, cliOptions) {
  var fileInfo = { filePath };
  var format$ = rxReadFile(filePath, 'utf8').map(function (text) {
    fileInfo.text = text;
    fileInfo.formatted = (0, _prettierEslint2.default)((0, _extends3.default)({ text, filePath }, prettierESLintOptions));
    fileInfo.unchanged = fileInfo.text === fileInfo.formatted;
    return fileInfo;
  });

  if (cliOptions.write) {
    format$ = format$.mergeMap(function (info) {
      if (info.unchanged) {
        return _Rx2.default.Observable.of(info);
      } else {
        return rxWriteFile(filePath, info.formatted).map(function () {
          return info;
        });
      }
    });
  } else if (cliOptions.listDifferent) {
    format$ = format$.map(function (info) {
      if (!info.unchanged) {
        process.exitCode = 1;
        console.log(info.filePath);
      }
      return info;
    });
  } else {
    format$ = format$.map(function (info) {
      process.stdout.write(info.formatted);
      return info;
    });
  }

  return format$.catch(function (error) {
    logger.error(`There was an error formatting "${fileInfo.filePath}":`, `\n${(0, _indentString2.default)(error.stack, 4)}`);
    return _Rx2.default.Observable.of(Object.assign(fileInfo, { error }));
  });
}

function getNearestEslintignorePath(filePath) {
  var _path$parse = _path2.default.parse(filePath),
      dir = _path$parse.dir;

  return findUpSyncMemoized('.eslintignore', dir);
}

function isFilePathMatchedByEslintignore(filePath) {
  var eslintignorePath = getNearestEslintignorePath(filePath);
  if (!eslintignorePath) {
    return false;
  }

  var eslintignoreDir = _path2.default.parse(eslintignorePath).dir;
  var filePathRelativeToEslintignoreDir = _path2.default.relative(eslintignoreDir, filePath);
  var isIgnored = getIsIgnoredMemoized(eslintignorePath);
  return isIgnored(filePathRelativeToEslintignoreDir);
}

function findUpSync(filename, cwd) {
  return _findUp2.default.sync('.eslintignore', { cwd });
}

function getIsIgnored(filename) {
  var ignoreLines = _fs2.default.readFileSync(filename, 'utf8').split(LINE_SEPERATOR_REGEX).filter(function (line) {
    return Boolean(line.trim());
  });
  var instance = (0, _ignore2.default)();
  instance.add(ignoreLines);
  return instance.ignores.bind(instance);
}


text:
<?php

namespace Lunr\Corona\Exceptions;

use \Lunr\Corona\HttpCode;
use \Exception;

/**
 * Exception for the Not Implemented HTTP error (501).
 */
class NotImplementedException extends HttpException
{

    /**
     * Constructor.
     */
    public function __construct($message = NULL, $app_code = 0, Exception $previous = NULL)
    {
        parent::__construct($message, HttpCode::NOT_IMPLEMENTED, $app_code, $previous);
    }

}

?>


text:
package org.eclipse.microprofile.opentracing.tck.tracer;

import java.util.function.Consumer;

/**
 * Provide a way to visit all the nodes of a tree with a lambda.
 * @param <T> The type of data in the tree.
 */
public interface ConsumableTree<T> {
    /**
     * Recursively visit all nodes with the lambda.
     * @param visitor Lambda
     */
    void visitTree(Consumer<? super T> visitor);
}


text:
@typedef {function(HTMLElement,String,CSSSelectorString,Function,can.Control)} can.Control.processor(element,eventName,selector,handler,control)

@description A function that handles the binding and unbinding of a [can.Control]'s declarative event method.

@param {HTMLElement} element the control's element or the object
specified by the templated event handler (`"{object}"`).

@param {String} eventName The event type.

@param {CSSSelectorString} selector The selector preceding the event in the binding used on the Control.

@param {function(this:can.Control,Object,Event)} handler(element, event) The callback function being bound.

@option {Object} element foo
@option {Event} event bar

@param {can.Control} control The Control the event is bound on.

@return {function()} A callback function that unbinds any event handlers bound within this processor.


text:
package com.example.acme.kazoo.ui;

import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;

import com.blackmoonit.androidbits.app.AppPrefsDebug;

/**
 * Allows the user to change the app preferences.
 */
public class SettingsActivity
extends AppPrefsDebug
implements SharedPreferences.OnSharedPreferenceChangeListener
{
    static private final String TAG = SettingsActivity.class.getSimpleName() ;

    @Override
    protected void setup()
    {
        super.setup() ;
        PreferenceManager.getDefaultSharedPreferences( this )
            .registerOnSharedPreferenceChangeListener( this ) ;
    }

    @Override
    protected void onResume()
    {
        super.onResume() ;
        this.resetPrefScreens() ;
    }

    @Override
    protected void onDestroy()
    {
        PreferenceManager.getDefaultSharedPreferences( this )
            .unregisterOnSharedPreferenceChangeListener( this ) ;
        super.onDestroy() ;
    }

    @Override
    public void onSharedPreferenceChanged( SharedPreferences prefs, String sPrefKey )
    {
        Log.d(TAG, (new StringBuilder())
                .append( "Preference [" )
                .append( sPrefKey )
                .append( "] changed." )
                .toString()
            );
    }

}


text:
class RailsScopesHandler < YardRailsPack::Base

  ### DSL methods to handle

  handles method_call(:scope)

  def process
    object = object_for_namespace
    (object[:scopes] ||= []) << statement.source
  end
end


text:
layout: post
title: Upgrading Azure Storage Python SDK to support asyncio
picture: https://raw.githubusercontent.com/RobertoPrevato/robertoprevato.github.io/master/images/posts/azurestoragepython/banner.png
---

In the last months I had occasion to use [Azure Storage](https://azure.microsoft.com/en-us/services/storage/?v=16.50) as primary persistence layer for a document management system for [my employer, William Demant Holding](https://www.demant.com). For those who don't know it, Azure Storage is a cloud based storage service by Microsoft, comprised of several services:
* **Table Service** - NoSQL database
* **Blob Service** - binary files storage, with support for virtual folders
* **Queue Service** - simple, cost-effective messaging system for large volume systems
* **File Service** - distributed file system

Azure Storage is cost effective and really convenient to store files and tabular data that don't require complex queries, even in large quantities.

All these services include [REST APIs](https://docs.microsoft.com/en-us/rest/api/storageservices/azure-storage-services-rest-api-reference) that enable programmatic access and administration via HTTP/HTTPS. Even though these REST APIs can be used directly, Microsoft distributes several client SDKs to simplify their consumption with some of the most popular programming languages.

* [Microsoft Azure Storage SDK for .NET](https://github.com/Azure/azure-storage-net)
* [Microsoft Azure Storage SDK for Python](https://github.com/Azure/azure-storage-python)
* [Microsoft Azure Storage SDK for Node.js](https://github.com/Azure/azure-storage-node)
* [Microsoft Azure Storage SDK for Java](https://github.com/Azure/azure-storage-java)
* [Microsoft Azure Storage SDK for PHP](https://github.com/Azure/azure-storage-php)
* [Microsoft Azure Storage SDK for C++](https://github.com/Azure/azure-storage-cpp)
* [Microsoft Azure Storage SDK for Ruby](https://github.com/Azure/azure-storage-ruby)
* [Microsoft Azure Storage SDK for iOS (preview)](https://github.com/Azure/azure-storage-ios)

These SDKs are necessary because certain operations are not trivial when trying to consume the APIs directly, for example the configuration of [authentication headers](https://docs.microsoft.com/en-us/rest/api/storageservices/authentication-for-the-azure-storage-services).

I mainly use .NET Framework and .NET Core at work, but when I code in my private time and for fun, I prefer to use Python. I am planning to use Azure Storage for my future private projects and I am also planning to use the newest versions of Python with latest features and performance improvements. Unfortunately for me and those who want to do the same, the official Python SDKs by Microsoft are designed to work across all Python versions (like described in [this discussion in GitHub](https://github.com/Azure/azure-sdk-for-python/issues/496)), thus sacrificing the coolest features that are only available in Python 3.

In the case of Azure Storage SDK, this translates into sacrificing support for asynchronous, non blocking web requests that could be implemented using the built-in [`asyncio`](https://docs.python.org/3/library/asyncio.html) infrastructure for event loops, available since version `3.5` of the programming language1.

To be more specific, the official Azure Storage SDK for Python uses [`requests`](http://docs.python-requests.org/en/master/) by Kenneth Reitz to make web requests, which is a wonderful library, but doesn't implement asynchronous calls.

Reimplementing a new SDK for Python from scratch would be a bad idea, because most of the logic available in the official repository is reusable. I decided to try to edit the source code of the official library, to integrate [`asyncio`](https://aiohttp.readthedocs.io/en/stable/glossary.html#term-asyncio) and [`aiohttp`, which is one implementation of HTTP Client/Server for asyncio](https://aiohttp.readthedocs.io/en/stable/), and see if this approach is feasible. The objective is to find the root function making web requests, replace it with an asynchronous implementation, then traverse back up the call stack to make all calling functions asynchronous, too. To do so effectively (and without losing your mind), it is necessary to debug the source code.

This post describes the steps to achieve this objective. Those who want to try the final result without reading through, can simply [clone my fork](https://github.com/RobertoPrevato/azure-storage-python.git) and use it.

## 1. Forking and cloning the original repository
Since the source code of the SDKs is public in GitHub, the [original repository](https://github.com/Azure/azure-storage-python) was simply forked and cloned locally. Thanks to Satya Nadella for driving Microsoft to embrace open source! I never liked .NET and MS products so much.

```bash
git clone https://github.com/Azure/azure-storage-python.git
```

## 2. Preparing the virtual environment
Like described in the README of the official repository, the source code of the Python SDK is organized in several packages. `azure-storage-common` is, as the name suggests, used by the other projects and contains common code. The picture below illustrates the folder structure of the repository; I decided to start from the Blob service2.

![Repo folder structure](https://raw.githubusercontent.com/RobertoPrevato/robertoprevato.github.io/a2e03e16a2cab29f2b937a5e48db43aa8f8ac502/images/posts/azurestoragepython/repo-folder-structure.png)

cd into `azure-storage-blob` and create a virtual environment for Python 3.
```bash
cd azure-storage-blob

# Windows:
py -3 -m venv env

# Linux (example, of course depends on $PATH)
python3 -m venv env
```

Activate the environment
```bash
# Windows
env\Scripts\activate

# Linux
source env\bin\activate
```

We need to install the dependencies of `azure-storage-blob`, which are described in its `requirements.txt`:
```bash
pip install -r requirements.txt
```

Then we also install `azure-storage-common` in development mode.
Since we know we are going to need a few extra packages for `azure-storage-common`, we must edit its `install_requires` configuration inside `setup.py`, to include `aiohttp`, `aiodns`, `cchardet` (the last two are [recommended dependencies for aiohttp](http://aiohttp.readthedocs.io/en/v0.17.2/index.html)).

```python
    install_requires=[
                         'azure-common>=1.1.5',
                         'cryptography',
                         'python-dateutil',
                         'requests',
                         'aiohttp',  # <--
                         'aiodns',   # <--
                         'cchardet', # <--
```

Install `azure-storage-common` in development mode, from file system and using the relative path:
```
pip install -e ..\azure-storage-common
```

This last step is important because it enables debugging and editing the `azure-storage-common` package on the fly, while running code in other libraries that depend on it. Development mode is a great feature of Python package manager.

## 3. Debugging
My favorite IDE for Python is [PyCharm](https://www.jetbrains.com/pycharm/specials/pycharm/pycharm.html) by JetBrains and I use it to debug.

![PyCharm](https://raw.githubusercontent.com/RobertoPrevato/robertoprevato.github.io/c8aef5e7316f3f3983d4127efcd12d26196acdb4/images/posts/azurestoragepython/pycharm-banner.png)

The original repository contains unit and integration tests, but since the objective is to investigate the source code, it is easier to simply add new tests. By the way, this is made easier by the fact that tests in the original repository are contained in a dedicated folder at the root of the repository.

Adding a new `tests` folder and a new `test_whatever_name.py` in it, with code below, enables debugging of Python SDK source code.

```python
import unittest
from azure.storage.blob import BlockBlobService

import logging
logging.basicConfig(format='%(asctime)s %(name)-20s %(levelname)-5s %(message)s', level=logging.INFO)

TEST_CONTAINER_PREFIX = 'container'

ACCOUNT_NAME = '<account name>'
ACCOUNT_KEY = '<account admin key>'

class TestContainers(unittest.TestCase):

    def setUp(self):
        self.bs = BlockBlobService(account_name=ACCOUNT_NAME,
                                   account_key=ACCOUNT_KEY)
        self.test_containers = []

    def test_list_containers(self):
        containers = self.bs.list_containers()

        for container in containers:
            print(container.name)

    def OFF_test_upload_blob(self):

        self.bs.create_blob_from_text("tests", "hello-world.txt", "Hello World")
```

### 3.1 Preparing a Storage Account
I ran my tests against a real instance of storage account, having a couple of containers and test files. Account name and one of its administrative keys are sufficient to execute the code above.
As a side note, I had problem using the Python SDK with the [Azure Storage Emulator](https://docs.microsoft.com/en-us/azure/storage/common/storage-use-emulator).

![Storage account](https://raw.githubusercontent.com/RobertoPrevato/robertoprevato.github.io/c8aef5e7316f3f3983d4127efcd12d26196acdb4/images/posts/azurestoragepython/storage-account.png)

### 3.2 Looking for the root function to change
Everything is setup to start debugging and investigating the original library. I started from the `list_containers` function.

```python
    def test_list_containers(self):
        containers = self.bs.list_containers()  # <-- put a break point here
```

_Stepping into..._

![Debugging 01](https://raw.githubusercontent.com/RobertoPrevato/robertoprevato.github.io/c8aef5e7316f3f3983d4127efcd12d26196acdb4/images/posts/azurestoragepython/debugging-01.png)

_Getting closer..._

![Debugging 02](https://raw.githubusercontent.com/RobertoPrevato/robertoprevato.github.io/c8aef5e7316f3f3983d4127efcd12d26196acdb4/images/posts/azurestoragepython/debugging-02.png)

_Bingo!_

![Debugging 03](https://raw.githubusercontent.com/RobertoPrevato/robertoprevato.github.io/c8aef5e7316f3f3983d4127efcd12d26196acdb4/images/posts/azurestoragepython/debugging-03.png)

The piece of code illustrated in the above picture is the first one to change, in order to integrate with `asyncio`.

This piece of code is the one that delegates to `requests` library the duty of making a web request to Blob Service REST API:
```python
        # Send the request
        response = self.session.request(request.method,
                                        uri,
                                        params=request.query,
                                        headers=request.headers,
                                        data=request.body or None,
                                        timeout=self.timeout,
                                        proxies=self.proxies)
```

## 4. Editing the source code to use asyncio

Switching between `requests` and `aiohttp` is not _that complicated_, since both implement their own kind of HTTP client session having similar functions. We simply need to replace the session object with a session from `aiohttp` and adjust the input parameters accordingly.

The session object is set in a single place of the code, inside the `azure.storage.common.StorageClient` class, which was modified to use the `ClientSession` implementation from `aiohttp`.

```python
def get_aiohttp_session():
    try:
        loop = asyncio.get_event_loop()
    except RuntimeError:
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
    return aiohttp.ClientSession(loop=loop)

## Later...

        # TODO: eventually define an interface for "SessionProvider", to support alternative implementations
        request_session = connection_params.request_session or get_aiohttp_session()
```

Then, I edited the code calling the `request` method of the session to handle differences between the two libraries:

```python
        query_string = urllib.parse.urlencode(request.query)

        response = await self.session.request(request.method,
                                          uri,
                                          params=query_string,
                                          headers=request.headers,
                                          data=request.body,
                                          timeout=self.timeout,
                                         ) # proxies=self.proxies -- apparently aiohttp can have one proxy, not many (https://docs.aiohttp.org/en/stable/client_reference.html)
```

The method was adapted to use `async` and `await` syntax:

```python
    async def perform_request(self, request):
        '''
        Sends an HTTPRequest to Azure Storage and returns an HTTPResponse. If
        the response code indicates an error, raise an HTTPError.
```

Similarly, I traversed the callstack backward, adding `await` and `async` to all calling functions up to the root `list_containers` function of `azure.storage.blob.BlockBlobService` class.

The unit test code was prepared to run asynchronous methods, too:

```python
import asyncio
import unittest
from azure.storage.blob import BlockBlobService

import logging
logging.basicConfig(format='%(asctime)s %(name)-20s %(levelname)-5s %(message)s', level=logging.INFO)

TEST_CONTAINER_PREFIX = 'container'

ACCOUNT_NAME = '<account name>'
ACCOUNT_KEY = '<account admin key>'

class TestContainers(unittest.TestCase):

    def setUp(self):
        self.loop = asyncio.get_event_loop()
        self.bs = BlockBlobService(account_name=ACCOUNT_NAME,
                                   account_key=ACCOUNT_KEY)
        self.test_containers = []

    def test_list_containers_async(self):
        async def go():
            containers = await self.bs.list_containers()

            for container in containers:
                print(container.name)

        self.loop.run_until_complete(go())

    def test_upload_blob_async(self):
        async def go():
            await self.bs.create_blob_from_text("tests", "hello-world.txt", "Hello World")

        self.loop.run_until_complete(go())
```

This way, I rapidly edited three read functions to be asynchronous: `list_containers`, `get_blob_metadata`, `list_blobs`. Note that the only I/O bound operations in this library are those interacting with the REST APIs. Arguably, the most complex code in `azure-storage-common` is the one creating and handling `Shared Access Signatures`, and this is CPU bound, so we don't need to touch it.

To simplify the process, I cloned again the [original repository](https://github.com/Azure/azure-storage-python) in a second folder and prepared an environment for debugging, like described above. This way it's possible to debug the original, working, code while working on edited (and often broken) code.

---

I then modified two write functions: `set_blob_metadata`, `create_blob_from_text`. In this case there was a minor problem: Authentication header was invalid because `aiohttp` is adding extra headers before shooting the REST API, hence invalidating the signed token.

The solution was found simply, comparing the headers sent by original code using `requests` with the headers sent by `aiohttp`. A quick workaround is to make Azure library aware of these extra headers, before creating the signed access token.

```python
                    # NB: aiohttp adds extra headers that would break the authentication token
                    request.headers.update({
                        'Accept': '*/*',
                        'Accept-Encoding': 'gzip, deflate',
                        'Host': f'{self.account_name}.blob.core.windows.net',
                        'Content-Type': 'application/octet-stream'
                    })

                    self.authentication.sign_request(request)
```

Of course a better solution would be to disable these extra headers in `aiohttp`, but this workaround is sufficient for the time being.

**Eureka!** In a couple of hours I managed to integrate `asyncio` in five functions and it wasn't really hard. With a small effort, I could help Python community by completing an alternative Python SDK for Azure Storage, supporting asynchronous calls; and I am willing to do so. An fork in GitHub could be easily installed by others, simply cloning the repository and installing the dependency from file system, and it doesn't look impossible to maintain. Azure Storage REST APIs are not going to change *that often*, hopefully.

I am willing to help Python community using Azure. **Join me, if you will!**

---

#### Notes
1. This is not to say that there aren't options to implement asynchronous web clients and servers in Python 2: some of them were implemented way before the original [Node.js presentation by Ryan Dahl](https://www.youtube.com/watch?v=ztspvPYybIY) (e.g Tornado, Twisted, Gevent), anyway none of them are completely cross platforms and work in both Python 2 and 3 - please correct me if I am wrong -.
2. Interestingly, the client for the Table Service was recently removed from this repository and merged to [CosmosDB SDK](https://github.com/Azure/azure-cosmosdb-python), because the two services [(Table Service and CosmosDB Table) share the same API](https://docs.microsoft.com/en-us/azure/cosmos-db/table-support). The choice in naming looks confusing to me, since CosmosDB and Azure Storage are two different services, and the client for Table Service in the Storage service is now published under the CosmosDB specific namespace.


text:
@interface FNScriptTests : SenTestCase

@end


text:
//
//  BitlyConfig.h
//  BitlyLib
//
//  Created by Tracy Pesin on 8/4/11.
//  Copyright 2011 Betaworks. All rights reserved.
//

#import <Foundation/Foundation.h>

extern NSString * const BitlyTwitterRequestTokenURL;
extern NSString * const BitlyTwitterAccessTokenURL;
extern NSString * const BitlyTwitterAuthorizeURLFormat;

@interface BitlyConfig: NSObject

@property(nonatomic, retain) NSString *bitlyLogin;
@property(nonatomic, retain) NSString *bitlyAPIKey;

@property(nonatomic, retain) NSString *twitterOAuthConsumerKey;
@property(nonatomic, retain) NSString *twitterOAuthConsumerSecret;
@property(nonatomic, retain) NSString *twitterOAuthSuccessCallbackURL;

+ (BitlyConfig *)sharedBitlyConfig;

/** BITLY CREDENTIALS **/
/* These are your api keys to bitly. They can be created at http://bitly.com/a/sign_up
 */
- (void)setBitlyLogin:(NSString *)bitlyLogin bitlyAPIKey:(NSString *)bitlyAPIKey;

/** TWITTER CREDENTIALS **/
/*These are your api keys to twitter. They can be created at https://dev.twitter.com/apps/
IMPORTANT: You must set a callback URL, even though the user will never see that page. The application will intercept redirects to that URL and act accordingly. As an example, our project uses @"http://twitterauthsuccess.bit.ly";
*/
- (void)setTwitterOAuthConsumerKey:(NSString *)consumerKey
twitterOAuthConsumerSecret:(NSString *)consumerSecret
twitterOAuthSuccessCallbackURL:(NSString *)successCallbackURL;

@end


text:
package com.auth0.json.mgmt.attackprotection;

import com.auth0.json.JsonMatcher;
import com.auth0.json.JsonTest;
import org.junit.Test;

import java.util.Arrays;
import java.util.List;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;

public class SuspiciousIPThrottlingConfigurationTest extends JsonTest<SuspiciousIPThrottlingConfiguration> {

    private final String json = "{\n" +
        "  \"enabled\": false,\n" +
        "  \"shields\": [\n" +
        "    \"block\",\n" +
        "    \"admin_notification\"\n" +
        "  ],\n" +
        "  \"allowlist\": [\n" +
        "    \"143.204.0.105\",\n" +
        "    \"2600:9000:208f:ca00:d:f5f5:b40:93a1\"\n" +
        "  ],\n" +
        "  \"stage\": {\n" +
        "    \"pre-login\": {\n" +
        "      \"max_attempts\": 100,\n" +
        "      \"rate\": 864000\n" +
        "    },\n" +
        "    \"pre-user-registration\": {\n" +
        "      \"max_attempts\": 50,\n" +
        "      \"rate\": 1728000\n" +
        "    }\n" +
        "  }\n" +
        "}";

    @Test
    public void shouldDeserialize() throws Exception {
        SuspiciousIPThrottlingConfiguration config = fromJSON(json, SuspiciousIPThrottlingConfiguration.class);

        assertThat(config, is(notNullValue()));
        assertThat(config.getEnabled(), is(false));
        assertThat(config.getShields(), is(Arrays.asList("block", "admin_notification")));
        assertThat(config.getAllowList(), is(Arrays.asList("143.204.0.105", "2600:9000:208f:ca00:d:f5f5:b40:93a1")));
        assertThat(config.getStage(), is(notNullValue()));
        assertThat(config.getStage().getPreLoginStage(), is(notNullValue()));
        assertThat(config.getStage().getPreLoginStage().getMaxAttempts(), is(100));
        assertThat(config.getStage().getPreLoginStage().getRate(), is(864000));
        assertThat(config.getStage().getPreUserRegistrationStage(), is(notNullValue()));
        assertThat(config.getStage().getPreUserRegistrationStage().getMaxAttempts(), is(50));
        assertThat(config.getStage().getPreUserRegistrationStage().getRate(), is(1728000));

    }

    @Test
    public void shouldSerialize() throws Exception {
        List<String> allowList = Arrays.asList("123", "456");
        List<String> shields = Arrays.asList("block", "user_notification");

        StageEntry preLogin = new StageEntry();
        preLogin.setMaxAttempts(100);
        preLogin.setRate(864000);

        StageEntry preRegistration = new StageEntry();
        preLogin.setMaxAttempts(50);
        preLogin.setRate(1728000);

        Stage stage = new Stage();
        stage.setPreLoginStage(preLogin);
        stage.setPreUserRegistrationStage(preRegistration);

        SuspiciousIPThrottlingConfiguration config = new SuspiciousIPThrottlingConfiguration();
        config.setEnabled(true);
        config.setAllowList(allowList);
        config.setShields(shields);
        config.setStage(stage);

        String json = toJSON(config);

        assertThat(json, JsonMatcher.hasEntry("enabled", true));
        assertThat(json, JsonMatcher.hasEntry("shields", shields));
        assertThat(json, JsonMatcher.hasEntry("allowlist", allowList));
        assertThat(json, JsonMatcher.hasEntry("stage", is(notNullValue())));
    }
}


text:
namespace syntaxnet {

// Returns OK if the |input_index|'th input is a tensor of the |rank| with
// unknown dimensions.
inline tensorflow::Status TensorInputShape(
    int input_index, int rank,
    tensorflow::shape_inference::InferenceContext *context) {
  tensorflow::shape_inference::ShapeHandle unused;
  return context->WithRank(context->input(input_index), rank, &unused);
}

// Returns OK if the |input_index|'th input is a scalar.
inline tensorflow::Status ScalarInputShape(
    int input_index, tensorflow::shape_inference::InferenceContext *context) {
  return TensorInputShape(input_index, 0, context);
}

// Returns OK if the |input_index|'th input is a vector of unknown dimension.
inline tensorflow::Status VectorInputShape(
    int input_index, tensorflow::shape_inference::InferenceContext *context) {
  return TensorInputShape(input_index, 1, context);
}

// Returns OK if the |input_index|'th input is a matrix of unknown dimensions.
inline tensorflow::Status MatrixInputShape(
    int input_index, tensorflow::shape_inference::InferenceContext *context) {
  return TensorInputShape(input_index, 2, context);
}

// Sets the |output_index|'th output to a scalar.
inline void ScalarOutputShape(
    int output_index, tensorflow::shape_inference::InferenceContext *context) {
  context->set_output(output_index, context->Scalar());
}

// Sets the |output_index|'th output to a vector of unknown dimension.
inline void VectorOutputShape(
    int output_index, tensorflow::shape_inference::InferenceContext *context) {
  context->set_output(output_index, context->UnknownShapeOfRank(1));
}

// Sets the |output_index|'th output to a matrix of unknown dimensions.
inline void MatrixOutputShape(
    int output_index, tensorflow::shape_inference::InferenceContext *context) {
  context->set_output(output_index, context->UnknownShapeOfRank(2));
}

}  // namespace syntaxnet

#endif  // SYNTAXNET_OPS_SHAPE_HELPERS_H_


text:
from impeller.workbook import Workbook

# TEST()

import time
import datetime

ROWS = 10**5
COLS = 10

c_wb = Workbook("Юникод имя_c.xlsx")
c_wb.set_properties({"author": " Ζεύς", "company": "كما"})
c_wb.set_custom_property("Кастом юникод дата", datetime.datetime.now())
c_ws = c_wb.add_worksheet("Ünicode shëët!")
start = time.clock()
bold_format = c_wb.add_format()
bold_format.set_bold()
for i in range(ROWS):
    for j in range(COLS):
        # row, col, data
        c_ws.write_number(i, j, i + j, None if i else bold_format)
c_ws.set_column(0, 2, 30)
c_ws.set_column("C:E", 50)
start_close = time.clock()
c_wb.close()
end_close = time.clock()
end = time.clock()
print("Close time:", format(end_close - start_close, ".2f"), "Total:", format(end - start, ".2f"))


text:
import {A11yModule} from '@angular/cdk/a11y';
import {NgModule} from '@angular/core';
import {RouterModule} from '@angular/router';
import {FocusOriginDemo} from './focus-origin-demo';

@NgModule({
  imports: [
    A11yModule,
    RouterModule.forChild([{path: '', component: FocusOriginDemo}]),
  ],
  declarations: [FocusOriginDemo],
})
export class FocusOriginDemoModule {
}


text:
package com.quakearts.webtools.resteasy.cdi.test.helpers;

import javax.inject.Inject;
import javax.transaction.Status;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import com.quakearts.appbase.cdi.annotation.Transaction;
import com.quakearts.appbase.cdi.annotation.Transactional;
import com.quakearts.appbase.cdi.annotation.Transactional.TransactionType;
import com.quakearts.webtools.resteasy.cdi.test.experiments.TestInject;

@Path("/test")
public class TestResource {

	private static boolean transactionWorked;
	private static String content;

	@Inject
	private TestInject testService;

	@Inject @Transaction
	private UserTransaction transaction;

	@GET
	@Produces(MediaType.TEXT_PLAIN)
	public String get(){
		testService.sayHello();
		return "OK";
	}

	@POST
	@Produces(MediaType.TEXT_PLAIN)
	@Consumes(MediaType.TEXT_PLAIN) @Transactional(TransactionType.SINGLETON)
	public TestParameter post(TestParameter parameter) {
		try {
			transactionWorked = transaction != null && transaction.getStatus() == Status.STATUS_ACTIVE;
			content = parameter.getContent();
		} catch (SystemException e) {
		}
		return parameter;
	}

	public static boolean transactionWorked() {
		return transactionWorked;
	}

	public static String getContent() {
		return content;
	}
}


text:
package dinamica.util;

import java.io.File;

/*
 * http://my.oschina.net/webas/blog/108427
 */

public class MavenInstallJar {

    private String dir = "D:/bxdev/github/codegen4/lib";
    private String groupId = "com.aliyun";
    private String version = "1.0";

    private void outputInstallJarBatchFile() {
        File d = new File(dir);
        File[] fs = d.listFiles();
        for(File f : fs) {
            String name = f.getName().toLowerCase();
            String fileName = name;
            if(f.isFile() && name.endsWith(".jar")) {
                name = name.replaceAll(".jar", "");
                String[] ns = name.split("-");
                String artifactId = ns[0];
                StringBuffer sb = new StringBuffer();
                sb = new StringBuffer();
                sb.append("mvn install:install-file -DgroupId=").append(groupId);
                sb.append(" -DartifactId=").append(artifactId);
                sb.append(" -Dversion=").append(version);
                sb.append(" -Dfile=").append(fileName);
                sb.append(" -Dpackaging=jar -DgeneratePom=true");
                System.out.println(sb.toString());
            }
        }
    }

    private void printDependency() {
        File d = new File(dir);
        File[] fs = d.listFiles();
        for(File f : fs) {
            String name = f.getName().toLowerCase();
            if(f.isFile() && name.endsWith(".jar")) {
                name = name.replaceAll(".jar", "");
                String[] ns = name.split("-");
                String artifactId = ns[0];
                StringBuffer sb = new StringBuffer();
                sb.append("<dependency>\n");
                sb.append("  <groupId>").append(groupId).append("</groupId>\n");
                sb.append("  <artifactId>").append(artifactId).append("</artifactId>\n");
                sb.append("  <version>").append(version).append("</version>\n");
                sb.append("</dependency>");
                System.out.println(sb.toString());
            }
        }
    }
    public static void main(String[] args) {
        MavenInstallJar inst = new MavenInstallJar();
        inst.outputInstallJarBatchFile();
        inst.printDependency();
    }
}


text:
layout: default
title: Portfólio
name: portfolio
---

Portfólio

Alguns projetos que tive prazer em estar envolvido como desenvolvedor nos últimos tempos.

            {% for case in site.data.cases %}

{{ case.name }}

{{ case.description }}

                                Visitar

            {% endfor %}


text:
var fail = require('./failure').fail
  , elementary = require('./elementary')

exports = module.exports = {
  isTypeof: function (actual, expected, message){
    if(expected !== typeof actual)
      throw fail(new Error()).simple('isTypeOf', actual, expected, 'typeof', message)
  }
, isInstanceof: function (actual,expected,message){
    if(!(actual instanceof expected))
      throw fail(new Error()).simple('isInstanceof', actual, expected, 'instanceof', message)
  }
, isArray: function (actual, message) {
    if(!Array.isArray(actual))
      throw fail(new Error()).explain('isArray: Array.isArray({actual:render})', {actual: actual}, message)
  }
, primitive: function (actual,message){
    if(!('function' !== typeof actual && 'object' !== typeof actual ))
      throw fail(new Error()).explain('primitive: {actual:render} must not be a function or an object', {actual: actual}, message)
  }
, complex: function (actual,message){
    if(!('function' == typeof actual || 'object' == typeof actual ))
      throw fail(new Error()).explain('complex: {actual:render} must be a function or an object', {actual: actual}, message)
  }
, isFunction: function (actual, message){
    if(!('function' == typeof actual))
      throw fail(new Error()).explain('isFunction: "function" == typeof {actual:render}', {actual: actual}, message)
  }
, matches : function (input, pattern, message) {
    if(!pattern.test(input))
      throw fail(new Error()).simple('matches', input, pattern, 'must match', message)
  }
, like: function (actual, expected, respect, message) {
    respect = respect || {}
    var op = 'like({' +
      [ respect.case ? 'case: true' : ''
      , respect.whitespace ? 'whitespace: true' : ''
      , respect.quotes ? 'quotes: true' : ''
      ].join()
      + '})'

    var a = '' + actual, e = '' + expected

    if(!respect.case) {
      a = a.toLowerCase()
      e = e.toLowerCase()
    }
    if(!respect.whitespace) {
      a = a.replace(/\s/g,'')
      e = e.replace(/\s/g,'')
    }
    if(!respect.quotes) {
      a = a.replace(/\"|\'/g,'\"')
      e = e.replace(/\"|\'/g,'\"')
    }

    if(! (a == e))
      throw fail(new Error()).simple('like', a, e, 'must be like', message)
  }
, lessThan: function (actual, expected, message) {
    if(!(actual < expected))
      throw fail(new Error()).simple('lessThan', actual, expected, '<', message)
  }
, greaterThan: function (actual, expected, message) {
    if(!(actual > expected))
      throw fail(new Error()).simple('greaterThan', actual, expected, '>', message)
  }
, lessThanOrEqual: function (actual, expected, message) {
    if(!(actual <= expected))
      throw fail(new Error()).simple('lessThanOrEqual', actual, expected, '<=', message)
  }
, greaterThanOrEqual: function (actual,expected, message) {
    if(!(actual >= expected))
      throw fail(new Error()).simple('greaterThanOrEqual', actual, expected, '>=', message)
  }
, between: function (actual, hi, lo, message) {
    if (lo > hi) {
      var tmp = hi; hi = lo; lo = tmp;
    }
    if(!(actual > lo && actual < hi))
      throw fail(new Error()).explain('between:{min} < {actual} < {max}', {actual: actual, min: lo, max: hi}, message)
  }
, betweenOrEqual: function (actual, hi, lo, message) {
    if (lo > hi) {
      var tmp = hi; hi = lo; lo = tmp;
    }
    if(!(actual >= lo && actual <= hi))
      throw fail(new Error()).explain('betweenOrEqual:{min} <= {actual} <= {max}', {actual: actual, min: lo, max: hi}, message)
  }
, isValidDate: function (actual, message) {
    var parsed = new Date(actual)
    if('Invalid Date' == parsed)
      throw fail(new Error()).explain('isValidDate:{actual} must be valid date', {actual: actual, min: lo, max: hi}, message)
  }
, contains: function (actual, expected, message) {
    var i = actual.indexOf(expected)
    if(-1 === i)
      throw fail(new Error()).simple('contains', actual, expected, 'contains', message)
  }
, includes: function (actual, expected, message) {
    var i = expected.indexOf(actual)
    if(-1 === i)
      throw fail(new Error()).simple('includes', actual, expected, 'includes', message)
  }
, isString: function (actual, message) {
    exports.isTypeof(actual, 'string', message)
  }
, isNumber: function (actual, message) {
    exports.isTypeof(actual, 'number', message)
  }
, isBoolean: function (actual, message) {
    exports.isTypeof(actual, 'boolean', message)
  }
, isUndefined: function (actual, message) {
    exports.isTypeof(actual, 'undefined', message)
  }
, isNull: function (actual, message) {
    elementary.strictEqual(actual, null, message)
  }
, isEmpty: function (actual, message) {
    elementary.deepEqual(actual, [], message)
  }
}


text:
#include "converter_raw.h"
#include "converter_dxt.h"
#include "converter_z.h"
//#include "converter_webp.h"
#include "converterfactory.h"

namespace tc {

ConverterPtr ConverterFactory::GetConverter(const Options& options, unsigned type) noexcept
{
  type &= 0xff;
  switch (type) {
    case ENCODE_RAW:
      // No conversion: RAW encoder/decoder
      return ConverterPtr(new ConverterRaw(options, type));
    case ENCODE_DXT1:
    case ENCODE_DXT3:
    case ENCODE_DXT5:
      // DXTn encoder/decoder
      return ConverterPtr(new ConverterDxt(options, type));
//    case ENCODE_WEBP:
      // WebP encoder/decoder
//      return ConverterPtr(new ConverterWebP(options, type));
    case ENCODE_Z:
      // MOZ/TIZ decoder
      return ConverterPtr(new ConverterZ(options, type));
    default:
      return nullptr;
  }
}

}   // namespace tc


text:
@interface AFURLConnectionOperationTests : SenTestCase
@property (readwrite, nonatomic, strong) NSURL *baseURL;
@end

@implementation AFURLConnectionOperationTests

- (void)setUp {
    self.baseURL = [NSURL URLWithString:AFNetworkingTestsBaseURLString];
}

#pragma mark -

- (void)testThatAFURLConnectionOperationInvokesWillSendRequestForAuthenticationChallengeBlock {
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/path" relativeToURL:self.baseURL]];
    AFURLConnectionOperation *operation = [[AFURLConnectionOperation alloc] initWithRequest:request];

    __block BOOL willSendRequestForAuthenticationChallengeBlockInvoked = NO;
    [operation setWillSendRequestForAuthenticationChallengeBlock:^(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge) {
        willSendRequestForAuthenticationChallengeBlockInvoked = YES;
    }];

    [AFMockURLProtocol handleNextRequestForURL:request.URL usingBlock:^(AFMockURLProtocol <AFMockURLProtocolProxy> * protocol) {

        void(^startOperation)(NSInvocation *invocation) = ^(NSInvocation *invocation) {
            __unsafe_unretained AFMockURLProtocol *protocol = nil;
            [invocation getArgument:&protocol atIndex:0];

            NSURLProtectionSpace *protectionSpace = [[NSURLProtectionSpace alloc] initWithHost:request.URL.host port:request.URL.port.integerValue protocol:request.URL.scheme realm:nil authenticationMethod:NSURLAuthenticationMethodDefault];
            NSURLAuthenticationChallenge *authenticationChallenge = [[NSURLAuthenticationChallenge alloc] initWithProtectionSpace:protectionSpace proposedCredential:nil previousFailureCount:0 failureResponse:nil error:nil sender:protocol];
            [protocol.client URLProtocol:protocol didReceiveAuthenticationChallenge:authenticationChallenge];
        };
        [[[protocol stub] andDo:startOperation] startLoading];
    }];

    [operation start];
    expect(willSendRequestForAuthenticationChallengeBlockInvoked).will.beTruthy();

    [operation cancel];
}

- (void)testThatAFURLConnectionOperationTrustsPinnedCertificates {
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/path" relativeToURL:self.baseURL]];
    AFURLConnectionOperation *operation = [[AFURLConnectionOperation alloc] initWithRequest:request];
    operation.SSLPinningMode = AFSSLPinningModeCertificate;

    __block BOOL useCredentialInvoked = NO;

    NSURLProtectionSpace *protectionSpace = [[NSURLProtectionSpace alloc] initWithHost:request.URL.host port:request.URL.port.integerValue protocol:request.URL.scheme realm:nil authenticationMethod:NSURLAuthenticationMethodServerTrust];

    NSData *certificateData = [NSData dataWithContentsOfFile:[[NSBundle bundleForClass:[self class]] pathForResource:@"root_certificate" ofType:@"cer"]];
    NSParameterAssert(certificateData);

    SecCertificateRef certificate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certificateData);
    NSParameterAssert(certificate);

    SecCertificateRef allowedCertificates[] = {certificate};
    CFArrayRef certificates = CFArrayCreate(NULL, (const void **)allowedCertificates, 1, NULL);

    SecPolicyRef policy = SecPolicyCreateBasicX509();
    SecTrustRef trust = NULL;
    OSStatus status = SecTrustCreateWithCertificates(certificates, policy, &trust);
    NSAssert(status == errSecSuccess, @"SecTrustCreateWithCertificates error: %ld", (long int)status);

    SecTrustResultType result;
    status = SecTrustEvaluate(trust, &result);
    NSAssert(status == errSecSuccess, @"SecTrustEvaluate error: %ld", (long int)status);

    id mockedProtectionSpace = [OCMockObject partialMockForObject:protectionSpace];

    [[[mockedProtectionSpace stub] andDo:^(NSInvocation *invocation) {
        [invocation setReturnValue:(void *)&trust];
    }] serverTrust];

    AFMockURLProtocol *protocol = [[AFMockURLProtocol alloc] initWithRequest:request cachedResponse:nil client:nil];
    id mockedProtocol = [OCMockObject partialMockForObject:protocol];

    void(^useCredential)(NSInvocation *invocation) = ^(NSInvocation *invocation) {
        useCredentialInvoked = YES;
    };

    [[[mockedProtocol stub] andDo:useCredential] useCredential:OCMOCK_ANY forAuthenticationChallenge:OCMOCK_ANY];

    NSURLCredential *credential = [[NSURLCredential alloc] initWithTrust:trust];
    NSURLAuthenticationChallenge *authenticationChallenge = [[NSURLAuthenticationChallenge alloc] initWithProtectionSpace:protectionSpace proposedCredential:credential previousFailureCount:0 failureResponse:nil error:nil sender:mockedProtocol];
    [protocol.client URLProtocol:mockedProtocol didReceiveAuthenticationChallenge:authenticationChallenge];

    [operation connection:nil willSendRequestForAuthenticationChallenge:authenticationChallenge];

    CFRelease(trust);
    CFRelease(policy);
    CFRelease(certificates);
    CFRelease(certificate);

    expect(useCredentialInvoked).will.beTruthy();
}

- (void)testThatAFURLConnectionOperationTrustsPinnedPublicKeys {
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/path" relativeToURL:self.baseURL]];
    AFURLConnectionOperation *operation = [[AFURLConnectionOperation alloc] initWithRequest:request];
    operation.SSLPinningMode = AFSSLPinningModePublicKey;

    __block BOOL useCredentialInvoked = NO;

    NSURLProtectionSpace *protectionSpace = [[NSURLProtectionSpace alloc] initWithHost:request.URL.host port:request.URL.port.integerValue protocol:request.URL.scheme realm:nil authenticationMethod:NSURLAuthenticationMethodServerTrust];

    NSData *certificateData = [NSData dataWithContentsOfFile:[[NSBundle bundleForClass:[self class]] pathForResource:@"root_certificate" ofType:@"cer"]];
    NSParameterAssert(certificateData);

    SecCertificateRef certificate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certificateData);
    NSParameterAssert(certificate);

    SecCertificateRef allowedCertificates[] = {certificate};
    CFArrayRef certificates = CFArrayCreate(NULL, (const void **)allowedCertificates, 1, NULL);

    SecPolicyRef policy = SecPolicyCreateBasicX509();
    SecTrustRef trust = NULL;
    OSStatus status = SecTrustCreateWithCertificates(certificates, policy, &trust);
    NSAssert(status == errSecSuccess, @"SecTrustCreateWithCertificates error: %ld", (long int)status);

    SecTrustResultType result;
    status = SecTrustEvaluate(trust, &result);
    NSAssert(status == errSecSuccess, @"SecTrustEvaluate error: %ld", (long int)status);

    id mockedProtectionSpace = [OCMockObject partialMockForObject:protectionSpace];

    [[[mockedProtectionSpace stub] andDo:^(NSInvocation *invocation) {
        [invocation setReturnValue:(void *)&trust];
    }] serverTrust];

    AFMockURLProtocol *protocol = [[AFMockURLProtocol alloc] initWithRequest:request cachedResponse:nil client:nil];
    id mockedProtocol = [OCMockObject partialMockForObject:protocol];

    void(^useCredential)(NSInvocation *invocation) = ^(NSInvocation *invocation) {
        useCredentialInvoked = YES;
    };

    [[[mockedProtocol stub] andDo:useCredential] useCredential:OCMOCK_ANY forAuthenticationChallenge:OCMOCK_ANY];

    NSURLCredential *credential = [[NSURLCredential alloc] initWithTrust:trust];
    NSURLAuthenticationChallenge *authenticationChallenge = [[NSURLAuthenticationChallenge alloc] initWithProtectionSpace:protectionSpace proposedCredential:credential previousFailureCount:0 failureResponse:nil error:nil sender:mockedProtocol];
    [protocol.client URLProtocol:mockedProtocol didReceiveAuthenticationChallenge:authenticationChallenge];

    [operation connection:nil willSendRequestForAuthenticationChallenge:authenticationChallenge];

    CFRelease(trust);
    CFRelease(policy);
    CFRelease(certificates);
    CFRelease(certificate);

    expect(useCredentialInvoked).will.beTruthy();
}

- (void)testThatAFURLConnectionOperationTrustsPublicKeysOfDerivedCertificates {
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/path" relativeToURL:self.baseURL]];
    AFURLConnectionOperation *operation = [[AFURLConnectionOperation alloc] initWithRequest:request];
    operation.SSLPinningMode = AFSSLPinningModePublicKey;

    __block BOOL useCredentialInvoked = NO;

    NSURLProtectionSpace *protectionSpace = [[NSURLProtectionSpace alloc] initWithHost:request.URL.host port:request.URL.port.integerValue protocol:request.URL.scheme realm:nil authenticationMethod:NSURLAuthenticationMethodServerTrust];

    NSData *caCertificateData = [NSData dataWithContentsOfFile:[[NSBundle bundleForClass:[self class]] pathForResource:@"ca" ofType:@"cer"]];
    NSParameterAssert(caCertificateData);

    SecCertificateRef caCertificate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)caCertificateData);
    NSParameterAssert(caCertificate);

    NSData *hostCertificateData = [NSData dataWithContentsOfFile:[[NSBundle bundleForClass:[self class]] pathForResource:@"derived" ofType:@"cert"]];
    NSParameterAssert(hostCertificateData);

    SecCertificateRef hostCertificate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)caCertificateData);
    NSParameterAssert(hostCertificate);

    SecCertificateRef allowedCertificates[] = {caCertificate, hostCertificate};
    CFArrayRef certificates = CFArrayCreate(NULL, (const void **)allowedCertificates, 2, NULL);

    SecPolicyRef policy = SecPolicyCreateBasicX509();
    SecTrustRef trust = NULL;
    OSStatus status = SecTrustCreateWithCertificates(certificates, policy, &trust);
    NSAssert(status == errSecSuccess, @"SecTrustCreateWithCertificates error: %ld", (long int)status);

    SecTrustResultType result;
    status = SecTrustEvaluate(trust, &result);
    NSAssert(status == errSecSuccess, @"SecTrustEvaluate error: %ld", (long int)status);

    id mockedProtectionSpace = [OCMockObject partialMockForObject:protectionSpace];

    [[[mockedProtectionSpace stub] andDo:^(NSInvocation *invocation) {
        [invocation setReturnValue:(void *)&trust];
    }] serverTrust];

    AFMockURLProtocol *protocol = [[AFMockURLProtocol alloc] initWithRequest:request cachedResponse:nil client:nil];
    id mockedProtocol = [OCMockObject partialMockForObject:protocol];

    void(^useCredential)(NSInvocation *invocation) = ^(NSInvocation *invocation) {
        useCredentialInvoked = YES;
    };

    [[[mockedProtocol stub] andDo:useCredential] useCredential:OCMOCK_ANY forAuthenticationChallenge:OCMOCK_ANY];

    NSURLCredential *credential = [[NSURLCredential alloc] initWithTrust:trust];
    NSURLAuthenticationChallenge *authenticationChallenge = [[NSURLAuthenticationChallenge alloc] initWithProtectionSpace:protectionSpace proposedCredential:credential previousFailureCount:0 failureResponse:nil error:nil sender:mockedProtocol];
    [protocol.client URLProtocol:mockedProtocol didReceiveAuthenticationChallenge:authenticationChallenge];

    [operation connection:nil willSendRequestForAuthenticationChallenge:authenticationChallenge];

    CFRelease(trust);
    CFRelease(policy);
    CFRelease(certificates);
    CFRelease(caCertificate);
    CFRelease(hostCertificate);

    expect(useCredentialInvoked).will.beTruthy();
}

- (void)testThatAFURLConnectionOperationTrustsDerivedCertificates {
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/path" relativeToURL:self.baseURL]];
    AFURLConnectionOperation *operation = [[AFURLConnectionOperation alloc] initWithRequest:request];
    operation.SSLPinningMode = AFSSLPinningModeCertificate;

    __block BOOL useCredentialInvoked = NO;

    NSURLProtectionSpace *protectionSpace = [[NSURLProtectionSpace alloc] initWithHost:request.URL.host port:request.URL.port.integerValue protocol:request.URL.scheme realm:nil authenticationMethod:NSURLAuthenticationMethodServerTrust];

    NSData *caCertificateData = [NSData dataWithContentsOfFile:[[NSBundle bundleForClass:[self class]] pathForResource:@"ca" ofType:@"cer"]];
    NSParameterAssert(caCertificateData);

    SecCertificateRef caCertificate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)caCertificateData);
    NSParameterAssert(caCertificate);

    NSData *hostCertificateData = [NSData dataWithContentsOfFile:[[NSBundle bundleForClass:[self class]] pathForResource:@"derived" ofType:@"cert"]];
    NSParameterAssert(hostCertificateData);

    SecCertificateRef hostCertificate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)caCertificateData);
    NSParameterAssert(hostCertificate);

    SecCertificateRef allowedCertificates[] = {caCertificate, hostCertificate};
    CFArrayRef certificates = CFArrayCreate(NULL, (const void **)allowedCertificates, 2, NULL);

    SecPolicyRef policy = SecPolicyCreateBasicX509();
    SecTrustRef trust = NULL;
    OSStatus status = SecTrustCreateWithCertificates(certificates, policy, &trust);
    NSAssert(status == errSecSuccess, @"SecTrustCreateWithCertificates error: %ld", (long int)status);

    SecTrustResultType result;
    status = SecTrustEvaluate(trust, &result);
    NSAssert(status == errSecSuccess, @"SecTrustEvaluate error: %ld", (long int)status);

    id mockedProtectionSpace = [OCMockObject partialMockForObject:protectionSpace];

    [[[mockedProtectionSpace stub] andDo:^(NSInvocation *invocation) {
        [invocation setReturnValue:(void *)&trust];
    }] serverTrust];

    AFMockURLProtocol *protocol = [[AFMockURLProtocol alloc] initWithRequest:request cachedResponse:nil client:nil];
    id mockedProtocol = [OCMockObject partialMockForObject:protocol];

    void(^useCredential)(NSInvocation *invocation) = ^(NSInvocation *invocation) {
        useCredentialInvoked = YES;
    };

    [[[mockedProtocol stub] andDo:useCredential] useCredential:OCMOCK_ANY forAuthenticationChallenge:OCMOCK_ANY];

    NSURLCredential *credential = [[NSURLCredential alloc] initWithTrust:trust];
    NSURLAuthenticationChallenge *authenticationChallenge = [[NSURLAuthenticationChallenge alloc] initWithProtectionSpace:protectionSpace proposedCredential:credential previousFailureCount:0 failureResponse:nil error:nil sender:mockedProtocol];
    [protocol.client URLProtocol:mockedProtocol didReceiveAuthenticationChallenge:authenticationChallenge];

    [operation connection:nil willSendRequestForAuthenticationChallenge:authenticationChallenge];

    CFRelease(trust);
    CFRelease(policy);
    CFRelease(certificates);
    CFRelease(caCertificate);
    CFRelease(hostCertificate);

    expect(useCredentialInvoked).will.beTruthy();
}

@end


text:
<?php
namespace EmojiModuleTest\Service;

use EmojiModule\Service\Emoji as EmojiService;
use PHPUnit_Framework_TestCase;

class EmojiTest extends PHPUnit_Framework_TestCase
{
    /**
     * @var EmojiService
     */
    protected $emojiSerivce;

    public function setUp()
    {
        $this->emojiSerivce = new EmojiService();
        $this->emojiSerivce->setUnifiedToVariables(include __DIR__ . '/../../../config/emoji.maps.php');
    }

    public function testEncode()
    {
        $this->assertSame(
            "#1f601# Hello World",
            $this->emojiSerivce->encode("\xF0\x9F\x98\x81 Hello World"),
            "Test encode"
        );
    }

    public function testDecode()
    {
        $this->assertSame(
            "\xF0\x9F\x98\x81 Hello World",
            $this->emojiSerivce->decode("#1f601# Hello World"),
            "Test decode"
        );
    }

    public function testVariablesToHtml()
    {
        $this->assertSame(
            ' Hello World',
            $this->emojiSerivce->variablesToHtml("#1f601# Hello World"),
            "Test variables to html"
        );
    }

    public function testUnifiedToHtml()
    {
        $this->assertSame(
            ' Hello World',
            $this->emojiSerivce->unifiedToHtml("\xF0\x9F\x98\x81 Hello World"),
            "Test unified to html"
        );
    }
}


text:
using System;

namespace Microsoft.Media.Advertising
{
    /// <summary>
    /// Represents a creative source that comes from an ad document
    /// </summary>
    public interface IDocumentCreativeSource : ICreativeSource
    {
        /// <summary>
        /// Gets the associated creative
        /// </summary>
        ICreative Creative { get; }
    }
}


text:
<?php
require_once('dbconn.php');

$con=getConnection();
$sql="
select emp.emp_number emp_no,concat(emp.emp_firstname  ,' ' ,emp.emp_lastname) employee,
 sup.emp_number supervisor,job_title,concat('http://localhost/cruxa/getEmpPic.php?emp=',emp.emp_number) pic_url
from hr_mysql_live.hs_hr_employee emp
left join hr_mysql_live.hs_hr_emp_reportto on emp.emp_number = erep_sub_emp_number and erep_reporting_mode = 1
left join  hr_mysql_live.hs_hr_employee sup on sup.emp_number = erep_sup_emp_number
left join hr_mysql_live.ohrm_job_title tt on tt.id = emp.job_title_code
left join hr_mysql_live.hs_hr_emp_picture tp on emp.emp_number = tp.emp_number
where emp.emp_status not in (6,4)
";
//echo $sql;

$result = mysqli_query($con,$sql) or debug($sql.$where."   failed

".mysql_error());
$return_arr = array();
while($row = mysqli_fetch_array($result))
{
//echo $row['project_name'];
 $return_arr[]  = array (

              'id' => $row['emp_no'],
            'pid' => $row['supervisor'],
             'name' => $row['employee'],
             'title' => $row['job_title'],
             'img' => $row['pic_url']
        );
}
    echo json_encode($return_arr);

?>


text:
<?php
$CURRENT_DIR = __DIR__;
$PAGE_TITLE = "King Jones";
?>
<?php require_once(dirname(dirname(__DIR__)) . "/public_html/php/headutils.php"); ?>


text:
<?php

namespace Frontend\GeneralBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Debug\Debug;
use Symfony\Component\Form\Form;
use Symfony\Component\Form\FormBuilder;
use Symfony\Component\HttpFoundation\Request;

class BaseController extends Controller {

    public $currentUser;
    /**
     * @var Request
     */
    public $request;

    /**
     * @var FormBuilder
     */
    private $_form;
    private $_repository;
    private $_entity;
    private $_views;
    private $_actions;
    private $_columns;          // this is show columns in list view
    private $_columns_special;
    private $_object;

    /**
     * @param $configs['form', 'entity', 'views', 'urls']
     */
    public function init($configs) {
        $this->request = $this->get('request');

        $this->_form            = isset($configs['form']) ? $configs['form'] : null;
        $this->_entity          = isset($configs['entity']) ? $configs['entity'] : '';
        $this->_repository      = isset($configs['repository']) ? $configs['repository'] : '';
        $this->_object          = isset($configs['object']) ? $configs['object'] : '';

        $this->_columns         = isset($configs['columns']) ? $configs['columns'] : array();
        $this->_columns_special = isset($configs['columns_special']) ? $configs['columns_special'] : array();

        // set views for each action
        $this->_views           = isset($configs['views']) ? $configs['views'] : array('');
        $this->_views           = array_merge($this->_views, $this->_getDefaultViews());
    }

    /**
     * Function get current user
     * @return mixed
     */
    public function getCurrentUser() {
        if ($this->currentUser === null) {
            $this->currentUser = $this->get('security.context')->getToken()->getUser();
        }
        // get current user
        return $this->currentUser;
    }

    /**
     * Get primary key for table item
     *
     * @return mixed
     */
    private function _getPrimaryKey() {
        $meta           =  $this->getDoctrine()->getManager()->getClassMetadata(get_class($this->_entity));
        $identifier     = $meta->getSingleIdentifierFieldName();
        return $identifier;
    }

    public function listAction() {
        $items          = $this->getDoctrine()
                            ->getRepository($this->_repository)
                            ->findByCreatedBy($this->getCurrentUser()->getUserId());
        $identifier     = $this->_getPrimaryKey();

        $data                       = array();
        $data['items']              = $items;
        $data['columns']            = $this->_columns;
        $data['columns_special']    = $this->_columns_special;
        $data['id']                 = $identifier;
        $data['object']             = $this->_object;
        $data['title']              = $this->_getTitle();

        return $this->render($this->_views['list'], $data);
    }

    /**
     * action add new an object
     *
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
     * @throws \Exception
     */
    public function addAction() {
        $data   = array();
        $form   = $this->_form->getForm();
        if($this->request->getMethod() == 'POST') {
            $form->bind($this->request);
            if($form->isValid()) {
                try {
//                    \Doctrine\Common\Util\Debug::dump($this->_entity); die;
                    $this->setDefaultValues();
                    $em = $this->getDoctrine()->getManager();
                    $em->persist($this->_entity);
                    $em->flush();
                    return $this->redirect($this->_getUrlRedirect('add'));
                } catch(Exception $e) {
                    throw new \Exception("Can not update ". get_class($this->_entity));
                }
            }
        }

        $data['form']       = $this->_form->getForm()->createView();
        $data['title']      = $this->_getTitle();
        return $this->render($this->_views['add'], $data);
    }

    /**
     * action edit for an entity
     *
     * @param $id
     * @return \Symfony\Component\HttpFoundation\Response
     * @throws \Exception
     */
    public function editAction($id) {
        $data = array();

        $identifier = $identifier     = $this->_getPrimaryKey();

        $this->_entity = $this->getDoctrine()
            ->getRepository($this->_repository)
            ->findOneBy(array($identifier => $id));
        $this->_form->setData($this->_entity);

        $form = $this->_form->getForm();

        /**
         * check method post and save data to database
         */
        if($this->request->getMethod() == 'POST') {
            $form->bind($this->request);
            if($form->isValid()) {
                try {
                    $this->setDefaultValues(true);
                    $em = $this->getDoctrine()->getManager();
                    $em->persist($this->_entity);
                    $em->flush();
                    return $this->redirect($this->_getUrlRedirect('edit'));
                } catch(Exception $e) {
                    throw new \Exception("Can not update ". get_class($this->_entity));
                }
            }
        }

        $data['title']   = $this->_getTitle();
        $data['form']   = $this->_form->getForm()->createView();
        return $this->render($this->_views['edit'], $data);
    }

    public function deleteAction($id) {
        // get item
        $identifier = $this->_getPrimaryKey();
        $item = $this->getDoctrine()->getRepository($this->_repository)
            ->findOneBy([$identifier => $id]);
        // delete this item
        try {
            $em     = $this->getDoctrine()->getManager();
            $em->remove($item);
            $em->flush();
            return $this->redirect($this->_getUrlRedirect('delete'));
        } catch (Exception $e) {
            throw new \Exception("Can not delete ". get_class($this->_entity));
        }
    }

    private function _getTitle() {
        return $this->_object;
    }

    /**
     * Set default value in table
     *
     * @param bool $isUpdate
     */
    public function setDefaultValues($isUpdate = false) {
        if(!$isUpdate) {
            $this->_entity->setCreatedDate(new \DateTime());
            $this->_entity->setCreatedBy($this->getCurrentUser()->getUserId());
        }
        $this->_entity->setUpdatedDate(new \DateTime());
        $this->_entity->setUpdatedBy($this->getCurrentUser()->getUserId());
    }

    /**
     * function get url redirect
     *
     * @param $action
     * @return string
     */
    private function _getUrlRedirect($action) {
        $actions = array();
        $actions['edit']    = $this->generateUrl('frontend_user_'.$this->_object);
        $actions['add']     = $this->generateUrl('frontend_user_'.$this->_object);
        $actions['delete']  = $this->generateUrl('frontend_user_'.$this->_object);
        return $actions[$action];
    }

    /**
     * get default views
     *
     * @return array
     */
    private function _getDefaultViews() {
        $views = array();
        $views['add'] = 'FrontendGeneralBundle:Controller:add.html.twig';
        $views['edit'] = 'FrontendGeneralBundle:Controller:edit.html.twig';
        $views['list'] = 'FrontendGeneralBundle:Controller:list.html.twig';
        return $views;
    }
}


text:
#import <TargetConditionals.h>

#if TARGET_OS_IOS || TARGET_OS_MACCATALYST

#import "OIDExternalUserAgentCatalyst.h"

#import <SafariServices/SafariServices.h>
#import <AuthenticationServices/AuthenticationServices.h>

#import "OIDErrorUtilities.h"
#import "OIDExternalUserAgentSession.h"
#import "OIDExternalUserAgentRequest.h"

#if TARGET_OS_MACCATALYST

NS_ASSUME_NONNULL_BEGIN

@interface OIDExternalUserAgentCatalyst ()<ASWebAuthenticationPresentationContextProviding>
@end

@implementation OIDExternalUserAgentCatalyst {
  UIViewController *_presentingViewController;
  BOOL _prefersEphemeralSession;

  BOOL _externalUserAgentFlowInProgress;
  __weak id<OIDExternalUserAgentSession> _session;
  ASWebAuthenticationSession *_webAuthenticationVC;
}

- (nullable instancetype)initWithPresentingViewController:
    (UIViewController *)presentingViewController {
  self = [super init];
  if (self) {
    _presentingViewController = presentingViewController;
  }
  return self;
}

- (nullable instancetype)initWithPresentingViewController:
    (UIViewController *)presentingViewController
                                  prefersEphemeralSession:(BOOL)prefersEphemeralSession {
  self = [self initWithPresentingViewController:presentingViewController];
  if (self) {
    _prefersEphemeralSession = prefersEphemeralSession;
  }
  return self;
}

- (BOOL)presentExternalUserAgentRequest:(id<OIDExternalUserAgentRequest>)request
                                session:(id<OIDExternalUserAgentSession>)session {
  if (_externalUserAgentFlowInProgress) {
    // TODO: Handle errors as authorization is already in progress.
    return NO;
  }

  _externalUserAgentFlowInProgress = YES;
  _session = session;
  BOOL openedUserAgent = NO;
  NSURL *requestURL = [request externalUserAgentRequestURL];

  __weak OIDExternalUserAgentCatalyst *weakSelf = self;
  NSString *redirectScheme = request.redirectScheme;
  ASWebAuthenticationSession *authenticationVC =
      [[ASWebAuthenticationSession alloc] initWithURL:requestURL
                                    callbackURLScheme:redirectScheme
                                    completionHandler:^(NSURL * _Nullable callbackURL,
                                                        NSError * _Nullable error) {
    __strong OIDExternalUserAgentCatalyst *strongSelf = weakSelf;
    if (!strongSelf) {
        return;
    }
    strongSelf->_webAuthenticationVC = nil;
    if (callbackURL) {
      [strongSelf->_session resumeExternalUserAgentFlowWithURL:callbackURL];
    } else {
      NSError *safariError =
          [OIDErrorUtilities errorWithCode:OIDErrorCodeUserCanceledAuthorizationFlow
                           underlyingError:error
                               description:nil];
      [strongSelf->_session failExternalUserAgentFlowWithError:safariError];
    }
  }];

  authenticationVC.presentationContextProvider = self;
  authenticationVC.prefersEphemeralWebBrowserSession = _prefersEphemeralSession;
  _webAuthenticationVC = authenticationVC;
  openedUserAgent = [authenticationVC start];

  if (!openedUserAgent) {
    [self cleanUp];
    NSError *safariError = [OIDErrorUtilities errorWithCode:OIDErrorCodeSafariOpenError
                                            underlyingError:nil
                                                description:@"Unable to open ASWebAuthenticationSession view controller."];
    [session failExternalUserAgentFlowWithError:safariError];
  }
  return openedUserAgent;
}

- (void)dismissExternalUserAgentAnimated:(BOOL)animated completion:(void (^)(void))completion {
  if (!_externalUserAgentFlowInProgress) {
    // Ignore this call if there is no authorization flow in progress.
    if (completion) completion();
    return;
  }

  ASWebAuthenticationSession *webAuthenticationVC = _webAuthenticationVC;

  [self cleanUp];

  if (webAuthenticationVC) {
    // dismiss the ASWebAuthenticationSession
    [webAuthenticationVC cancel];
    if (completion) completion();
  } else {
    if (completion) completion();
  }
}

- (void)cleanUp {
  // The weak reference to |_session| is set to nil to avoid accidentally using
  // it while not in an authorization flow.
  _webAuthenticationVC = nil;
  _session = nil;
  _externalUserAgentFlowInProgress = NO;
}

#pragma mark - ASWebAuthenticationPresentationContextProviding

- (ASPresentationAnchor)presentationAnchorForWebAuthenticationSession:(ASWebAuthenticationSession *)session {
  return _presentingViewController.view.window;
}

@end

NS_ASSUME_NONNULL_END

#endif // TARGET_OS_MACCATALYST

#endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST


text:
module.exports = angular.module('trafficPortal.private.cacheGroups.edit', [])
    .config(function($stateProvider, $urlRouterProvider) {
        $stateProvider
            .state('trafficPortal.private.cacheGroups.edit', {
                url: '/{cacheGroupId:[0-9]{1,8}}',
                views: {
                    cacheGroupsContent: {
                        templateUrl: 'common/modules/form/cacheGroup/form.cacheGroup.tpl.html',
                        controller: 'FormEditCacheGroupController',
                        resolve: {
                            cacheGroup: function($stateParams, cacheGroupService) {
                                return cacheGroupService.getCacheGroup($stateParams.cacheGroupId);
                            },
                            types: function(typeService) {
                                return typeService.getTypes({ useInTable: 'cachegroup' });
                            },
                            cacheGroups: function(cacheGroupService) {
                                return cacheGroupService.getCacheGroups({ orderby: 'name' });
                            }
                        }
                    }
                }
            })
        ;
        $urlRouterProvider.otherwise('/');
    });


text:
package lang;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import lang.ast.ErrorMessage;
import lang.ast.LangParser;
import lang.ast.LangScanner;
import lang.ast.Program;
import beaver.Parser.Exception;
/**
 * Dumps the parsed Abstract Syntax Tree of a Calc program.
 */
public class Compiler {
	/**
	 * Entry point
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			if (args.length != 1) {
				System.err.println(
						"You must specify a source file on the command line!");
				printUsage();
				System.exit(1);
				return;
			}

			String filename = args[0];
			LangScanner scanner = new LangScanner(new FileReader(filename));
			LangParser parser = new LangParser();
			Program program = (Program) parser.parse(scanner);
			for (ErrorMessage e: program.errors()) {
				System.err.println(e);
			}
		} catch (FileNotFoundException e) {
			System.out.println("File not found!");
			System.exit(1);
		} catch (IOException e) {
			e.printStackTrace(System.err);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static void printUsage() {
		System.err.println("Usage: DumpTree FILE");
		System.err.println("  where FILE is the file to be parsed");
	}
}


text:
package processing.opengl;

import processing.core.PSurface;

/**
 * Having the possibility to define a custom surface..
 *
 * @author MKL.
 */
public class PGraphicsOpenGLFixed extends PGraphicsOpenGL {
    /** {@inheritDoc} */
    @Override
    public PSurface createSurface() {
        return new PSurfaceJOGLFixed(this);
    }
}


text:
package com.marshmallowswisdom.liber.services;

import java.util.List;

import org.springframework.util.AutoPopulatingList;

public class TypeForm {

	private int id;
	private String name;
	private List<FieldForm> fields;

	public TypeForm() {
		fields = new AutoPopulatingList<FieldForm>( FieldForm.class );
	}

	public int getId() {
		return id;
	}

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

	public String getName() {
		return name;
	}

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

	public List<FieldForm> getFields() {
		return fields;
	}

	public void setFields( final List<FieldForm> fields ) {
		this.fields = fields;
	}

}


text:
require "action_view/template"
require "redcarpet"
require "handlers/railtie"

ActionView::Template.register_template_handler :md,
  lambda {|template| "Redcarpet.new(#{template.source.inspect}).to_html" }

module Handlers
  module MERB
    def self.erb_handler
      @@erb_handler ||= ActionView::Template.registered_template_handler(:erb)
    end

    def self.call(template)
      compiled_source = erb_handler.call(template)
      if template.formats.include? :html
        "Redcarpet.new(begin;#{compiled_source};end).to_html"
      else
        compiled_source
      end
    end
  end
end

ActionView::Template.register_template_handler :merb, Handlers::MERB


text:
var $compile,
    $rootScope;

beforeEach(module('dndLists'));

beforeEach(inject(function(_$compile_, _$rootScope_){
  $compile = _$compile_;
  $rootScope = _$rootScope_;
}));

afterEach(function() {
  // Reset internal dndState in case dragend was not called.
  Dragend.on(compileAndLink('

'));
});

function compileAndLink(html) {
  var scope = $rootScope.$new();
  var element = $compile(html)(scope);
  scope.$digest();
  return element;
}


text:
'use strict';

var through = require('through2');
var extend = require('extend-shallow');
var PluginError = require('plugin-error');
var utils = require('../utils');

module.exports = function(options) {
  var locals = options.locals;
  var app = this;

  return through.obj(function (file, enc, cb) {
    if (utils.norender(app, file, locals)) {
      this.push(file);
      return cb();
    }

    file.content = file.contents.toString();
    var stream = this;

    locals = extend({}, file.data, locals);
    app.render(file, locals, function (err, res) {
      if (err) {
        stream.emit('error', new PluginError('render-plugin', err));
        return cb(err);
      }
      file.contents = new Buffer(res);
      stream.push(file);
      return cb();
    });
  });
};