text:
namespace ITweakMyBuild
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.Composition;
    using System.IO;
    using System.Linq;
    using System.Xml.Linq;

    using JetBrains.Annotations;

    using TomsToolbox.Core;

    [Export]
    [PartCreationPolicy(CreationPolicy.NonShared)]
    public class CustomTargetsFile
    {
        [NotNull]
        private static readonly string _filePath = Path.Combine(VSPackage.ConfigurationFolder, @"ITweakMyBuild.targets");
        [NotNull]
        private static readonly XNamespace _xmlns = @"http://schemas.microsoft.com/developer/msbuild/2003";
        [NotNull]
        // ReSharper disable once AssignNullToNotNullAttribute
        private static readonly XName _projectName = _xmlns + @"Project";
        [NotNull]
        // ReSharper disable once AssignNullToNotNullAttribute
        private static readonly XName _propertyGroupName = _xmlns + @"PropertyGroup";
        [NotNull]
        // ReSharper disable once AssignNullToNotNullAttribute
        private static readonly XName _itemGroupName = _xmlns + @"ItemGroup";
        [NotNull]
        // ReSharper disable once AssignNullToNotNullAttribute
        private static readonly XName _analyzerName = _xmlns + @"Analyzer";

        [NotNull]
        private readonly Tracer _tracer;
        [NotNull]
        private readonly XDocument _document;
        [NotNull]
        private readonly XElement _propertyGroup;
        [NotNull]
        private readonly XElement _itemGroup;

        private DateTime _fileTime;

        [ImportingConstructor]
        private CustomTargetsFile([NotNull] Tracer tracer)
        {
            _tracer = tracer;
            try
            {
                if (File.Exists(_filePath))
                {
                    try
                    {
                        _document = XDocument.Load(_filePath);
                        _fileTime = File.GetLastWriteTime(_filePath);
                        return;
                    }
                    catch (Exception ex)
                    {
                        _tracer.TraceError(ex.ToString());
                    }
                }

                _document = new XDocument(new XElement(_projectName, new XElement(_propertyGroupName)));
            }
            finally
            {
                var documentRoot = _document.Root;

                if (documentRoot == null)
                {
                    documentRoot = new XElement(_projectName);
                    _document.Add(documentRoot);
                }

                _propertyGroup = ForceElement(documentRoot, _propertyGroupName);

                _itemGroup = ForceElement(documentRoot, _itemGroupName);
            }
        }

        [NotNull]
        private static XElement ForceElement([NotNull] XContainer documentRoot, [NotNull] XName groupName)
        {
            var itemGroup = documentRoot.Descendants(groupName).FirstOrDefault();

            if (itemGroup != null)
                return itemGroup;

            itemGroup = new XElement(groupName);
            documentRoot.Add(itemGroup);

            return itemGroup;
        }

        public bool HasExternalChanges => !File.Exists(_filePath) || _fileTime != File.GetLastWriteTime(_filePath);

        [NotNull]
        public IReadOnlyDictionary<string, string> Properties
        {
            get
            {
                return _propertyGroup.Descendants()
                    // ReSharper disable once PossibleNullReferenceException
                    .Where(item => item.Parent == _propertyGroup)
                    .ToDictionary(item => item.Name.LocalName, item => item.Value);
            }
            set
            {
                try
                {
                    var itemsToRemove = _propertyGroup.Descendants()
                        // ReSharper disable once PossibleNullReferenceException
                        .Where(item => item.Parent == _propertyGroup)
                        .Where(item => !value.ContainsKey(item.Name.LocalName))
                        .ToArray();

                    // ReSharper disable once PossibleNullReferenceException
                    itemsToRemove.ForEach(item => item.Remove());

                    var existingItems = Properties;

                    var itemsToAdd = value.Where(item => !existingItems.ContainsKey(item.Key))
                        .ToArray();

                    // ReSharper disable AssignNullToNotNullAttribute
                    itemsToAdd.ForEach(item => _propertyGroup.Add(new XElement(_xmlns.GetName(item.Key), new XText(item.Value))));
                    // ReSharper enable AssignNullToNotNullAttribute

                    _document.Save(_filePath);
                    _fileTime = File.GetLastWriteTime(_filePath);
                }
                catch (Exception ex)
                {
                    _tracer.TraceError(ex.ToString());
                }
            }
        }

        [NotNull]
        public IReadOnlyCollection<string> Analyzers
        {
            get
            {
                return _itemGroup.Descendants(_analyzerName)
                    // ReSharper disable once PossibleNullReferenceException
                    .Where(item => item.Parent == _itemGroup)
                    .Select(item => item.Attribute("Include")?.Value)
                    .Where(item => item != null)
                    .ToArray();
            }
            set
            {
                try
                {
                    var itemsToRemove = _itemGroup.Descendants(_analyzerName)
                        // ReSharper disable once PossibleNullReferenceException
                        .Where(item => item.Parent == _itemGroup)
                        .Where(item => !value.Contains(item.Attribute("Include")?.Value, StringComparer.OrdinalIgnoreCase))
                        .ToArray();

                    // ReSharper disable once PossibleNullReferenceException
                    itemsToRemove.ForEach(item => item.Remove());

                    var existingItems = Analyzers;

                    var itemsToAdd = value.Where(item => !existingItems.Contains(item, StringComparer.OrdinalIgnoreCase))
                        .ToArray();

                    // ReSharper disable AssignNullToNotNullAttribute
                    itemsToAdd.ForEach(item => _itemGroup.Add(new XElement(_analyzerName, new XAttribute("Include", item))));
                    // ReSharper enable AssignNullToNotNullAttribute

                    _document.Save(_filePath);
                    _fileTime = File.GetLastWriteTime(_filePath);
                }
                catch (Exception ex)
                {
                    _tracer.TraceError(ex.ToString());
                }
            }
        }
    }
}


text:
package ch.bind.philib.util;

import org.testng.annotations.Test;

import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;

public class CowSetTest {

	@Test
	public void isEmpty() {
		CowSet<Integer> cs = new CowSet<>(Integer.class);
		assertTrue(cs.isEmpty());
		assertTrue(cs.add(1));
		assertFalse(cs.isEmpty());
		assertTrue(cs.remove(1)); // other integer object
		assertTrue(cs.isEmpty());
	}

	@Test
	public void emptyView() {
		CowSet<Integer> cs = new CowSet<>(Integer.class);
		Integer[] empty1 = cs.getView();
		cs.add(1);
		assertEquals(cs.getView().length, 1);
		cs.remove(1);
		Integer[] empty2 = cs.getView();
		assertTrue(empty1 == empty2);
	}

	@Test
	public void noNullAdd() {
		CowSet<Integer> cs = new CowSet<>(Integer.class);
		assertFalse(cs.add(null));
	}

	@Test
	public void noNullRemove() {
		CowSet<Integer> cs = new CowSet<>(Integer.class);
		assertFalse(cs.remove(null));
	}

	@Test
	public void noViewUpdateOnFalseRemove() {
		CowSet<Integer> cs = new CowSet<>(Integer.class);
		cs.add(55);
		Integer[] v = cs.getView();
		assertEquals(v.length, 1);
		assertEquals(v[0], Integer.valueOf(55));
		assertFalse(cs.remove(1));
		assertTrue(v == cs.getView());
	}

	@Test
	public void noDuplicates() {
		CowSet<Integer> cs = new CowSet<>(Integer.class);
		Integer a = 55;
		Integer b = 55; // different reference but equals
		assertTrue(cs.add(a));
		assertFalse(cs.add(a));
		assertFalse(cs.add(b));
		assertEquals(cs.getView().length, 1);
	}

	@Test
	public void size() {
		CowSet<Integer> cs = new CowSet<>(Integer.class);
		assertEquals(cs.size(), 0);
		cs.add(1);
		assertEquals(cs.size(), 1);
	}
}

redpajama_set_name: RedPajamaGithub


text:
namespace media_router {

namespace {

std::unique_ptr<KeyedService> CreateMockMediaRouter(
    content::BrowserContext* context) {
  return base::WrapUnique(new MockMediaRouter);
}

}  // namespace

class MediaRouterFactoryTest : public testing::Test {
 protected:
  MediaRouterFactoryTest() {}
  ~MediaRouterFactoryTest() override {}

  Profile* profile() { return &profile_; }

 private:
  content::TestBrowserThreadBundle thread_bundle_;
  TestingProfile profile_;
};

TEST_F(MediaRouterFactoryTest, CreateForRegularProfile) {
  ASSERT_TRUE(MediaRouterFactory::GetApiForBrowserContext(profile()));
}

TEST_F(MediaRouterFactoryTest, CreateForOffTheRecordProfile) {
  Profile* otr_profile = profile()->GetOffTheRecordProfile();
  ASSERT_TRUE(otr_profile);

  // Makes sure a MediaRouter can be created from an OTR Profile.
  MediaRouter* router =
      MediaRouterFactory::GetApiForBrowserContext(otr_profile);
  ASSERT_TRUE(router);

  // A Profile and its OTR Profile share the same MediaRouter instance.
  ASSERT_EQ(router, MediaRouterFactory::GetApiForBrowserContext(profile()));
}

TEST_F(MediaRouterFactoryTest, OffTheRecordBrowserContextShutdown) {
  MediaRouterFactory::GetMediaRouterFactoryForTest()->SetTestingFactory(
      profile(), &CreateMockMediaRouter);

  // Creates an off the record profile.
  profile()->GetOffTheRecordProfile();
  MockMediaRouter* router = static_cast<MockMediaRouter*>(
      MediaRouterFactory::GetApiForBrowserContext(profile()));
  ASSERT_TRUE(router);
  EXPECT_CALL(*router, OnOffTheRecordProfileShutdown());
  profile()->DestroyOffTheRecordProfile();
}

}  // namespace media_router


text:
import axios, { parseCursor } from '@/base/api/axios'

export default {
  async get (id) {
    return (await axios.get(`/api/history/${id}/`)).data
  },

  async list (filter) {
    const response = (await axios.get('/api/history/', { params: filter })).data
    return {
      ...response,
      next: parseCursor(response.next),
      results: convert(response.results),
    }
  },

  async listMore (cursor) {
    const response = (await axios.get(cursor)).data
    return {
      ...response,
      next: parseCursor(response.next),
      prev: parseCursor(response.prev),
      results: convert(response.results),
    }
  },
}

export function convert (val) {
  if (Array.isArray(val)) {
    return val.map(convert)
  }
  else {
    const date = new Date(val.date)
    let payload = val.payload
    if (payload) {
      // convert some known payload dates
      const dates = {};
      ['date', 'startDate', 'invitedAt'].forEach(k => {
        if (payload[k]) {
          if (Array.isArray(payload[k])) {
            dates[k] = payload[k].map(d => new Date(d))
          }
          else {
            dates[k] = new Date(payload[k])
          }
        }
      })
      payload = {
        ...payload,
        ...dates,
      }
    }
    return { ...val, date, payload }
  }
}


text:
<!DOCTYPE html>

    <title>Stateful Workload Tutorial</title>

Latest Info

Latest Date:

Latest Writer:

Total entries:

Number of Unique Writers:

Write History:


text:
import tornado.ioloop
import tornado.web
import tornado.options
import sys
import os
import yaml
from concurrent import futures
import controller.base

tornado.options.define("port", default=5555, help="Run server on a specific port", type=int)
tornado.options.parse_command_line()

setting = {
    "cookie_secret": "17a18595b03aef1def118e8ed4e5b00d",
    "config_filename": "config.yaml",
    "compress_response": True,
    "default_handler_class": controller.base.NotFoundHandler,
    "xsrf_cookies": False,
    "autoreload": True,
    "thread_pool": futures.ThreadPoolExecutor(4)
}

if os.environ.get("AVDIR_ENV") == 'dev':
    setting["serve_traceback"] = True
    config_env = "dev"
else:
    config_env = "prod"

print(config_env)

config = {}
try:
    with open(os.path.join(os.path.abspath(os.path.dirname(__file__)), setting["config_filename"]), "r", encoding="utf-8") as fin:
        config = yaml.load(fin)
    theme = config["site"]["theme"]
    setting["site"] = config["site"]
    setting["qiniu"] = config["qiniu"]
    setting["static_path"] = os.path.join(os.path.abspath(os.path.dirname(__file__)), "theme/{}/static".format(theme))
    setting["static_admin_path"] = os.path.join(os.path.abspath(os.path.dirname(__file__)), "theme/admin/static")
    setting["template_path"] = os.path.join(os.path.abspath(os.path.dirname(__file__)),
                                            "theme/{}/templates".format(theme))
except Exception as e:
    print(e)
    print("cannot found config.yaml file")
    sys.exit(0)

application = tornado.web.Application([
    (r"^/", "controller.main.MainHandler"),

    (r"^/ajax/([a-z]+)", "controller.ajax.AjaxHandler"),

    (r"^/archives", "controller.archive.ArchiveLineHandler"),
    (r"^/archive/(.*)", "controller.archive.ArchiveHandler"),

    (r"^/page/([\d]+)?", "controller.main.PageHandler"),
    (r"^/tag/(.*)", "controller.main.TagHandler"),
    (r"^/feed", "controller.main.FeedHandler"),

    (r"^/admin", "controller.admin.IndexHandler"),
    (r"^/admin/login", "controller.admin.LoginHandler"),
    (r"^/admin/logout", "controller.admin.LogoutHandler"),
    (r"^/admin/upload", "controller.admin.UploadHandler"),
    (r"^/admin/archive/add", "controller.admin.ArchiveAddHandler"),
    (r"^/admin/archive/edit/([0-9]+)", "controller.admin.ArchiveEditHandler"),
    (r"^/admin/archive/list", "controller.admin.ArchiveListHandler"),
    (r"^/admin/user/add", "controller.admin.UserAddHandler"),
    (r"^/admin/user/edit/([0-9]+)", "controller.admin.UserEditHandler"),
    (r"^/admin/user/list", "controller.admin.UserListHandler"),

    (r"/admin/static/(.*)", tornado.web.StaticFileHandler, dict(path=setting["static_admin_path"])),
    (r"^/diracsea", "controller.base.NotFoundHandler"),
    (r"^/(.*)", "controller.archive.PageHandler"),
], **setting)

if __name__ == "__main__":
    try:
        application.listen(tornado.options.options.port)
        tornado.ioloop.IOLoop.instance().start()
    except:
        import traceback
        print(traceback.print_exc())
    finally:
        sys.exit(0)


text:
import ffn                       # Financial data manipulation
import bt                        # Backtesting
import matplotlib.pyplot as plt  # Plotting

# Parameters
tickers = ['GS', 'JPM']
startDate = '2000-01-01'
endDate = '2015-01-01'

# Retrieve time series
data = ffn.get(tickers,
               start=startDate,
               end=endDate,
               common_dates=False,
               forward_fill=True)

# Compute logreturns
returns = data.to_log_returns().dropna()

# Compute performance
perf = data.calc_stats()
perf.plot()
plt.show()
print perf.display()

# Create the strategy
s = bt.Strategy('s1', [bt.algos.RunMonthly(),
                       bt.algos.SelectAll(),
                       bt.algos.WeighEqually(),
                       bt.algos.Rebalance()])

test = bt.Backtest(s, data)
res = bt.run(test)

res.plot(lw=1.5)
plt.show()
print res.display()


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Razor.Text;

namespace Foosball.Models.FoosballModels
{
    public class Game
    {
        public int Id { get; set; }
        public int LocationId { get; set; }
        public DateTime Date { get; set; }
        public bool IsConfirmed() { return PlayerGames.All(x => x.IsConfirmed); }

        public virtual Location Location { get; set; }
        public virtual ICollection<PlayerGame> PlayerGames { get; set; }

        public Game()
        {
            PlayerGames = PlayerGames ?? new List<PlayerGame>() { };
        }
    }
}


text:
'use strict';

import type {SchemaType} from '../../CodegenSchema.js';

// $FlowFixMe[untyped-import] there's no flowtype flow-parser
const flowParser = require('flow-parser');
const fs = require('fs');
const {
  buildSchemaFromConfigType,
  getConfigType,
  isModuleRegistryCall,
} = require('../utils');
const {buildComponentSchema} = require('./components');
const {wrapComponentSchema} = require('./components/schema');
const {buildModuleSchema} = require('./modules');

function Visitor(infoMap: {isComponent: boolean, isModule: boolean}) {
  return {
    CallExpression(node: $FlowFixMe) {
      if (
        node.callee.type === 'Identifier' &&
        node.callee.name === 'codegenNativeComponent'
      ) {
        infoMap.isComponent = true;
      }

      if (isModuleRegistryCall(node)) {
        infoMap.isModule = true;
      }
    },
    InterfaceExtends(node: $FlowFixMe) {
      if (node.id.name === 'TurboModule') {
        infoMap.isModule = true;
      }
    },
  };
}

function buildSchema(contents: string, filename: ?string): SchemaType {
  // Early return for non-Spec JavaScript files
  if (
    !contents.includes('codegenNativeComponent') &&
    !contents.includes('TurboModule')
  ) {
    return {modules: {}};
  }

  const ast = flowParser.parse(contents, {enums: true});
  const configType = getConfigType(ast, Visitor);

  return buildSchemaFromConfigType(
    configType,
    filename,
    ast,
    wrapComponentSchema,
    buildComponentSchema,
    buildModuleSchema,
  );
}

function parseModuleFixture(filename: string): SchemaType {
  const contents = fs.readFileSync(filename, 'utf8');

  return buildSchema(contents, 'path/NativeSampleTurboModule.js');
}

function parseString(contents: string, filename: ?string): SchemaType {
  return buildSchema(contents, filename);
}

module.exports = {
  buildSchema,
  parseModuleFixture,
  parseString,
};


text:
package geo

// A Pointer is the interface for something that has a point.
type Pointer interface {
	// Point should return the "center" or other canonical point
	// for the object. The caller is expected to Clone
	// the point if changes need to be make.
	Point() *Point
}

// TODO: add some functionality around sets of pointers,
// ie. `type PointerSlice []Pointer`


text:
<?php
/**
 * ALIPAY API: alipay.stock.portfolio.single.add request
 *
 * @author auto create
 * @since 1.0, 2015-01-04 10:03:56
 */
class AlipayStockPortfolioSingleAddRequest
{
	/**
	 * 股票代码,格式:代码.市场
	 **/
	private $symbol;

	/**
	 * 支付宝的用户号
	 **/
	private $userId;

	private $apiParas = array();
	private $terminalType;
	private $terminalInfo;
	private $prodCode;
	private $apiVersion="1.0";
	private $notifyUrl;

	public function setSymbol($symbol)
	{
		$this->symbol = $symbol;
		$this->apiParas["symbol"] = $symbol;
	}

	public function getSymbol()
	{
		return $this->symbol;
	}

	public function setUserId($userId)
	{
		$this->userId = $userId;
		$this->apiParas["user_id"] = $userId;
	}

	public function getUserId()
	{
		return $this->userId;
	}

	public function getApiMethodName()
	{
		return "alipay.stock.portfolio.single.add";
	}

	public function setNotifyUrl($notifyUrl)
	{
		$this->notifyUrl=$notifyUrl;
	}

	public function getNotifyUrl()
	{
		return $this->notifyUrl;
	}

	public function getApiParas()
	{
		return $this->apiParas;
	}

	public function getTerminalType()
	{
		return $this->terminalType;
	}

	public function setTerminalType($terminalType)
	{
		$this->terminalType = $terminalType;
	}

	public function getTerminalInfo()
	{
		return $this->terminalInfo;
	}

	public function setTerminalInfo($terminalInfo)
	{
		$this->terminalInfo = $terminalInfo;
	}

	public function getProdCode()
	{
		return $this->prodCode;
	}

	public function setProdCode($prodCode)
	{
		$this->prodCode = $prodCode;
	}

	public function setApiVersion($apiVersion)
	{
		$this->apiVersion=$apiVersion;
	}

	public function getApiVersion()
	{
		return $this->apiVersion;
	}

}


text:
class MeasureTypeValidator < TradeTariffBackend::Validator
  validation :MT1, 'The  measure type code must be unique.', on: [:create, :update] do
    validates :uniqueness, of: [:measure_type_id]
  end

  validation :MT2, 'The start date must be less than or equal to the end date.' do
    validates :validity_dates
  end

  validation :MT4, 'The referenced measure type series must exist.', on: [:create, :update] do
    validates :presence, of: :measure_type_series
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate android:fromYDelta="0" android:toYDelta="-100%" android:duration="125" />
</set><!-- From: file:/F:/practise/PopupWindowHelper/popuphelper/src/main/res/anim/hide_to_top.xml -->


text:
package org.seeknresolve.service.permissions;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.seeknresolve.domain.dto.PermissionDTO;
import org.seeknresolve.domain.entity.Permission;
import org.seeknresolve.domain.repository.PermissionRepository;
import org.seeknresolve.domain.repository.RoleRepository;
import org.seeknresolve.service.common.DtosFactory;
import org.seeknresolve.service.permission.PermissionService;

import javax.persistence.EntityNotFoundException;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.*;

@RunWith(MockitoJUnitRunner.class)
public class PermissionServiceTest {

    @Mock
    private PermissionRepository permissionRepository;

    @Mock
    private RoleRepository roleRepository;

    private PermissionService permissionService;

    @Before
    public void setUp() {
        permissionService = new PermissionService(permissionRepository, roleRepository);
    }

    @Test
    public void shouldCreatePermissionFromDTO() {
        when(permissionRepository.save(any(Permission.class))).thenReturn(new Permission("add_all"));
        PermissionDTO arg = DtosFactory.createPermissionDTO(new Permission("add_all"));

        PermissionDTO saved = permissionService.createAndSaveNewPermission(arg);

        assertThat(saved).isNotNull();
        assertThat(saved.getPermissionName()).isEqualTo(arg.getPermissionName());
        verify(permissionRepository, times(1)).save(any(Permission.class));
    }

    @Test(expected = EntityNotFoundException.class)
    public void deleteFailWhenNoPermission() {
        when(permissionRepository.exists(anyString())).thenReturn(false);

        permissionService.delete("perm_name");
    }

    @Test
    public void delete() {
        when(permissionRepository.exists(anyString())).thenReturn(true);

        permissionService.delete("perm_name");

        verify(permissionRepository, times(1)).delete("perm_name");
    }
}


text:
#import "BBAUserDetails.h"

@implementation BBAUserDetails
- (NSString *) description{
    return [NSString stringWithFormat:@"%@, \rfirst name:%@, \rlast name: %@, \remail:%@, \rpassword: %@, \ridentifier: %@, \raccepts T&C: %d, \rallowsMarketing: %d, \rrefresh token: %@", [super description],
            self.firstName, self.lastName, self.email, self.password, self.identifier,
            self.acceptsTermsAndConditions, self.allowMarketing, self.refreshToken];

}
@end


text:
'use strict';

var utils = require('./../utils');
var settle = require('./../core/settle');
var buildFullPath = require('../core/buildFullPath');
var buildURL = require('./../helpers/buildURL');
var http = require('http');
var https = require('https');
var httpFollow = require('follow-redirects').http;
var httpsFollow = require('follow-redirects').https;
var url = require('url');
var zlib = require('zlib');
var pkg = require('./../../package.json');
var createError = require('../core/createError');
var enhanceError = require('../core/enhanceError');

var isHttps = /https:?/;

/**
 *
 * @param {http.ClientRequestArgs} options
 * @param {AxiosProxyConfig} proxy
 * @param {string} location
 */
function setProxy(options, proxy, location) {
  options.hostname = proxy.host;
  options.host = proxy.host;
  options.port = proxy.port;
  options.path = location;

  // Basic proxy authorization
  if (proxy.auth) {
    var base64 = Buffer.from(proxy.auth.username + ':' + proxy.auth.password, 'utf8').toString('base64');
    options.headers['Proxy-Authorization'] = 'Basic ' + base64;
  }

  // If a proxy is used, any redirects must also pass through the proxy
  options.beforeRedirect = function beforeRedirect(redirection) {
    redirection.headers.host = redirection.host;
    setProxy(redirection, proxy, redirection.href);
  };
}

/*eslint consistent-return:0*/
module.exports = function httpAdapter(config) {
  return new Promise(function dispatchHttpRequest(resolvePromise, rejectPromise) {
    var resolve = function resolve(value) {
      resolvePromise(value);
    };
    var reject = function reject(value) {
      rejectPromise(value);
    };
    var data = config.data;
    var headers = config.headers;

    // Set User-Agent (required by some servers)
    // Only set header if it hasn't been set in config
    // See https://github.com/axios/axios/issues/69
    if (!headers['User-Agent'] && !headers['user-agent']) {
      headers['User-Agent'] = 'axios/' + pkg.version;
    }

    if (data && !utils.isStream(data)) {
      if (Buffer.isBuffer(data)) {
        // Nothing to do...
      } else if (utils.isArrayBuffer(data)) {
        data = Buffer.from(new Uint8Array(data));
      } else if (utils.isString(data)) {
        data = Buffer.from(data, 'utf-8');
      } else {
        return reject(createError(
          'Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream',
          config
        ));
      }

      // Add Content-Length header if data exists
      headers['Content-Length'] = data.length;
    }

    // HTTP basic authentication
    var auth = undefined;
    if (config.auth) {
      var username = config.auth.username || '';
      var password = config.auth.password || '';
      auth = username + ':' + password;
    }

    // Parse url
    var fullPath = buildFullPath(config.baseURL, config.url);
    var parsed = url.parse(fullPath);
    var protocol = parsed.protocol || 'http:';

    if (!auth && parsed.auth) {
      var urlAuth = parsed.auth.split(':');
      var urlUsername = urlAuth[0] || '';
      var urlPassword = urlAuth[1] || '';
      auth = urlUsername + ':' + urlPassword;
    }

    if (auth) {
      delete headers.Authorization;
    }

    var isHttpsRequest = isHttps.test(protocol);
    var agent = isHttpsRequest ? config.httpsAgent : config.httpAgent;

    var options = {
      path: buildURL(parsed.path, config.params, config.paramsSerializer).replace(/^\?/, ''),
      method: config.method.toUpperCase(),
      headers: headers,
      agent: agent,
      agents: { http: config.httpAgent, https: config.httpsAgent },
      auth: auth
    };

    if (config.socketPath) {
      options.socketPath = config.socketPath;
    } else {
      options.hostname = parsed.hostname;
      options.port = parsed.port;
    }

    var proxy = config.proxy;
    if (!proxy && proxy !== false) {
      var proxyEnv = protocol.slice(0, -1) + '_proxy';
      var proxyUrl = process.env[proxyEnv] || process.env[proxyEnv.toUpperCase()];
      if (proxyUrl) {
        var parsedProxyUrl = url.parse(proxyUrl);
        var noProxyEnv = process.env.no_proxy || process.env.NO_PROXY;
        var shouldProxy = true;

        if (noProxyEnv) {
          var noProxy = noProxyEnv.split(',').map(function trim(s) {
            return s.trim();
          });

          shouldProxy = !noProxy.some(function proxyMatch(proxyElement) {
            if (!proxyElement) {
              return false;
            }
            if (proxyElement === '*') {
              return true;
            }
            if (proxyElement[0] === '.' &&
                parsed.hostname.substr(parsed.hostname.length - proxyElement.length) === proxyElement) {
              return true;
            }

            return parsed.hostname === proxyElement;
          });
        }

        if (shouldProxy) {
          proxy = {
            host: parsedProxyUrl.hostname,
            port: parsedProxyUrl.port,
            protocol: parsedProxyUrl.protocol
          };

          if (parsedProxyUrl.auth) {
            var proxyUrlAuth = parsedProxyUrl.auth.split(':');
            proxy.auth = {
              username: proxyUrlAuth[0],
              password: proxyUrlAuth[1]
            };
          }
        }
      }
    }

    if (proxy) {
      options.headers.host = parsed.hostname + (parsed.port ? ':' + parsed.port : '');
      setProxy(options, proxy, protocol + '//' + parsed.hostname + (parsed.port ? ':' + parsed.port : '') + options.path);
    }

    var transport;
    var isHttpsProxy = isHttpsRequest && (proxy ? isHttps.test(proxy.protocol) : true);
    if (config.transport) {
      transport = config.transport;
    } else if (config.maxRedirects === 0) {
      transport = isHttpsProxy ? https : http;
    } else {
      if (config.maxRedirects) {
        options.maxRedirects = config.maxRedirects;
      }
      transport = isHttpsProxy ? httpsFollow : httpFollow;
    }

    if (config.maxBodyLength > -1) {
      options.maxBodyLength = config.maxBodyLength;
    }

    // Create the request
    var req = transport.request(options, function handleResponse(res) {
      if (req.aborted) return;

      // uncompress the response body transparently if required
      var stream = res;

      // return the last request in case of redirects
      var lastRequest = res.req || req;

      // if no content, is HEAD request or decompress disabled we should not decompress
      if (res.statusCode !== 204 && lastRequest.method !== 'HEAD' && config.decompress !== false) {
        switch (res.headers['content-encoding']) {
        /*eslint default-case:0*/
        case 'gzip':
        case 'compress':
        case 'deflate':
        // add the unzipper to the body stream processing pipeline
          stream = stream.pipe(zlib.createUnzip());

          // remove the content-encoding in order to not confuse downstream operations
          delete res.headers['content-encoding'];
          break;
        }
      }

      var response = {
        status: res.statusCode,
        statusText: res.statusMessage,
        headers: res.headers,
        config: config,
        request: lastRequest
      };

      if (config.responseType === 'stream') {
        response.data = stream;
        settle(resolve, reject, response);
      } else {
        var responseBuffer = [];
        stream.on('data', function handleStreamData(chunk) {
          responseBuffer.push(chunk);

          // make sure the content length is not over the maxContentLength if specified
          if (config.maxContentLength > -1 && Buffer.concat(responseBuffer).length > config.maxContentLength) {
            stream.destroy();
            reject(createError('maxContentLength size of ' + config.maxContentLength + ' exceeded',
              config, null, lastRequest));
          }
        });

        stream.on('error', function handleStreamError(err) {
          if (req.aborted) return;
          reject(enhanceError(err, config, null, lastRequest));
        });

        stream.on('end', function handleStreamEnd() {
          var responseData = Buffer.concat(responseBuffer);
          if (config.responseType !== 'arraybuffer') {
            responseData = responseData.toString(config.responseEncoding);
            if (!config.responseEncoding || config.responseEncoding === 'utf8') {
              responseData = utils.stripBOM(responseData);
            }
          }

          response.data = responseData;
          settle(resolve, reject, response);
        });
      }
    });

    // Handle errors
    req.on('error', function handleRequestError(err) {
      if (req.aborted && err.code !== 'ERR_FR_TOO_MANY_REDIRECTS') return;
      reject(enhanceError(err, config, null, req));
    });

    // Handle request timeout
    if (config.timeout) {
      // Sometime, the response will be very slow, and does not respond, the connect event will be block by event loop system.
      // And timer callback will be fired, and abort() will be invoked before connection, then get "socket hang up" and code ECONNRESET.
      // At this time, if we have a large number of request, nodejs will hang up some socket on background. and the number will up and up.
      // And then these socket which be hang up will devoring CPU little by little.
      // ClientRequest.setTimeout will be fired on the specify milliseconds, and can make sure that abort() will be fired after connect.
      req.setTimeout(config.timeout, function handleRequestTimeout() {
        req.abort();
        reject(createError('timeout of ' + config.timeout + 'ms exceeded', config, 'ECONNABORTED', req));
      });
    }

    if (config.cancelToken) {
      // Handle cancellation
      config.cancelToken.promise.then(function onCanceled(cancel) {
        if (req.aborted) return;

        req.abort();
        reject(cancel);
      });
    }

    // Send the request
    if (utils.isStream(data)) {
      data.on('error', function handleStreamError(err) {
        reject(enhanceError(err, config, null, req));
      }).pipe(req);
    } else {
      req.end(data);
    }
  });
};


text:
/*
mirror tree
*/
public class TreeNode{
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) {val = x;}
}

public TreeNode MirrorTree(TreeNode root){
    //return a mirror tree of the input;
    if(root==null)return root;
    if(root.left==null && root.right==null) return root;
    TreeNode left = MirrorTree(root.left);
    TreeNode right = MirrorTree(root.right);
    root.left=right;
    root.right=left;
    return root;
}


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

    angular
        .module('azure')
        .controller('BizTalk', BizTalk);

    BizTalk.$inject = ['$scope'];

    function BizTalk($scope) {

        activate();

        function activate() { }
    }
})();


text:
<?php

namespace Application\Migrations;

use Doctrine\DBAL\Migrations\AbstractMigration;
use Doctrine\DBAL\Schema\Schema;

/**
 * Auto-generated Migration: Please modify to your needs!
 */
class Version20170829161036 extends AbstractMigration
{
    /**
     * @param Schema $schema
     */
    public function up(Schema $schema)
    {
        // this up() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('CREATE TABLE history (id INT AUTO_INCREMENT NOT NULL, user_id INT DEFAULT NULL, qualification_id INT DEFAULT NULL, total_points INT NOT NULL, points INT NOT NULL, created_at DATETIME NOT NULL, INDEX IDX_27BA704BA76ED395 (user_id), INDEX IDX_27BA704B1A75EE38 (qualification_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB');
        $this->addSql('ALTER TABLE history ADD CONSTRAINT FK_27BA704BA76ED395 FOREIGN KEY (user_id) REFERENCES user (id)');
        $this->addSql('ALTER TABLE history ADD CONSTRAINT FK_27BA704B1A75EE38 FOREIGN KEY (qualification_id) REFERENCES qualification (id)');
        $this->addSql('ALTER TABLE question CHANGE id id INT AUTO_INCREMENT NOT NULL, CHANGE query query LONGTEXT NOT NULL, CHANGE answerA answerA LONGTEXT NOT NULL, CHANGE answerB answerB LONGTEXT NOT NULL, CHANGE answerC answerC LONGTEXT NOT NULL, CHANGE answerD answerD LONGTEXT NOT NULL');
    }

    /**
     * @param Schema $schema
     */
    public function down(Schema $schema)
    {
        // this down() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('DROP TABLE history');
        $this->addSql('ALTER TABLE question CHANGE id id INT AUTO_INCREMENT NOT NULL, CHANGE query query LONGTEXT NOT NULL COLLATE utf8_unicode_ci, CHANGE answerA answerA LONGTEXT NOT NULL COLLATE utf8_unicode_ci, CHANGE answerB answerB LONGTEXT NOT NULL COLLATE utf8_unicode_ci, CHANGE answerC answerC LONGTEXT NOT NULL COLLATE utf8_unicode_ci, CHANGE answerD answerD LONGTEXT NOT NULL COLLATE utf8_unicode_ci');
    }
}


text:
'use strict';

Connector.useMediaSessionApi();

Connector.playerSelector = 'body';

Connector.getArtist = () => {
	const artists = $('.now_playing .artist a').toArray();
	return Util.joinArtists(artists);
};

Connector.trackSelector = '.now_playing .title';

Connector.albumSelector = '.now_playing .album';

Connector.trackArtSelector = '.now_playing .art_container';

Connector.isPlaying = () => $('#r4_audio_player').hasClass('playing');


text:
#include "supervisor/board.h"
#include "mpconfigboard.h"

#include "stm32l4xx.h"
#include "stm32l4r5xx.h"

#include "shared-bindings/microcontroller/Pin.h"
#include "shared-bindings/digitalio/DigitalInOut.h"
#include "shared-bindings/digitalio/Direction.h"
#include "shared-bindings/digitalio/DriveMode.h"
#include "board.h"

digitalio_digitalinout_obj_t power_pin = { .base.type = &digitalio_digitalinout_type };
digitalio_digitalinout_obj_t discharge_pin = { .base.type = &digitalio_digitalinout_type };

void initialize_discharge_pin(void) {

    /* Initialize the 3V3 discharge to be OFF and the output power to be ON */
    __HAL_RCC_GPIOE_CLK_ENABLE();
    __HAL_RCC_GPIOC_CLK_ENABLE();

    common_hal_digitalio_digitalinout_construct(&power_pin, &pin_PE04);
    common_hal_digitalio_digitalinout_construct(&discharge_pin, &pin_PE06);
    common_hal_digitalio_digitalinout_never_reset(&power_pin);
    common_hal_digitalio_digitalinout_never_reset(&discharge_pin);

    GPIO_InitTypeDef GPIO_InitStruct;
    /* Set the DISCHARGE pin and the USB_DETECT pin to FLOAT */
    GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
    GPIO_InitStruct.Pull = GPIO_NOPULL;
    GPIO_InitStruct.Pin = GPIO_PIN_6;
    HAL_GPIO_Init(GPIOE, &GPIO_InitStruct); /* PE6 DISCHRG */
    HAL_GPIO_Init(GPIOC, &GPIO_InitStruct); /* PC6 is USB_DETECT */

    /* Turn on the 3V3 regulator */
    GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
    GPIO_InitStruct.Speed = GPIO_SPEED_LOW;
    GPIO_InitStruct.Pin = GPIO_PIN_4;
    HAL_GPIO_Init(GPIOE, &GPIO_InitStruct);
    HAL_GPIO_WritePin(GPIOE, GPIO_PIN_4, GPIO_PIN_SET);

}

void board_init(void) {
    // enable the debugger while sleeping. Todo move somewhere more central (kind of generally useful in a debug build)
    SET_BIT(DBGMCU->CR, DBGMCU_CR_DBG_SLEEP);

    //  Set tick interrupt priority, default HAL value is intentionally invalid
    //  Without this, USB does not function.
    HAL_InitTick((1UL << __NVIC_PRIO_BITS) - 1UL);

    __HAL_RCC_GPIOE_CLK_ENABLE();
    GPIO_InitTypeDef GPIO_InitStruct;
    GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
    GPIO_InitStruct.Pull = GPIO_NOPULL;
    GPIO_InitStruct.Speed = GPIO_SPEED_LOW;
    GPIO_InitStruct.Pin = GPIO_PIN_2;
    HAL_GPIO_Init(GPIOE, &GPIO_InitStruct);
    HAL_GPIO_WritePin(GPIOE, GPIO_PIN_2, GPIO_PIN_SET);
    HAL_Delay(50);
    HAL_GPIO_WritePin(GPIOE, GPIO_PIN_2, GPIO_PIN_RESET);
}

void reset_board(void) {
    initialize_discharge_pin();
}

// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here.


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>Epilogue — CasperJS  documentation</title>

    <link rel="stylesheet" href="../_static/basic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <link rel="stylesheet" href="../_static/jsdemo.css" type="text/css" />
    <link rel="stylesheet" href="../_static/sphinxcontrib-images/LightBox2/lightbox2/css/lightbox.css" type="text/css" />

    <link rel="shortcut icon" href="../_static/casperjs-favicon.ico"/>
    <link rel="top" title="CasperJS  documentation" href="../index.html" />
    <link rel="prev" title="Ontomatica Expertise" href="../15_dir/$_15-ontomatica-expertise.html" />
    <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Asap:400,700,400italic,700italic&subset=latin,latin-ext">
    <link rel="stylesheet" title="Dark theme" href="../_static/casperjs-dark.css">
    <link rel="alternate stylesheet" title="Light theme" href="../_static/casperjs-light.css">

Navigation

          index

          previous |

CasperJS  documentation »

Epilogue¶

Vegetables are a must on a diet. I suggest carrot cake, zucchini bread, and pumpkin pie. ~Jim Davis

There is a lot more juice in grapefruit than meets the eye. ~Author Unknown

Sex is good, but not as good as fresh, sweet corn. ~Garrison Keillor

Do vegetarians eat animal crackers? ~Author Unknown

Shipping is a terrible thing to do to vegetables. They probably get jet-lagged, just like people. ~Elizabeth Berry

Red meat is not bad for you. Now blue-green meat, that’s bad for you! ~Tommy Smothers

As a child my family’s menu consisted of two choices: take it or leave it. ~Buddy Hackett

My favorite animal is steak. ~Fran Lebowitz

The poets have been mysteriously silent on the subject of cheese. ~G.K. Chesterton

In Mexico we have a word for sushi: bait. ~Jose Simons

I don’t think America will have really made it until we have our own salad dressing. Until then we’re stuck behind the French, Italians, Russians and Caesarians. ~Pat McNelis

Chili represents your three stages of matter: solid, liquid, and eventually gas. ~Roseanne Barr

A nickel will get you on the subway, but garlic will get you a seat. ~Old New York proverb

It’s bizarre that the produce manager is more important to my children’s health than the pediatrician. ~Meryl Streep

We are living in a world today where lemonade is made from artificial flavors and furniture polish is made from real lemons. ~Alfred E. Newman

Hey yogurt, if you’re so cultured, how come I never see you at the opera? ~Attributed to Stephen Colbert

I will not eat oysters. I want my food dead - not sick, not wounded - dead. ~Woody Allen

Part of the secret of success in life is to eat what you like and let the food fight it out inside. ~Mark Twain

Condensed milk is wonderful. I don’t see how they can get a cow to sit down on those little cans. ~Fred Allen

The most remarkable thing about my mother is that for thirty years she served the family nothing but leftovers. The original meal has never been found. ~Calvin Trillin

If you ate pasta and antipasto, would you still be hungry? ~Author Unknown

An onion can make people cry, but there has never been a vegetable invented to make them laugh. ~Will Rogers

Training is everything. The peach was once a bitter almond; cauliflower is nothing but cabbage with a college education. ~Mark Twain

And, of course, the funniest food of all, kumquats. ~George Carlin

Pre-heat the oven? Really? If I was the sort of person who planned ahead, I wouldn’t be eating this Totino’s Party Pizza in the first place. ~Adam Peterson

A fruit is a vegetable with looks and money. Plus, if you let fruit rot, it turns into wine, something Brussels sprouts never do. ~P.J. O’Rourke

Avoid fruit and nuts. You are what you eat. ~Jim Davis

I’m not sure what makes pepperoni so good - if it’s the pepper or the oni. ~S.A. Sachs

Fish is the only food that is considered spoiled once it smells like what it is. ~P.J. O’Rourke

We got married in a fever hotter than a pepper sprout. ~June Carter Cash

Welcome to the Church of the Holy Cabbage. Lettuce pray. ~Author Unknown

A golfer’s diet: live on greens as much as possible. ~Author Unknown

Let your food be your medicine and your medicine be your food. ~Hippocrates

Stressed spelled backwards is desserts. Coincidence? I think not! ~Author Unknown

Strength is the capacity to break a chocolate bar into four pieces with your bare hands - and then eat just one of the pieces. ~Judith Viorst

There are four basic food groups: milk chocolate, dark chocolate, white chocolate, and chocolate truffles. ~Author Unknown

Chocolate is an antidepressant, which is especially useful as you start to gain weight. ~Jason Love

I’ve been on a diet for two weeks and all I’ve lost is fourteen days. ~Totie Fields

I’m on a seafood diet. I see food and I eat it. ~Author Unknown

The biggest seller is cookbooks and the second is diet books - how not to eat what you’ve just learned how to cook. ~Andy Rooney

A balanced diet is a cookie in each hand. ~Author Unknown

My doctor told me to stop having intimate dinners for four. Unless there are three other people. ~Orson Welles

The only way to lose weight is to check it as airline baggage. ~Peggy Ryan

Never eat more than you can lift. ~Miss Piggy

Caffeine isn’t a drug, it’s a vitamin! ~Author Unknown

In Seattle you haven’t had enough coffee until you can thread a sewing machine while it’s running. ~Jeff Bezos

Ultimate office automation - networked coffee machines. ~Author Unknown

Water is the most essential element of life, because without it you can’t make coffee. ~Author Unknown

Vegetarian - that’s an old Indian word meaning “lousy hunter.” ~Andy Rooney

If vegetarians eat vegetables, what do humanitarians eat? ~Author Unknown

Previous topic

Ontomatica Expertise

Index

Thesaurus

This Page

Show Source

Quick search

    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    Enter search terms or a module, class or function name.

Navigation

          index

          previous |

CasperJS  documentation »

        © Copyright 2011-2015 Nicolas Perriault and contributors. CasperJS logo by Jeremy Forveille.
      Created using Sphinx 1.3.1.


text:
title: April 2020
description: sensenet frontend updates of April 2020
---

## Work From Home 🏠

Because of the pandemic we are now working from home. This doesn't mean that the development is stopped. Here are the changes we made.

### @sensenet/redux@5.3.0

- Added some missing actions for
  - put
  - content creation with a content template
  - preview related actions
  - preview comments
  - allowedchildtypes
  - restore from trash
  - add/remove list fields

### @sensenet/document-viewer-react@2.0.6

- fix: adding comments returned error, because the x and y coordinates were floating numbers and the request body was not a valid json. These two params' type is changed to string. [#617](https://github.com/SenseNet/sn-client/pull/617)

### sn-dms-demo@2.0.1

- DMS demo is refactored to use create react app.

### Admin-ui@1.6.0

- Deleting the active item from tree now doesn't crash. [#591](https://github.com/SenseNet/sn-client/pull/591)
- Fix double click on localization file and on users and groups [#604](https://github.com/SenseNet/sn-client/pull/604)
- Changed our progress indicator to circle [#609](https://github.com/SenseNet/sn-client/pull/609)

 ![Admin-ui full screen loader](/img/admin-ui-fullscreen-loader.gif "Admin-ui full screen loader")

- 🆕 We restyled our forms [#593](https://github.com/SenseNet/sn-client/pull/593)

![Admin-ui new form](/img/admin-ui-new-form.png "Admin-ui new form")

You can find the release [here](https://github.com/SenseNet/sn-client/releases/tag/2020.4.0)


text:
package ubc.pavlab.aspiredb.server.dao;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import ubc.pavlab.aspiredb.server.model.Indel;

/**
 * DAO operations for indel variants.
 *
 * @author ??
 * @version $Id: IndelDaoImpl.java,v 1.3 2013/06/11 22:30:46 anton Exp $
 */
@Repository("indelDao")
public class IndelDaoImpl extends VariantDaoBaseImpl<Indel> implements IndelDao {

    @Autowired
    public IndelDaoImpl( SessionFactory sessionFactory ) {
        super( Indel.class );
        super.setSessionFactory( sessionFactory );
    }

}


text:
import { Injectable } from '@angular/core';
import { HttpClient, HttpResponse } from '@angular/common/http';

import { Observable } from 'rxjs/Observable';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

import { Data } from '../../model/data.model';

import { ClubsHttpService } from '../../clubs/clubs-http.service';

@Injectable()
export class ResultsHttpClubsService extends ClubsHttpService {

    constructor(protected http: HttpClient) {
        super(http);
    }

  public getClubsData(): Observable<Data> {
    return this.getData(this.endPoint);
   }
}


text:
package org.ansj.splitWord.analysis;

import org.ansj.domain.Result;
import org.ansj.domain.Term;
import org.ansj.recognition.arrimpl.NumRecognition;
import org.ansj.recognition.arrimpl.PersonRecognition;
import org.ansj.recognition.arrimpl.UserDefineRecognition;
import org.ansj.splitWord.Analysis;
import org.ansj.util.AnsjReader;
import org.ansj.util.Graph;
import org.ansj.util.TermUtil.InsertTermType;
import org.nlpcn.commons.lang.tire.domain.Forest;

import java.io.Reader;
import java.util.ArrayList;
import java.util.List;

/**
 * 标准分词
 *
 * @author ansj
 */
public class ToAnalysis extends Analysis {

	@Override
	protected List<Term> getResult(final Graph graph) {

		Merger merger = new Merger() {
			@Override
			public List<Term> merger() {

				graph.walkPath();

				// 姓名识别
				if (graph.hasPerson && isNameRecognition) {
					// 人名识别
					new PersonRecognition().recognition(graph);
				}

				// 数字发现
				if (isNumRecognition) {
					new NumRecognition(isQuantifierRecognition && graph.hasNumQua).recognition(graph);
				}

				// 用户自定义词典的识别
				userDefineRecognition(graph, forests);

				return getResult();
			}

			private void userDefineRecognition(final Graph graph, Forest... forests) {
				new UserDefineRecognition(InsertTermType.SKIP, forests).recognition(graph);
				graph.rmLittlePath();
				graph.walkPathByScore();
			}

			private List<Term> getResult() {
				List<Term> result = new ArrayList<Term>();
				int length = graph.terms.length - 1;
				for (int i = 0; i < length; i++) {
					if (graph.terms[i] != null) {
						setIsNewWord(graph.terms[i]) ;
						result.add(graph.terms[i]);
					}
				}
				setRealName(graph, result);
				return result;
			}
		};
		return merger.merger();
	}

	public ToAnalysis() {
		super();
	}

	public ToAnalysis(Reader reader) {
		super.resetContent(new AnsjReader(reader));
	}

	public static Result parse(String str) {
		return new ToAnalysis().parseStr(str);
	}

	public static Result parse(String str, Forest... forests) {
		return new ToAnalysis().setForests(forests).parseStr(str);
	}

}


text:
"use strict";

import axios from 'axios';

import PHRDispacher from '../dispatcher/PHRDispatcher';
import DashboardConstants from '../constants/DashboardConstants';
import SessionConstants from '../constants/SessionConstants';

class SessionActions {
    constructor() {}

    /**
     * Get Session
     */
    static getSession() {
        console.log('getSession');
        let token, user;
        if(typeof(Storage) !== "undefined") {
            token = localStorage.getItem('token') || '';
            user = JSON.parse(localStorage.getItem('user')) || {};
        } else {
            console.log('No Web Storage support..');
        }
        if(user.hasOwnProperty('username')) {
            axios.get('/user/' + user.username, {
                headers: {
                    'Authorization': 'Bearer ' + token
                }
            }).then(res => {
                console.log('/user/{username} res: ', res.data);
                PHRDispacher.dispatch({
                    actionType: SessionConstants.NEW_SESSION,
                    user: res.data.user
                });
                PHRDispacher.dispatch({
                    actionType: DashboardConstants.DASHBOARD_GET_PATIENT,
                    patient: res.data.user
                });
            }).catch(err => {
                console.error(err);
                PHRDispacher.dispatch({
                    actionType: SessionConstants.INVALID_SESSION,
                    error: err
                });
            });
        } else {
            PHRDispacher.dispatch({
                actionType: SessionConstants.INVALID_SESSION,
                error: {
                    type: 'not_found',
                    error: new Error('Username is not available in localStorage.'),
                    message: 'Username is not available in localStorage.'
                }
            });
        }
    }
}

export default SessionActions;


text:
<?php
/**
 * User: Joe Linn
 * Date: 3/20/2014
 * Time: 5:20 PM
 */

namespace Stripe\Response\Cards;

use JMS\Serializer\Annotation\Type;
use Stripe\Response\AbstractListResponse;

class ListCardsResponse extends AbstractListResponse
{
    /**
     * @Type("array<Stripe\Response\Cards\CardResponse>")
     * @var CardResponse[]
     */
    protected $data;

    /**
     * @return CardResponse[]
     */
    public function getData()
    {
        return $this->data;
    }

    /**
     * @param CardResponse[] $data
     * @return $this
     */
    public function setData($data)
    {
        $this->data = $data;
        return $this;
    }
}


text:
package com.github.jeroenr.tepkin.examples

import akka.stream.ActorMaterializer
import akka.util.Timeout
import com.github.jeroenr.bson.BsonDocument
import com.github.jeroenr.tepkin.MongoClient

import scala.concurrent.duration._

object TailableCursorExample extends App {

  val client = MongoClient("mongodb://localhost")

  import client.{context, ec}

  implicit val timeout: Timeout = 5.seconds
  implicit val mat = ActorMaterializer()

  val db = client("tepkin")
  val messages = db("messages")

  db.createCollection("messages", capped = Some(true), size = Some(100000000))

  messages
    .find(query = BsonDocument.empty, tailable = true)
    .runForeach(println)
}


text:
package org.mifos.reports.branchreport;

import static org.mifos.reports.branchreport.BranchReportStaffingLevelSummaryBO.IS_NOT_TOTAL;
import static org.mifos.reports.branchreport.BranchReportStaffingLevelSummaryBO.IS_TOTAL;

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

import junit.framework.Assert;
import junit.framework.TestCase;

public class BranchReportStaffingLevelSummaryBOTest extends TestCase {

    public void testCompareToReturnsAnyBOGreaterThanTotalSummaryBO() {
        Assert.assertEquals(-1, new BranchReportStaffingLevelSummaryBO(IS_NOT_TOTAL, "A", 1).compareTo(new BranchReportStaffingLevelSummaryBO(IS_TOTAL, "A", 1)));
        Assert.assertEquals(1, new BranchReportStaffingLevelSummaryBO(IS_TOTAL, "A", 1).compareTo(new BranchReportStaffingLevelSummaryBO(IS_NOT_TOTAL, "A", 1)));
    }

    public void testCompareTo() throws Exception {
        Assert.assertEquals(-1, new BranchReportStaffingLevelSummaryBO(IS_NOT_TOTAL, "A", 1).compareTo(new BranchReportStaffingLevelSummaryBO(IS_NOT_TOTAL, "B", 1)));
        Assert.assertEquals(1, new BranchReportStaffingLevelSummaryBO(IS_NOT_TOTAL, "B", 1).compareTo(new BranchReportStaffingLevelSummaryBO(IS_NOT_TOTAL, "A", 1)));
        Assert.assertEquals(0, new BranchReportStaffingLevelSummaryBO(IS_NOT_TOTAL, "A", 1).compareTo(new BranchReportStaffingLevelSummaryBO(IS_NOT_TOTAL, "A", 1)));
    }

    public void testSortingBasedOnComparator() throws Exception {
        BranchReportStaffingLevelSummaryBO one = new BranchReportStaffingLevelSummaryBO(IS_NOT_TOTAL, "A", 1);
        BranchReportStaffingLevelSummaryBO two = new BranchReportStaffingLevelSummaryBO(IS_NOT_TOTAL, "B", 1);
        BranchReportStaffingLevelSummaryBO three = new BranchReportStaffingLevelSummaryBO(IS_NOT_TOTAL, "C", 1);
        BranchReportStaffingLevelSummaryBO total = new BranchReportStaffingLevelSummaryBO(IS_TOTAL, "A", 1);
        List<BranchReportStaffingLevelSummaryBO> list = new ArrayList<BranchReportStaffingLevelSummaryBO>();
        list.add(three);
        list.add(one);
        list.add(total);
        list.add(two);
        Collections.sort(list);
       Assert.assertEquals(0, one.compareTo(list.get(0)));
       Assert.assertEquals(0, two.compareTo(list.get(1)));
       Assert.assertEquals(0, three.compareTo(list.get(2)));
       Assert.assertEquals(0, total.compareTo(list.get(3)));
    }
}


text:
package io.github.narikiro.xtrapunish.manager;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Random;

import org.spongepowered.api.Sponge;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.format.TextColor;

import io.github.narikiro.xtrapunish.util.TaskPlayer;

public class ChatSpamManager {

    private List<TaskPlayer> taskPlayers = new ArrayList<>();

    public void storeSpam(TaskPlayer taskPlayer) {
        this.taskPlayers.add(taskPlayer);
    }

    public boolean stopSpam(Player player) {
        for (TaskPlayer taskPlayer : this.taskPlayers) {
            if (taskPlayer.player.equals(player)) {
                taskPlayer.task.cancel();
                this.taskPlayers.remove(taskPlayer);
                return true;
            }
        }
        return false;
    }

    public Text generateSpam() {
        Text.Builder message = Text.builder();
        Random random = new Random();
        Collection<TextColor> textCollection = Sponge.getRegistry().getAllOf(TextColor.class);

        // With 50 chars in each spam message
        for (int i2 = 0; i2 < 50; i2++) {
            char letter = (char) (random.nextInt(26) + 'a');
            int textCol = random.nextInt(textCollection.size());
            message.append(Text.of(textCollection.toArray()[textCol], letter));
        }
        return message.build();
    }
}


text:
<?xml version='1.0' encoding='utf-8'?>
<widget id="com.github.lheberlie.cordova.mobilestarter" version="0.0.1" xmlns="http://www.w3.org/ns/widgets"
        xmlns:cdv="http://cordova.apache.org/ns/1.0">
    <name>Mobile Starter</name>
    <description>
        A sample Apache Cordova application that responds to the deviceready event.
    </description>
    <author email="dev@cordova.apache.org" href="http://cordova.io">
        Apache Cordova Team
    </author>
    <content src="index.html"/>
    <!--
      Define access to external domains.

      <access />            - a blank access tag denies access to all external resources.
      <access origin="*" /> - a wildcard access tag allows access to all external resource.

      Otherwise, you can specify specific domains:
  -->
    <access origin="http://127.0.0.1*"/>
    <!-- allow local pages -->

    <!-- All protocols and subdomains below are allowed -->
    <access origin="*.arcgis.com"/>
    <access origin="*.arcgisonline.com"/>

    <!--
        <access origin="http://phonegap.com" />                    - allow any secure requests to http://phonegap.com/
        <access origin="http://phonegap.com" subdomains="true" />  - same as above, but including subdomains, such as http://build.phonegap.com/
        <access origin="http://phonegap.com" browserOnly="true" /> - only allows http://phonegap.com to be opened by the child browser.
    -->
</widget>


text:
#ifndef CRYPTOPP_ZINFLATE_H
#define CRYPTOPP_ZINFLATE_H

#include "cryptlib.h"
#include "secblock.h"
#include "filters.h"
#include "stdcpp.h"

NAMESPACE_BEGIN(CryptoPP)

//! \class LowFirstBitReader
//! \since Crypto++ 1.0
class LowFirstBitReader
{
public:
	LowFirstBitReader(BufferedTransformation &store)
		: m_store(store), m_buffer(0), m_bitsBuffered(0) {}
	unsigned int BitsBuffered() const {return m_bitsBuffered;}
	unsigned long PeekBuffer() const {return m_buffer;}
	bool FillBuffer(unsigned int length);
	unsigned long PeekBits(unsigned int length);
	void SkipBits(unsigned int length);
	unsigned long GetBits(unsigned int length);

private:
	BufferedTransformation &m_store;
	unsigned long m_buffer;
	unsigned int m_bitsBuffered;
};

struct CodeLessThan;

//! \class HuffmanDecoder
//! \brief Huffman Decoder
//! \since Crypto++ 1.0
class HuffmanDecoder
{
public:
	typedef unsigned int code_t;
	typedef unsigned int value_t;
	enum {MAX_CODE_BITS = sizeof(code_t)*8};

	class Err : public Exception {public: Err(const std::string &what) : Exception(INVALID_DATA_FORMAT, "HuffmanDecoder: " + what) {}};

	HuffmanDecoder() : m_maxCodeBits(0), m_cacheBits(0), m_cacheMask(0), m_normalizedCacheMask(0) {}
	HuffmanDecoder(const unsigned int *codeBitLengths, unsigned int nCodes)
		: m_maxCodeBits(0), m_cacheBits(0), m_cacheMask(0), m_normalizedCacheMask(0)
			{Initialize(codeBitLengths, nCodes);}

	void Initialize(const unsigned int *codeBitLengths, unsigned int nCodes);
	unsigned int Decode(code_t code, /* out */ value_t &value) const;
	bool Decode(LowFirstBitReader &reader, value_t &value) const;

private:
	friend struct CodeLessThan;

	struct CodeInfo
	{
		CodeInfo(code_t code=0, unsigned int len=0, value_t value=0) : code(code), len(len), value(value) {}
		inline bool operator<(const CodeInfo &rhs) const {return code < rhs.code;}
		code_t code;
		unsigned int len;
		value_t value;
	};

	struct LookupEntry
	{
		unsigned int type;
		union
		{
			value_t value;
			const CodeInfo *begin;
		};
		union
		{
			unsigned int len;
			const CodeInfo *end;
		};
	};

	static code_t NormalizeCode(code_t code, unsigned int codeBits);
	void FillCacheEntry(LookupEntry &entry, code_t normalizedCode) const;

	unsigned int m_maxCodeBits, m_cacheBits, m_cacheMask, m_normalizedCacheMask;
	std::vector<CodeInfo, AllocatorWithCleanup<CodeInfo> > m_codeToValue;
	mutable std::vector<LookupEntry, AllocatorWithCleanup<LookupEntry> > m_cache;
};

//! \class Inflator
//! \brief DEFLATE decompressor (RFC 1951)
//! \since Crypto++ 1.0
class Inflator : public AutoSignaling<Filter>
{
public:
	class Err : public Exception
	{
	public:
		Err(ErrorType e, const std::string &s)
			: Exception(e, s) {}
	};
	//! \brief Exception thrown when a truncated stream is encountered
	class UnexpectedEndErr : public Err {public: UnexpectedEndErr() : Err(INVALID_DATA_FORMAT, "Inflator: unexpected end of compressed block") {}};
	//! \brief Exception thrown when a bad block is encountered
	class BadBlockErr : public Err {public: BadBlockErr() : Err(INVALID_DATA_FORMAT, "Inflator: error in compressed block") {}};
	//! \brief Exception thrown when an invalid distance is encountered
	class BadDistanceErr : public Err {public: BadDistanceErr() : Err(INVALID_DATA_FORMAT, "Inflator: error in bit distance") {}};

	//! \brief RFC 1951 Decompressor
	//! \param attachment the filter's attached transformation
	//! \param repeat decompress multiple compressed streams in series
	//! \param autoSignalPropagation 0 to turn off MessageEnd signal
	Inflator(BufferedTransformation *attachment = NULLPTR, bool repeat = false, int autoSignalPropagation = -1);

	void IsolatedInitialize(const NameValuePairs &parameters);
	size_t Put2(const byte *inString, size_t length, int messageEnd, bool blocking);
	bool IsolatedFlush(bool hardFlush, bool blocking);

	virtual unsigned int GetLog2WindowSize() const {return 15;}

protected:
	ByteQueue m_inQueue;

private:
	virtual unsigned int MaxPrestreamHeaderSize() const {return 0;}
	virtual void ProcessPrestreamHeader() {}
	virtual void ProcessDecompressedData(const byte *string, size_t length)
		{AttachedTransformation()->Put(string, length);}
	virtual unsigned int MaxPoststreamTailSize() const {return 0;}
	virtual void ProcessPoststreamTail() {}

	void ProcessInput(bool flush);
	void DecodeHeader();
	bool DecodeBody();
	void FlushOutput();
	void OutputByte(byte b);
	void OutputString(const byte *string, size_t length);
	void OutputPast(unsigned int length, unsigned int distance);

	static const HuffmanDecoder *FixedLiteralDecoder();
	static const HuffmanDecoder *FixedDistanceDecoder();

	const HuffmanDecoder& GetLiteralDecoder() const;
	const HuffmanDecoder& GetDistanceDecoder() const;

	enum State {PRE_STREAM, WAIT_HEADER, DECODING_BODY, POST_STREAM, AFTER_END};
	State m_state;
	bool m_repeat, m_eof, m_wrappedAround;
	byte m_blockType;
	word16 m_storedLen;
	enum NextDecode {LITERAL, LENGTH_BITS, DISTANCE, DISTANCE_BITS};
	NextDecode m_nextDecode;
	unsigned int m_literal, m_distance;	// for LENGTH_BITS or DISTANCE_BITS
	HuffmanDecoder m_dynamicLiteralDecoder, m_dynamicDistanceDecoder;
	LowFirstBitReader m_reader;
	SecByteBlock m_window;
	size_t m_current, m_lastFlush;
};

NAMESPACE_END

#endif


text:
'use strict';

var chalk = require('chalk');
var extend = require('../utils/extend');
var fs = require('fs');
var path = require('path');
var shell = require('shelljs');
var request = require('request');
var unzip = require('unzip');
var argv = require('optimist').argv;
var prompt = require('prompt');
var IonicAppLib = require('ionic-app-lib');
var appLibUtils = IonicAppLib.utils;
var log = IonicAppLib.logging.logger;
var exec = require('child_process').exec;
var Q = require('q');

var settings =  {
  title: 'lib',
  name: 'lib',
  summary: 'Gets Ionic library version or updates the Ionic library',
  args: {
    '[options]': '',
    '[update]': 'Updates the Ionic Framework in www/lib/ionic'
  },
  options: {
    '--version|-v': 'Specific Ionic version\nOtherwise it defaults to the latest version'
  },
  isProjectTask: true
};

function run(ionic, argv) {

  // This command will be deprecated in the future.
  var deprecationMsg = 'This command has been ' + chalk.red('deprecated') + '.  All ' +
   'resources are currently available in NPM and we recommend that you use NPM to manage these.\n' +
   'More information is available here: https://github.com/driftyco/ionic-cli/wiki/Migrating-to-NPM-from-bower\n';
  log.info(chalk.bold(deprecationMsg));

  if (!fs.existsSync(path.resolve('www'))) {
    return appLibUtils.fail('"www" directory cannot be found. Make sure the working directory ' +
                      'is at the top level of an Ionic project.', 'lib');
  }

  // Gather version data from version.json or bower.json files
  var data = loadVersionData();

  // If this is an update command then do an update and exit
  if (argv._.length > 1 &&
      (argv._[1].toLowerCase() === 'update' || argv._[1].toLowerCase() === 'up')) {
    return updateLibVersion(data);
  }

  // Otherwise lets print the version info
  return printLibVersions(data);
}

function loadVersionData() {

  var versionFilePath = path.resolve('www/lib/ionic/version.json');
  var usesBower = false;
  var local = {};

  if (!fs.existsSync(versionFilePath)) {
    versionFilePath = path.resolve('www/lib/ionic/bower.json');
    usesBower = fs.existsSync(versionFilePath);
  }

  try {
    local = JSON.parse(fs.readFileSync(versionFilePath));
  } catch (e) {
    log.error('Unable to load ionic lib version information');
  }

  return {
    versionFilePath: versionFilePath,
    usesBower: usesBower,
    local: local
  };
}

function printLibVersions(data) {

  log.info(chalk.bold.green('Local Ionic version: ') + data.local.version + '  (' + data.versionFilePath + ')');

  getVersionData('latest').then(function(versionData) {
    log.info(chalk.bold.green('Latest Ionic version: ') + versionData.version_number +
             '  (released ' + versionData.release_date + ')');

    if (data.local.version !== versionData.version_number) {
      log.info(chalk.yellow(' * Local version is out of date'));
    } else {
      log.info(chalk.green(' * Local version up to date'));
    }
  });
}

function getVersionData(data, version) {
  var q = Q.defer();

  var url = 'http://code.ionicframework.com';
  if (version === 'latest') {
    url += '/latest.json';
  } else {
    url += '/' + version + '/version.json';
  }

  var proxy = process.env.PROXY || process.env.http_proxy || null;
  request({ url: url, proxy: proxy }, function(err, res, body) {
    try {
      if (err || !res || !body) {
        log.error('Unable to receive version data');
        q.reject();
        return;
      }
      if (parseInt(res.statusCode, 10) === 404) {
        log.error('Invalid version: ' + version);
        q.reject();
        return;
      }
      if (parseInt(res.statusCode, 10) >= 400) {
        log.error('Unable to load version data');
        q.reject();
        return;
      }
      var versionData = JSON.parse(body);
      versionData['version_number'] = versionData.version_number || versionData.version;
      versionData['version_codename'] = versionData.version_codename || versionData.codename;
      versionData['release_date'] = versionData.release_date || versionData.date;

      q.resolve(versionData);
    } catch (e) {
      log.error('Error loading ' + chalk.bold(version) + ' version information');
      q.reject();
    }
  });

  return q.promise;
}

function updateLibVersion(data) {

  if (data.usesBower) {
    var bowerCmd = exec('bower update ionic');

    bowerCmd.stdout.on('data', function(data) {
      process.stdout.write(data);
    });

    bowerCmd.stderr.on('data', function(data) {
      if (data) {
        process.stderr.write(chalk.red.bold(data.toString()));
      }
    });

    return;
  }

  prompt.message = '';
  prompt.delimiter = '';
  prompt.start();

  var libPath = path.resolve('www/lib/ionic/');

  log.info(chalk.green.bold('Are you sure you want to replace ') + chalk.bold(libPath) +
           chalk.green.bold(' with an updated version of Ionic?'));

  var promptProperties = {
    areYouSure: {
      name: 'areYouSure',
      description: chalk.yellow.bold('(yes/no):'),
      required: true
    }
  };

  prompt.get({ properties: promptProperties }, function(err, promptResult) {
    if (err) {
      return log.error(err);
    }

    var areYouSure = promptResult.areYouSure.toLowerCase().trim();
    if (areYouSure === 'yes' || areYouSure === 'y') {
      getLatest(data);
    }
  });
}

function getLatest() {
  var dirPath = path.resolve('www/lib/');
  if (!fs.existsSync(dirPath)) {
    fs.mkdirSync(dirPath);
  }

  dirPath = path.resolve('www/lib/ionic/');
  if (!fs.existsSync(dirPath)) {
    fs.mkdirSync(dirPath);
  }

  var version = argv.version || argv.v;
  if (version === true || !version) {
    version = 'latest';
  }

  getVersionData(version).then(function(versionData) {
    if (version === 'latest') {
      log.info(chalk.bold.green('Latest version: ') + versionData.version_number +
               '  (released ' + versionData.release_date + ')');
    } else {
      log.info(chalk.bold.green('Version: ') + versionData.version_number +
               '  (released ' + versionData.release_date + ')');
    }
    downloadZip(versionData.version_number);
  });
}

function downloadZip(data, version) {
  var archivePath = 'https://github.com/driftyco/ionic-bower/archive/v' + version + '.zip';

  var tmpExtractPath = path.resolve('www/lib/.ionic');
  var tmpZipPath = path.join(data.tmpExtractPath, 'ionic.zip');

  if (!fs.existsSync(data.tmpExtractPath)) {
    fs.mkdirSync(data.tmpExtractPath);
  }

  log.info(chalk.bold.green('Downloading: ') + archivePath);

  var proxy = process.env.PROXY || null;
  request({ url: archivePath, rejectUnauthorized: false, encoding: null, proxy: proxy }, function(err, res, body) {
    if (err) {
      log.error(err);
      return;
    }
    if (parseInt(res.statusCode, 10) === 404 || parseInt(res.statusCode, 10) === 406) {
      log.error('Invalid version: ' + version);
      return;
    }
    if (parseInt(res.statusCode, 10) >= 400) {
      log.error('Unable to download zip (' + res.statusCode + ')');
      return;
    }
    try {
      fs.writeFileSync(tmpZipPath, body);
      updateFiles(data, tmpZipPath, tmpExtractPath);
    } catch (e) {
      log.error(e);
    }
  }).on('response', function(res) {

    var ProgressBar = require('progress');
    var bar = new ProgressBar('[:bar]  :percent  :etas', {
      complete: '=',
      incomplete: ' ',
      width: 30,
      total: parseInt(res.headers['content-length'], 10)
    });

    res.on('data', function(chunk) {
      try {
        bar.tick(chunk.length);
      } catch (e) {
        log.error(e);
      }
    });

  }).on('error', function(err) {
    try {
      fs.unlink(tmpZipPath);
    } catch (e) {
      log.error(e);
    }
    log.error(err);
  });
}

function updateFiles(data, tmpZipPath, tmpExtractPath) {
  var ionicLibDir = path.resolve('www/lib/ionic');

  try {
    var readStream = fs.createReadStream(tmpZipPath);
    readStream.on('error', function(err) {
      log.debug('updateFiles readStream error: ' + err);
    });

    var writeStream = unzip.Extract({ path: tmpExtractPath }); // eslint-disable-line new-cap
    writeStream.on('close', function() {
      try {
        shell.rm('-rf', tmpZipPath);
      } catch (e) {
        log.error(e);
      }

      try {
        var dir = fs.readdirSync(tmpExtractPath);
        var copyFrom;
        for (var x = 0; x < dir.length; x += 1) {
          if (dir[x].indexOf('ionic') === 0) {
            copyFrom = path.join(tmpExtractPath, dir[x], '*');
          }
        }
        if (!copyFrom) {
          log.error('updateFiles, invalid zip');
          return;
        }

        shell.cp('-Rf', copyFrom, ionicLibDir);

        try {
          shell.rm('-rf', tmpExtractPath);
        } catch (e) {
          log.error(e);
        }

        try {
          shell.rm('-rf', path.join(ionicLibDir, 'README.md'));
        } catch (e) {
          log.error(e);
        }

        try {
          shell.rm('-rf', path.join(ionicLibDir, 'bower.json'));
        } catch (e) {
          log.error(e);
        }

        log.info(chalk.bold.green('Ionic version updated to: ') + chalk.bold(data.versionData.version_number));

        writeVersionData(data);

        var ionicBower = require('../utils/bower').IonicBower;
        ionicBower.setIonicVersion(data.versionData.version_number);

      } catch (e) {
        log.error('updateFiles Error: ' + e);
      }
    });
    writeStream.on('error', function(err) {
      log.error('updateFiles writeStream: ' + err);
    });
    readStream.pipe(writeStream);

  } catch (e) {
    log.error('updateFiles Error: ' + e);
  }
}

function writeVersionData(data) {
  try {
    var versionData = {
      version: data.versionData.version_number || data.versionData.version,
      codename: data.versionData.version_codename || data.versionData.codename,
      date: data.versionData.release_date || data.versionData.date
    };

    fs.writeFileSync(path.resolve('www/lib/ionic/version.json'),
                      JSON.stringify(versionData, null, 2));

  } catch (e) {
    log.error('Error writing version data: ' + e);
  }
}

module.exports = extend(settings, {
  run: run
});


text:
from django.conf.urls.defaults import *
from blog import views

urlpatterns = patterns('',
    url(r'^$', views.BlogList.as_view(), name="blog_list"),
    url(r'^add/$', views.BlogCreate.as_view(), name='blog_create'),
    url(r'^post/(?P<slug>[-_\w]+)/edit/$', views.BlogUpdate.as_view(), name='blog_update'),
    url(r'^post/(?P<slug>[-_\w]+)/delete/$', views.BlogDelete.as_view(), name='blog_delete'),
    url(r'^post/(?P<slug>[-_\w]+)/$', views.BlogDetail.as_view(), name='blog_detail'),
)


text:
from .image_search_api import ImageSearchAPI
from .version import VERSION

__all__ = ['ImageSearchAPI']

__version__ = VERSION


text:
@interface ViewController () <GVMusicPlayerControllerDelegate, MPMediaPickerControllerDelegate>
@property (weak, nonatomic) IBOutlet UILabel *songLabel;
@property (weak, nonatomic) IBOutlet UILabel *artistLabel;
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (weak, nonatomic) IBOutlet UIButton *playPauseButton;
@property (weak, nonatomic) IBOutlet UISlider *progressSlider;
@property (weak, nonatomic) IBOutlet UISlider *volumeSlider;
@property (weak, nonatomic) IBOutlet UILabel *trackCurrentPlaybackTimeLabel;
@property (weak, nonatomic) IBOutlet UILabel *trackLengthLabel;
@property (weak, nonatomic) IBOutlet UIView *chooseView;
@property (weak, nonatomic) IBOutlet UIButton *repeatButton;
@property (weak, nonatomic) IBOutlet UIButton *shuffleButton;
@property (strong, nonatomic) NSTimer *timer;
@property BOOL panningProgress;
@property BOOL panningVolume;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self.view bringSubviewToFront:self.chooseView];

    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timedJob) userInfo:nil repeats:YES];
    [self.timer fire];
}

- (void)viewWillAppear:(BOOL)animated {
    // NOTE: add and remove the GVMusicPlayerController delegate in
    // the viewWillAppear / viewDidDisappear methods, not in the
    // viewDidLoad / viewDidUnload methods - it will result in dangling
    // objects in memory.
    [super viewWillAppear:animated];
    [[GVMusicPlayerController sharedInstance] addDelegate:self];
}

- (void)viewDidDisappear:(BOOL)animated {
    [[GVMusicPlayerController sharedInstance] removeDelegate:self];
    [super viewDidDisappear:animated];
}

- (void)timedJob {
    if (!self.panningProgress) {
        self.progressSlider.value = [GVMusicPlayerController sharedInstance].currentPlaybackTime;
        self.trackCurrentPlaybackTimeLabel.text = [NSString stringFromTime:[GVMusicPlayerController sharedInstance].currentPlaybackTime];
    }
}

#pragma mark - Catch remote control events, forward to the music player

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    self.shuffleButton.selected = ([GVMusicPlayerController sharedInstance].shuffleMode != MPMusicShuffleModeOff);
    [self setCorrectRepeatButtomImage];
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    [self becomeFirstResponder];
}

- (void)viewWillDisappear:(BOOL)animated {
    [[UIApplication sharedApplication] endReceivingRemoteControlEvents];
    [self resignFirstResponder];
    [super viewWillDisappear:animated];
}

- (BOOL)canBecomeFirstResponder {
    return YES;
}

- (void)remoteControlReceivedWithEvent:(UIEvent *)receivedEvent {
    [[GVMusicPlayerController sharedInstance] remoteControlReceivedWithEvent:receivedEvent];
}

#pragma mark - IBActions

- (IBAction)playButtonPressed {
    if ([GVMusicPlayerController sharedInstance].playbackState == MPMusicPlaybackStatePlaying) {
        [[GVMusicPlayerController sharedInstance] pause];
    } else {
        [[GVMusicPlayerController sharedInstance] play];
    }
}

- (IBAction)prevButtonPressed {
    [[GVMusicPlayerController sharedInstance] skipToPreviousItem];
}

- (IBAction)nextButtonPressed {
    [[GVMusicPlayerController sharedInstance] skipToNextItem];
}

- (IBAction)chooseButtonPressed {
#if !(TARGET_IPHONE_SIMULATOR)
    MPMediaPickerController *picker = [[MPMediaPickerController alloc] initWithMediaTypes:MPMediaTypeMusic];
    picker.delegate = self;
    picker.allowsPickingMultipleItems = YES;
    [self presentViewController:picker animated:YES completion:nil];
#endif
}

- (IBAction)playEverythingButtonPressed {
#if !(TARGET_IPHONE_SIMULATOR)
    MPMediaQuery *query = [MPMediaQuery songsQuery];
    [[GVMusicPlayerController sharedInstance] setQueueWithQuery:query];
    [[GVMusicPlayerController sharedInstance] play];
#endif
}

- (IBAction)volumeChanged:(UISlider *)sender {
    self.panningVolume = YES;
    [GVMusicPlayerController sharedInstance].volume = sender.value;
}

- (IBAction)volumeEnd {
    self.panningVolume = NO;
}

- (IBAction)progressChanged:(UISlider *)sender {
    // While dragging the progress slider around, we change the time label,
    // but we're not actually changing the playback time yet.
    self.panningProgress = YES;
    self.trackCurrentPlaybackTimeLabel.text = [NSString stringFromTime:sender.value];
}

- (IBAction)progressEnd {
    // Only when dragging is done, we change the playback time.
    [GVMusicPlayerController sharedInstance].currentPlaybackTime = self.progressSlider.value;
    self.panningProgress = NO;
}

- (IBAction)shuffleButtonPressed {
    self.shuffleButton.selected = !self.shuffleButton.selected;

    if (self.shuffleButton.selected) {
        [GVMusicPlayerController sharedInstance].shuffleMode = MPMusicShuffleModeSongs;
    } else {
        [GVMusicPlayerController sharedInstance].shuffleMode = MPMusicShuffleModeOff;
    }
}

- (IBAction)repeatButtonPressed {
    switch ([GVMusicPlayerController sharedInstance].repeatMode) {
        case MPMusicRepeatModeAll:
            // From all to one
            [GVMusicPlayerController sharedInstance].repeatMode = MPMusicRepeatModeOne;
            break;

        case MPMusicRepeatModeOne:
            // From one to none
            [GVMusicPlayerController sharedInstance].repeatMode = MPMusicRepeatModeNone;
            break;

        case MPMusicRepeatModeNone:
            // From none to all
            [GVMusicPlayerController sharedInstance].repeatMode = MPMusicRepeatModeAll;
            break;

        default:
            [GVMusicPlayerController sharedInstance].repeatMode = MPMusicRepeatModeAll;
            break;
    }

    [self setCorrectRepeatButtomImage];
}

- (void)setCorrectRepeatButtomImage {
    NSString *imageName;

    switch ([GVMusicPlayerController sharedInstance].repeatMode) {
        case MPMusicRepeatModeAll:
            imageName = @"Track_Repeat_On";
            break;

        case MPMusicRepeatModeOne:
            imageName = @"Track_Repeat_On_Track";
            break;

        case MPMusicRepeatModeNone:
            imageName = @"Track_Repeat_Off";
            break;

        default:
            imageName = @"Track_Repeat_Off";
            break;
    }

    [self.repeatButton setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
}

#pragma mark - GVMusicPlayerControllerDelegate

- (void)musicPlayer:(GVMusicPlayerController *)musicPlayer playbackStateChanged:(MPMusicPlaybackState)playbackState previousPlaybackState:(MPMusicPlaybackState)previousPlaybackState {
    self.playPauseButton.selected = (playbackState == MPMusicPlaybackStatePlaying);
}

- (void)musicPlayer:(GVMusicPlayerController *)musicPlayer trackDidChange:(MPMediaItem *)nowPlayingItem previousTrack:(MPMediaItem *)previousTrack {
    if (!nowPlayingItem) {
        self.chooseView.hidden = NO;
        return;
    }

    self.chooseView.hidden = YES;

    // Time labels
    NSTimeInterval trackLength = [[nowPlayingItem valueForProperty:MPMediaItemPropertyPlaybackDuration] doubleValue];
    self.trackLengthLabel.text = [NSString stringFromTime:trackLength];
    self.progressSlider.value = 0;
    self.progressSlider.maximumValue = trackLength;

    // Labels
    self.songLabel.text = [nowPlayingItem valueForProperty:MPMediaItemPropertyTitle];
    self.artistLabel.text = [nowPlayingItem valueForProperty:MPMediaItemPropertyArtist];

    // Artwork
    MPMediaItemArtwork *artwork = [nowPlayingItem valueForProperty:MPMediaItemPropertyArtwork];
    if (artwork != nil) {
        self.imageView.image = [artwork imageWithSize:self.imageView.frame.size];
    }

    NSLog(@"Proof that this code is being called, even in the background!");
}

- (void)musicPlayer:(GVMusicPlayerController *)musicPlayer endOfQueueReached:(MPMediaItem *)lastTrack {
    NSLog(@"End of queue, but last track was %@", [lastTrack valueForProperty:MPMediaItemPropertyTitle]);
}

- (void)musicPlayer:(GVMusicPlayerController *)musicPlayer volumeChanged:(float)volume {
    if (!self.panningVolume) {
        self.volumeSlider.value = volume;
    }
}

#pragma mark - MPMediaPickerControllerDelegate

- (void)mediaPickerDidCancel:(MPMediaPickerController *)mediaPicker {
    [mediaPicker dismissViewControllerAnimated:YES completion:nil];
}

- (void)mediaPicker:(MPMediaPickerController *)mediaPicker didPickMediaItems:(MPMediaItemCollection *)mediaItemCollection {
    [[GVMusicPlayerController sharedInstance] setQueueWithItemCollection:mediaItemCollection];
    [[GVMusicPlayerController sharedInstance] play];
    [mediaPicker dismissViewControllerAnimated:YES completion:nil];
}

@end


text:
package io.appium.java_client.imagecomparison;

import static java.util.Optional.ofNullable;

import com.google.common.collect.ImmutableMap;

import java.util.Map;

public class OccurrenceMatchingOptions extends BaseComparisonOptions<OccurrenceMatchingOptions> {
    private Double threshold;

    /**
     * At what normalized threshold to reject an occurrence.
     *
     * @param threshold value in range 0..1. 0.5 is the default value.
     * @return self instance for chaining.
     */
    public OccurrenceMatchingOptions withThreshold(double threshold) {
        this.threshold = threshold;
        return this;
    }

    @Override
    public Map<String, Object> build() {
        final ImmutableMap.Builder<String, Object> builder = ImmutableMap.builder();
        builder.putAll(super.build());
        ofNullable(threshold).map(x -> builder.put("threshold", x));
        return builder.build();
    }
}


text:
package de.upb.s2cx.parser.sql.xml;

public abstract class AbstractXmlAttribute implements XmlValue {

	private String name;

	public AbstractXmlAttribute(String name) {
		super();
		this.name = name;
	}

	public String getName() {
		return name;
	}

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

	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder();
		toString(builder);
		return builder.toString();
	}

	@Override
	public void toString(StringBuilder builder) {
		builder.append(getValue());
		builder.append(" AS ");
		builder.append(name);
	}
}


text:
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;

namespace Cameronism.Csv
{
    sealed internal class DataTableHandler : ReaderBase<DataRow, DataTable>
    {
        public DataTableHandler(char separator) : base(separator) { }

        public override void Serialize(DataTable table, Action<TextWriter, DataRow, int>[] writers, TextWriter destination)
        {
            WriteHeaders(table, writers, destination);

            var firstWriter = writers[0];
            foreach (DataRow row in table.Rows)
            {
                if (!row.IsNull(0))
                {
                    firstWriter.Invoke(destination, row, 0);
                }

                // remaining columns
                for (int i = 1; i < writers.Length; i++)
                {
                    destination.Write(_separator);
                    if (!row.IsNull(i))
                    {
                        writers[i].Invoke(destination, row, i);
                    }
                }
                destination.WriteLine();
            }
        }

        protected override int GetFieldCount(DataTable table) => table.Columns.Count;
        protected override Type GetFieldType(DataTable table, int i) => table.Columns[i].DataType;
        protected override string GetFieldName(DataTable table, int i) => table.Columns[i].ColumnName;

        // would love a more strongly typed way to handle the following (that doesn't do the same under the hood)
        protected override bool GetBoolean(DataRow row, int i) => (bool)row[i];
        protected override byte GetByte(DataRow row, int i) => (byte)row[i];
        protected override decimal GetDecimal(DataRow row, int i) => (decimal)row[i];
        protected override double GetDouble(DataRow row, int i) => (double)row[i];
        protected override float GetFloat(DataRow row, int i) => (float)row[i];
        protected override Guid GetGuid(DataRow row, int i) => (Guid)row[i];
        protected override DateTime GetDateTime(DataRow row, int i) => (DateTime)row[i];
        protected override short GetInt16(DataRow row, int i) => (short)row[i];
        protected override int GetInt32(DataRow row, int i) => (int)row[i];
        protected override long GetInt64(DataRow row, int i) => (long)row[i];
        protected override string GetString(DataRow row, int i) => (string)row[i];
        protected override byte[] GetByteArray(DataRow row, int i) => (byte[])row[i];
    }
}


text:
class AddChangeNotificationsEnabledToUsers < ActiveRecord::Migration[5.1]
  def change
    add_column :users, :change_notifications_enabled, :boolean, default: true
  end
end


text:
// discussion.js

(function($){

    var calli = window.calli || (window.calli={});

    calli.insertDiscussionBadge = function(url, element) {
        return calli.getCurrentUserName().then(function(username){
            if (username && element.offsetWidth > 0) return checkTab(url, element);
        });
    };

    function checkTab(url, element) {
        if (location.search == '?discussion') {
            return calli.ready(calli.getPageUrl()).then(function(url){
                var posts = $(".comment").parent().find("time").map(function(){ return $(this).attr("content"); });
                try {
                    if (posts.length) {
                        window.localStorage.setItem(url, posts.get().join(','));
                    }
                } catch (e) { }
            });
        }
        var a = document.createElement('a');
        a.setAttribute('href', url);
        return calli.getText(a.href).then(function(doc) {
            return handleDiscussion($(element), a.href, doc);
        }, function(){});
    }

    function handleDiscussion(tab, key, data) {
        var posts = $(".comment", data).parent().find("time").map(function(){ return $(this).text(); });
        if (posts.length) {
            var span = $('');
            try {
                if (window.localStorage.getItem(key)) {
                    var seen = window.localStorage.getItem(key).split(',');
                    var newer = posts.filter(function(){
                        for (var i=0; i<seen.length; i++) {
                            if (seen[i] == this)
                                return false;
                        }
                        return true;
                    });
                    if (newer.size()) {
                        span.text(newer.size());
                        tab.prepend(span);
                    }
                } else {
                    span.text(posts.size());
                    tab.prepend(span);
                }
            } catch(e) {
                span.text(posts.size());
                tab.prepend(span);
            }
        }
    }

})(jQuery);


text:
section_name: "Utilities"
---
<div class="reference-body">
  <%= items['/utilities/helpers.*'].compiled_content %>
</div>


text:
package org.apache.jackrabbit.oak.plugins.index.lucene.util.fv;

import java.io.Reader;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenFilter;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.Tokenizer;
import org.apache.lucene.analysis.shingle.ShingleFilter;
import org.apache.lucene.util.Version;

/**
 * {@link Analyzer} for LSH search
 */
public class LSHAnalyzer extends Analyzer {

  private static final int DEFAULT_SHINGLE_SIZE = 4;

  private final int min;
  private final int max;
  private final int hashCount;
  private final int bucketCount;
  private final int hashSetSize;

  private LSHAnalyzer(int min, int max, int hashCount, int bucketCount, int hashSetSize) {
    super();
    this.min = min;
    this.max = max;
    this.hashCount = hashCount;
    this.bucketCount = bucketCount;
    this.hashSetSize = hashSetSize;
  }

  public LSHAnalyzer() {
    this(DEFAULT_SHINGLE_SIZE, DEFAULT_SHINGLE_SIZE, MinHashFilter.DEFAULT_HASH_COUNT, MinHashFilter.DEFAULT_BUCKET_COUNT, MinHashFilter.DEFAULT_HASH_SET_SIZE);
  }

  @Override
  protected TokenStreamComponents createComponents(String fieldName, Reader reader) {
    Tokenizer source = new FVTokenizer(Version.LUCENE_47, reader);
    TokenFilter truncate = new TruncateTokenFilter(source, 5);
    TokenFilter featurePos = new FeaturePositionTokenFilter(truncate);
    ShingleFilter shingleFilter = new ShingleFilter(featurePos, min, max);
    shingleFilter.setTokenSeparator(" ");
    shingleFilter.setOutputUnigrams(false);
    shingleFilter.setOutputUnigramsIfNoShingles(false);
    TokenStream filter = new MinHashFilter(shingleFilter, hashCount, bucketCount, hashSetSize, bucketCount > 1);
    return new TokenStreamComponents(source, filter);
  }

}


text:
Cheveret
========

A Rails library for generating flexible width HTML tables.

_**Cheveret**: (noun) a small English table of the 18th century, having an oblong top, one or two rows of drawers, and slender legs joined near the bottom by a shelf._

Install
-------

Cheveret was developed for Rails 2.3.8 and might work with more recent versions. There are no other dependencies aside from Rails itself.

To install using Bundler simply add the following to your `Gemfile` and run a `bundle install`:

    gem 'cheveret', :git => 'git@github.com:ratecity/cheveret.git'

Usage
-----

Generating HTML tables of data in the views of your Rails application is not very **DRY** even for the simpler of cases. Cheveret allows you to more clearly separate logic and templating and reduce the amount of code in your views.

There are several ways to define the structure of a table using Cheveret, the simplest being via the `tabulatable` method in your `ActiveRecord` models:

    class Book < ActiveRecord::Base
      tabulatable do |t|
        t.flexible :title
        t.column   :author       :width => 200, :flexible => true
        t.column   :release_date :width => 100, :label=> false
        t.sortable :amount,
        t.fixed    :add_to_cart, :width => 120, :display => false
      end

      ...

    end

An instance of `Cheveret::Table` will then be configured on your model, accessible via `.cheveret`.

### Rendering

You can now render a table in your view by using the `cheveret_table` helper:

    = cheveret_table_for @books

If your view should only display a subset of the defined columns in the table (e.g. not display the _add to cart_ button for non-authenticated users), supply either `:only` or `:exclude`:

    = cheveret_table_for @books, :exclude => :add_to_cart

### Header

By default, Cheveret will attempt to use i18n to look up a sensible label for your column headers using the `cheveret.#{object.human_name}.#{column_name}.label` scope, where `object` is the object in which your columns are defined. If a translation is found at `.desc` in the same scope, it will be used as the HTML `title` attribute of the label element.

The default behaviour can be overridden by way of the `:label` option when defining your columns. Prevent the label from being rendered altogether by specifying `:label => false`.

Lastly, you can completely override the markup for each header cell by using the `cheveret_headers_for` helper and supplying a block:

    = cheveret_headers_for @books do |name, column|
      - case name
      - when :add_to_cart
        = image_tag("add_to_cart.png")

In the above example, the block will be called once for each column in the table and render the results. There are two exceptions to this behaviour:

1. if the return value is `nil`, Cheveret will render standard markup using the columns `:label` setting

2. otherwise, if the return value is `false`, no markup will be rendered

### Body

When rendering the table body, Cheveret assumes it's dealing with `ActiveRecord` model objects (or similar) and that you have _named your columns to match your data_. To get a value for each table cell it will call `object.send(column_name)` to each of your objects.

This is sufficient for a list of simple `ActiveRecord` instances, but what if you need to format values, or you want to list something else? Enter the `cheveret_body_for` helper:

    = cheveret_body_for @books do |name, column, book|
      - case name
      - when :amount
        = number_to_currency(book.amount)

This behaves in the same way as `cheveret_header`, except for the additional 3rd argument passed to the block, which gives access to the data object being rendered.

You could, for example, create a column that is an aggregate of more than one attribute:

    = cheveret_body_for @books do |name, column, book|
       - case name
       - when :title
         = "#{book.title} (#{book.edition})"

Or, if you're using _Sunspot_, list stored search results without hitting the database to get model objects:

    = cheveret_body_for @books do |name, column, book|
      = book.stored(name)

Todo
----

* Make the documentation tell fewer lies
* Support i18n translations for table headers
* Handle exceeding table width, drop columns
* Better support for ActiveRecord model objects
* Write some tests

Note on Patches/Pull Requests
-----------------------------

* Fork the project.
* Make your feature addition or bug fix.
* Add tests for it. This is important so I don't break it in a
  future version unintentionally.
* Commit, do not mess with rakefile, version, or history.
  (if you want to have your own version, that is fine but bump version in a commit by itself I can ignore when I pull)
* Send me a pull request. Bonus points for topic branches.

Maintainers & Contributors
--------------------------

* Ben Caldwell - http://github.com/lankz

Copyright
---------

Copyright (c) 2010 RateCity. See LICENSE for details.